2016-02-29 06:57:24 +08:00
|
|
|
from uuid import uuid4
|
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
|
|
|
|
|
|
|
|
LINK_PATTERN = 'https://telegram.me/%s?start=%s'
|
|
|
|
|
|
|
|
|
|
|
|
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):
|
|
|
|
self.gameid_game = dict()
|
|
|
|
self.userid_game = dict()
|
2016-03-08 09:50:24 +08:00
|
|
|
self.chatid_gameid = dict() # Goes both ways
|
2016-02-29 06:57:24 +08:00
|
|
|
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-09 18:31:38 +08:00
|
|
|
def generate_invite_link(self, bot_name, chat_id, join=False):
|
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-03-09 18:31:38 +08:00
|
|
|
if join and chat_id in self.chatid_gameid:
|
|
|
|
game_id = self.chatid_gameid[chat_id]
|
|
|
|
else:
|
|
|
|
game_id = str(uuid4())
|
|
|
|
game = Game()
|
|
|
|
|
|
|
|
self.logger.info("Creating new game with id " + game_id)
|
|
|
|
self.gameid_game[game_id] = game
|
|
|
|
self.chatid_gameid[chat_id] = game_id
|
|
|
|
self.chatid_gameid[game_id] = chat_id
|
|
|
|
self.chatid_gameid[game] = chat_id
|
2016-02-29 06:57:24 +08:00
|
|
|
|
|
|
|
return LINK_PATTERN % (bot_name, game_id)
|
|
|
|
|
|
|
|
def join_game(self, game_id, user):
|
2016-03-08 09:50:24 +08:00
|
|
|
""" Create a player from the Telegram user and add it to the game """
|
2016-02-29 08:53:59 +08:00
|
|
|
self.logger.info("Joining game with id " + game_id)
|
2016-02-29 06:57:24 +08:00
|
|
|
game = self.gameid_game[game_id]
|
|
|
|
player = Player(game, user)
|
|
|
|
self.userid_player[user.id] = player
|
|
|
|
self.userid_game[user.id] = game
|
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-02-29 19:16:12 +08:00
|
|
|
player = self.userid_player[user.id]
|
|
|
|
|
|
|
|
player.leave()
|
|
|
|
del self.userid_player[user.id]
|
|
|
|
del self.userid_game[user.id]
|
|
|
|
|