Permalink
Browse files

sdf

  • Loading branch information...
1 parent 0ca1233 commit d1ffa3284529010330bd02f1825a46a5f7b9c439 @alexbft committed May 15, 2011
View
@@ -1 +1,2 @@
-*.pyc
+*.pyc
+*.suo
View
@@ -46,6 +46,7 @@
<Content Include="static\js\scripts.js" />
<Content Include="static\styles.css" />
<Content Include="templates\js\chat.html" />
+ <Content Include="templates\js\loc_dungeon.html" />
<Content Include="templates\js\loc_arena.html" />
<Content Include="templates\js\loc_default.html" />
<Content Include="templates\js\loc_fight.html" />
View
@@ -17,9 +17,7 @@ class RejectException(Exception):
"Такой вызов действия возможен, но по каким-то причинам действие не может быть выполнено"
pass
-class Action:
- "Хэндлеры для действий"
-
+class BaseAction:
def __init__(self, user, q):
''' Конструктор.
User user - пользователь, который производит действие
@@ -29,8 +27,8 @@ def __init__(self, user, q):
self.q = q
self.action = q["action"]
action_name = str(self.action)
- if not action_name.startswith("_") and action_name in Action.__dict__:
- Action.__dict__[action_name](self)
+ if not action_name.startswith("_") and action_name in self.__class__.__dict__:
+ self._result = self.__class__.__dict__[action_name](self)
else:
self._error("no such action")
@@ -50,7 +48,10 @@ def _reject(self, reason):
str reason - причина.
'''
raise RejectException(reason)
-
+
+class Action(BaseAction):
+ "Хэндлеры для действий"
+
def go_arena(self):
' Переход на арену '
self._checkloc("default")
@@ -132,10 +133,25 @@ def move(self):
fighter.move = {"card": card.id, "cast_target": cast_target.id, "atk_target": atk_target.id}
else:
fighter.move = {"card": None, "atk_target": atk_target.id}
+ fighter.slowpoke = False
fighter.fight.check_end_turn()
def dungeon_search(self):
' Осмотр подземелья '
# STUB
self._checkloc("dungeon")
- Fight.create([self.user], [mob.get("Slime"), mob.get("Slime")])
+ Fight.create([self.user], [mob.get("Slime"), mob.get("Slime")])
+
+class QAction(BaseAction):
+
+ def stats_up(self):
+ stat = self.q["stat"]
+ up = self.q.get("up", 1)
+ if stat not in ["atk", "def", "matk", "mdef"]:
+ self._error("Wrong stat")
+ if self.user['free_stats'] < up:
+ self._error("No free stats")
+ self.user['free_stats'] -= up
+ self.user[stat] += up
+ self.user.save()
+ return self.user.js_stats()
View
@@ -0,0 +1,10 @@
+# coding: utf-8
+
+# Òåêóùèé êîíòåêñò çàïðîñà.
+# (c) alexbft 2011
+
+current = None
+
+def current_user():
+ global current
+ return current.current_user
View
@@ -19,6 +19,7 @@ def User(u):
return user.User(u)
class Fight:
+ TURN_TIME_LIMIT = 60
def __init__(self, src):
''' Конструктор.
@@ -68,8 +69,10 @@ def save(self):
db().fight.save(self.js_save())
def run_time_checks(self):
- ' Всякие проверки при создании объекта - stub '
- pass
+ ' Всякие проверки при создании объекта '
+ if self.status == "active" and now() > self.turn_time_limit:
+ self.mark_slowpokes()
+ self.check_end_turn()
def add_fighter(self, unit, team_id):
''' Добавляет файтера в битву.
@@ -112,6 +115,7 @@ def begin_turn(self):
eff.onturn()
self.check_fight_over()
if not self.over():
+ self.turn_time_limit = now() + self.TURN_TIME_LIMIT
self.check_end_turn()
def update(self):
@@ -126,7 +130,7 @@ def log(self, message, params = None):
def channel(self):
''' Возвращает название канала битвы '''
- return "$fight" + str(self.id)
+ return "$fight$" + str(self.id)
def check_end_turn(self):
''' Проверяет на конец хода и делает update '''
@@ -214,6 +218,10 @@ def drop_old_effects(self):
def check_fight_over(self):
''' Проверка на конец битвы '''
+ if self.turn >= 100:
+ self.log("Битва слишком затянулась. Никакая сторона не смогла одержать победу!")
+ self.fight_over(-1)
+ return
p0 = sum(1 for f in self.p[0] if f.alive)
p1 = sum(1 for f in self.p[1] if f.alive)
if p0 == 0 and p1 == 0:
@@ -222,6 +230,9 @@ def check_fight_over(self):
self.fight_over(1)
elif p1 == 0:
self.fight_over(0)
+ elif all(not f.alive or f.slowpoke for f in self.fighters()):
+ self.log("Все участники спят...")
+ self.fight_over(-1)
def fight_over(self, winner):
''' Завершить битву.
@@ -233,4 +244,38 @@ def fight_over(self, winner):
for f in self.fighters():
f.move = None
self.log(u"Битва окончена!")
- self.update()
+ if winner != -1:
+ sumlev = [sum(f.level for f in team if f._type == "user") for team in self.p]
+ for f in self.fighters():
+ if f._type == "user":
+ owner = user.User.get(f.user_id)
+ if owner != None:
+ reward = 0
+ for enemy in f.enemies():
+ if f.team_id == winner:
+ if enemy._type == "mob":
+ reward += 10 * enemy.level
+ elif enemy._type == "user":
+ reward += 25 * enemy.level * owner.reward_factor(enemy.user_id)
+ else:
+ if enemy._type == "user":
+ reward += 10 * enemy.level * owner.reward_factor(enemy.user_id)
+ reward = int(round(reward * f.level / sumlev[f.team_id]))
+ if reward > 0:
+ exp_reward = reward
+ gold_reward = reward * 5
+ if f.team_id == winner:
+ reason = u"За победу в битве"
+ else:
+ reason = u"За участие в битве"
+ owner.private_message(u"%s вы получаете %s опыта и %s золотых монет." % (reason, exp_reward, gold_reward))
+ owner["gold"] += gold_reward
+ owner.give_exp(exp_reward)
+ owner.save()
+ self.update()
+
+ def mark_slowpokes(self):
+ ' Помечает игроков, которые не сходили за тайм лимит. Их больше не ждем (пока они не проснутся). '
+ for f in self.fighters():
+ if f.should_move() and not f.move:
+ f.slowpoke = True
View
@@ -85,7 +85,7 @@ def js(self):
' Для пользователя - контроллера файтера '
res = self.js_save()
res["deck"] = len(res["deck"])
- res["should_move"] = self.should_move()
+ res["can_move"] = self.can_move()
res["effects"] = [eff.js() for eff in self.effects]
return res
@@ -119,7 +119,7 @@ def can_move(self):
def should_move(self):
' Должны ли мы ждать, пока файтер сделает ход '
- return self._type == "user" and self.can_move()
+ return self._type == "user" and self.can_move() and not self.slowpoke
def allies(self):
' Список союзников '
View
@@ -47,7 +47,7 @@ def arena(user):
def fight(user):
fight = user.fight()
fighter = user.fighter()
- res = {"turn": fight.turn, "start": fight.start, "status": fight.status, "winner": fight.winner}
+ res = {"turn": fight.turn, "time_left": fight.turn_time_limit - now(), "status": fight.status, "winner": fight.winner}
res["me"] = fighter.js()
res["allies"] = [f.js_ally() for f in fight.p[fighter.team_id]]
res["enemies"] = [f.js_enemy() for f in fight.p[1 - fighter.team_id]]
View
@@ -12,13 +12,15 @@
import os.path
import json
from chat import Chat
-from actions import Action, ActionException, RejectException
+from actions import Action, QAction, ActionException, RejectException
+import context
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
try:
+ context.current = self
# TODO: sessions
- u = User.get(ObjectId(self.get_secure_cookie("user")))
+ u = User.get(ObjectId(self.get_secure_cookie("user")), False)
u.update_activity()
return u
except:
@@ -87,6 +89,11 @@ class ActionHandler(QueryHandler):
def handle(self, q):
Action(self.current_user, q)
return self.current_user.js_all()
+
+class QActionHandler(QueryHandler):
+ @tornado.web.authenticated
+ def handle(self, q):
+ return QAction(self.current_user, q)._result
settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static"),
@@ -99,7 +106,8 @@ def handle(self, q):
(r"/login", LoginHandler),
(r"/templates.js", ClientTemplatesHandler),
(r"/chat", ChatHandler),
- (r"/action", ActionHandler)
+ (r"/action", ActionHandler),
+ (r"/qaction", QActionHandler)
], **settings)
if __name__ == "__main__":
View
@@ -14,13 +14,29 @@ def get(id):
res.id = id
return res
+def stats_average(level):
+ return 10 + level * 1.5
+
+def hp_average(level):
+ return 100 * level_multiplier(level)
+
class Mob:
- stats = {"atk": 10, "def": 10, "matk": 10, "mdef": 10, "hp_max": 100}
+ stats = {}
level = 1
name = "Unknown"
spells = []
cast_chance = 1
+ def __init__(self):
+ self.auto_stats()
+
+ def auto_stats(self):
+ stats = dict(self.stats)
+ for key in ["atk", "def", "matk", "mdef"]:
+ stats[key] = int(self.stats.get(key, 1) * stats_average(self.level))
+ stats["hp_max"] = int(self.stats.get("hp_max", 1) * hp_average(self.level))
+ self.stats = stats
+
def run_ai(self, fighter):
self.fighter = fighter
self.spell = None
@@ -31,7 +47,6 @@ def run_ai(self, fighter):
def ai(self):
if len(self.spells) > 0 and rnd() < self.cast_chance:
- log_debug('casting!')
self.cast(random.choice(self.spells))
def cast(self, spell_id, target = None):
@@ -59,7 +74,7 @@ def random_enemy(self):
return None
class Slime(Mob):
- stats = {"atk": 5, "def": 5, "matk": 5, "mdef": 5, "hp_max": 50}
+ stats = {"atk": 0.5, "def": 0.5, "hp_max": 0.5}
name = "Slime"
spells = ["Heal"]
cast_chance = 0.3
Oops, something went wrong.

0 comments on commit d1ffa32

Please sign in to comment.