2016-02-29 08:53:59 +08:00
|
|
|
import logging
|
|
|
|
|
2016-02-29 06:57:24 +08:00
|
|
|
from game import Game
|
|
|
|
from player import Player
|
|
|
|
|
|
|
|
|
|
|
|
class GameManager(object):
|
2016-03-08 09:50:24 +08:00
|
|
|
""" Manages all running games by using a confusing amount of dicts """
|
2016-02-29 06:57:24 +08:00
|
|
|
|
|
|
|
def __init__(self):
|
2016-03-11 16:23:53 +08:00
|
|
|
self.chatid_game = dict()
|
2016-02-29 06:57:24 +08:00
|
|
|
self.userid_game = dict()
|
|
|
|
self.userid_player = dict()
|
2016-02-29 08:53:59 +08:00
|
|
|
self.logger = logging.getLogger(__name__)
|
2016-02-29 06:57:24 +08:00
|
|
|
|
2016-03-11 16:23:53 +08:00
|
|
|
def new_game(self, chat_id):
|
2016-03-08 09:50:24 +08:00
|
|
|
"""
|
|
|
|
Generate a game join link with a unique ID and connect the game to the
|
|
|
|
group chat
|
|
|
|
"""
|
2016-02-29 06:57:24 +08:00
|
|
|
|
2016-03-11 16:23:53 +08:00
|
|
|
self.logger.info("Creating new game with id " + str(chat_id))
|
|
|
|
game = Game()
|
|
|
|
self.chatid_game[chat_id] = game
|
|
|
|
self.chatid_game[game] = chat_id
|
2016-02-29 06:57:24 +08:00
|
|
|
|
2016-03-11 16:23:53 +08:00
|
|
|
def join_game(self, chat_id, user):
|
2016-03-08 09:50:24 +08:00
|
|
|
""" Create a player from the Telegram user and add it to the game """
|
2016-03-11 16:23:53 +08:00
|
|
|
self.logger.info("Joining game with id " + str(chat_id))
|
|
|
|
try:
|
|
|
|
game = self.chatid_game[chat_id]
|
|
|
|
except KeyError:
|
|
|
|
return None
|
|
|
|
if user.id not in self.userid_game or \
|
|
|
|
self.userid_game[user.id] is not game:
|
|
|
|
self.leave_game(user)
|
|
|
|
player = Player(game, user)
|
|
|
|
self.userid_player[user.id] = player
|
|
|
|
self.userid_game[user.id] = game
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
2016-02-29 19:16:12 +08:00
|
|
|
|
|
|
|
def leave_game(self, user):
|
2016-03-08 09:50:24 +08:00
|
|
|
""" Remove a player from its current game """
|
2016-03-11 16:23:53 +08:00
|
|
|
try:
|
|
|
|
player = self.userid_player[user.id]
|
|
|
|
|
|
|
|
player.leave()
|
|
|
|
del self.userid_player[user.id]
|
|
|
|
del self.userid_game[user.id]
|
|
|
|
return True
|
|
|
|
except KeyError:
|
|
|
|
return False
|
2016-02-29 19:16:12 +08:00
|
|
|
|
2016-03-11 16:23:53 +08:00
|
|
|
def end_game(self, chat_id):
|
|
|
|
"""
|
|
|
|
Generate a game join link with a unique ID and connect the game to the
|
|
|
|
group chat
|
|
|
|
"""
|
2016-02-29 19:16:12 +08:00
|
|
|
|
2016-03-11 16:23:53 +08:00
|
|
|
self.logger.info("Game with id " + str(chat_id) + " ended")
|
|
|
|
game = self.chatid_game[chat_id]
|
|
|
|
self.leave_game(game.current_player.user)
|
|
|
|
del self.chatid_game[chat_id]
|
|
|
|
del self.chatid_game[game]
|