major change in game creation, fixed some bugs

This commit is contained in:
Jannes Höke 2016-03-11 09:23:53 +01:00
parent c144fb7c3b
commit 367d16e85f
4 changed files with 117 additions and 74 deletions

111
bot.py
View file

@ -27,19 +27,17 @@ help_text = "Follow these steps:\n\n" \
"1. Add this bot to a group\n" \ "1. Add this bot to a group\n" \
"2. In the group, start a new game with /new or join an already" \ "2. In the group, start a new game with /new or join an already" \
" running game with /join\n" \ " running game with /join\n" \
"3. The bot will send a link into the group. " \ "3. After at least two players have joined, start the game with" \
"Click the link and then on the <b>Start</b> " \ " /start\n" \
"button to join the game.\n" \ "4. Type <code>@mau_mau_bot</code> into your chat box and hit " \
"4. Go back to the group chat and wait for at least one " \ "space, or click the <code>via @mau_mau_bot</code> text above " \
"other person to join the game (you can also play alone, " \ "messages. You will see the cards that you can play, any extra " \
"but it's no fun)\n" \
"5. Type <code>@mau_mau_bot</code> into your chat box and hit " \
"space. You will see the cards that you can play, any extra " \
"options like drawing, your other cards (those you can not play " \ "options like drawing, your other cards (those you can not play " \
"at the moment) and an option to see the current game state.\n\n" \ "at the moment) and an option to see the current game state. " \
"Tap an option to execute the selected action. \n\n" \
"Players can join the game at any time, though you currently " \ "Players can join the game at any time, though you currently " \
"can not play more than one game at a time. To leave a game, " \ "can not play more than one game at a time. To leave a game, " \
"send /leave into the group.\n" \ "use /leave.\n" \
"If you enjoy this bot, " \ "If you enjoy this bot, " \
"<a href=\"https://telegram.me/storebot?start=mau_mau_bot\">" \ "<a href=\"https://telegram.me/storebot?start=mau_mau_bot\">" \
"rate me</a>, join the " \ "rate me</a>, join the " \
@ -89,11 +87,10 @@ def new_game(bot, update):
if update.message.chat.type == 'private': if update.message.chat.type == 'private':
help(bot, update) help(bot, update)
else: else:
link = gm.generate_invite_link(u.bot.getMe().username, chat_id) gm.new_game(chat_id)
bot.sendMessage(chat_id, bot.sendMessage(chat_id,
text="Click this link and press the Start button to" text="Created a new game! Join the game with /join "
" join the game: %s" % link, "and start the game with /start")
disable_web_page_preview=True)
if botan: if botan:
botan.track(update.message, 'New games') botan.track(update.message, 'New games')
@ -104,19 +101,27 @@ def join_game(bot, update):
if update.message.chat.type == 'private': if update.message.chat.type == 'private':
help(bot, update) help(bot, update)
else: else:
link = gm.generate_invite_link(u.bot.getMe().username, chat_id, joined = gm.join_game(chat_id, update.message.from_user)
join=True) if joined:
bot.sendMessage(chat_id, bot.sendMessage(chat_id,
text="Click this link and press the Start button to" text="Joined the game",
" join the game: %s" % link, reply_to_message_id=update.message.message_id)
disable_web_page_preview=True) elif joined is None:
bot.sendMessage(chat_id,
text="No game is running at the moment. "
"Create a new game with /new",
reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(chat_id,
text="You already joined the game. Start the game "
"with /start",
reply_to_message_id=update.message.message_id)
def leave_game(bot, update): def leave_game(bot, update):
""" Handler for the /leave command """ """ Handler for the /leave command """
chat_id = update.message.chat_id chat_id = update.message.chat_id
game_id = gm.chatid_gameid[chat_id] game = gm.chatid_game[chat_id]
game = gm.gameid_game[game_id]
user = update.message.from_user user = update.message.from_user
if game.current_player.user.id == user.id: if game.current_player.user.id == user.id:
@ -127,30 +132,27 @@ def leave_game(bot, update):
bot.sendMessage(chat_id, text="Okay") bot.sendMessage(chat_id, text="Okay")
def start(bot, update, args): def start_game(bot, update):
""" Handler for the /start command """ """ Handler for the /start command """
if args:
game_id = args[0] # Contains the game id
gm.join_game(game_id, update.message.from_user)
game = gm.gameid_game[game_id]
groupchat = gm.chatid_gameid[game_id]
bot.sendMessage(update.message.chat_id,
text="Joined game! Please go back to the group chat "
"and play there, via inline commands.")
bot.sendMessage(groupchat,
text=update.message.from_user.first_name +
" joined the game!")
# Check if user is the first player to join and if, show the first card if update.message.chat.type != 'private':
if game.current_player is game.current_player.next: # Show the first card
chat_id = update.message.chat_id
game = gm.chatid_game[chat_id]
if game.current_player in (None, game.current_player.next):
bot.sendMessage(chat_id, text="At least two players must /join "
"the game before you can start it")
elif game.started:
bot.sendMessage(chat_id, text="The game has already started")
else:
game.play_card(game.last_card) game.play_card(game.last_card)
bot.sendPhoto(groupchat, game.started = True
bot.sendPhoto(chat_id,
photo=game.last_card.get_image_link(), photo=game.last_card.get_image_link(),
caption="First Card") caption="First Card")
else: else:
bot.sendMessage(update.message.chat_id, help(bot, update)
text="Please invite me to a group and "
"issue the /new command there.")
def inline(bot, update): def inline(bot, update):
@ -169,6 +171,13 @@ def help(bot, update):
disable_web_page_preview=True) disable_web_page_preview=True)
def news(bot, update):
""" Handler for the /news command """
bot.sendMessage(update.message.chat_id,
text="All news here: https://telegram.me/unobotupdates",
disable_web_page_preview=True)
def reply_to_query(bot, update): def reply_to_query(bot, update):
""" Builds the result list for inline queries and answers to the client """ """ Builds the result list for inline queries and answers to the client """
results = list() results = list()
@ -181,7 +190,9 @@ def reply_to_query(bot, update):
except KeyError: except KeyError:
add_no_game(results) add_no_game(results)
else: else:
if user_id == game.current_player.user.id: if not game.started:
add_not_started(results)
elif user_id == game.current_player.user.id:
if game.choosing_color: if game.choosing_color:
add_choose_color(results) add_choose_color(results)
else: else:
@ -245,6 +256,16 @@ def add_no_game(results):
) )
def add_not_started(results):
results.append(
InlineQueryResultArticle(
"nogame",
title="The game wasn't started yet",
message_text='Start the game with /start'
)
)
def add_draw(player, results, could_play_card): def add_draw(player, results, could_play_card):
results.append( results.append(
InlineQueryResultArticle( InlineQueryResultArticle(
@ -328,7 +349,7 @@ def process_result(bot, update):
game = gm.userid_game[user.id] game = gm.userid_game[user.id]
player = gm.userid_player[user.id] player = gm.userid_player[user.id]
result_id = update.chosen_inline_result.result_id result_id = update.chosen_inline_result.result_id
chat_id = gm.chatid_gameid[game] chat_id = gm.chatid_game[game]
logger.debug("Selected result: " + result_id) logger.debug("Selected result: " + result_id)
if result_id in ('hand', 'gameinfo', 'nogame'): if result_id in ('hand', 'gameinfo', 'nogame'):
@ -358,6 +379,9 @@ def do_play_card(bot, chat_id, game, player, result_id, user):
if len(player.cards) == 0: if len(player.cards) == 0:
gm.leave_game(user) gm.leave_game(user)
bot.sendMessage(chat_id, text="Player won!") bot.sendMessage(chat_id, text="Player won!")
if game.current_player is game.current_player.next:
bot.sendMessage(chat_id, text="Game ended!")
gm.end_game(chat_id)
if botan: if botan:
botan.track(Message(randint(1, 1000000000), user, datetime.now(), botan.track(Message(randint(1, 1000000000), user, datetime.now(),
@ -398,11 +422,12 @@ def do_call_bluff(bot, chat_id, game, player):
# Add all handlers to the dispatcher and run the bot # Add all handlers to the dispatcher and run the bot
dp.addTelegramInlineHandler(inline) dp.addTelegramInlineHandler(inline)
dp.addTelegramCommandHandler('start', start) dp.addTelegramCommandHandler('start', start_game)
dp.addTelegramCommandHandler('new', new_game) dp.addTelegramCommandHandler('new', new_game)
dp.addTelegramCommandHandler('join', join_game) dp.addTelegramCommandHandler('join', join_game)
dp.addTelegramCommandHandler('leave', leave_game) dp.addTelegramCommandHandler('leave', leave_game)
dp.addTelegramCommandHandler('help', help) dp.addTelegramCommandHandler('help', help)
dp.addTelegramCommandHandler('news', news)
dp.addErrorHandler(error) dp.addErrorHandler(error)
start_bot(u) start_bot(u)

View file

@ -10,6 +10,7 @@ class Game(object):
reversed = False reversed = False
draw_counter = 0 draw_counter = 0
choosing_color = False choosing_color = False
started = False
def __init__(self): def __init__(self):
self.deck = Deck() self.deck = Deck()

View file

@ -1,54 +1,66 @@
from uuid import uuid4
import logging import logging
from game import Game from game import Game
from player import Player from player import Player
LINK_PATTERN = 'https://telegram.me/%s?start=%s'
class GameManager(object): class GameManager(object):
""" Manages all running games by using a confusing amount of dicts """ """ Manages all running games by using a confusing amount of dicts """
def __init__(self): def __init__(self):
self.gameid_game = dict() self.chatid_game = dict()
self.userid_game = dict() self.userid_game = dict()
self.chatid_gameid = dict() # Goes both ways
self.userid_player = dict() self.userid_player = dict()
self.logger = logging.getLogger(__name__) self.logger = logging.getLogger(__name__)
def generate_invite_link(self, bot_name, chat_id, join=False): def new_game(self, chat_id):
""" """
Generate a game join link with a unique ID and connect the game to the Generate a game join link with a unique ID and connect the game to the
group chat group chat
""" """
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.logger.info("Creating new game with id " + str(chat_id))
self.gameid_game[game_id] = game game = Game()
self.chatid_gameid[chat_id] = game_id self.chatid_game[chat_id] = game
self.chatid_gameid[game_id] = chat_id self.chatid_game[game] = chat_id
self.chatid_gameid[game] = chat_id
return LINK_PATTERN % (bot_name, game_id) def join_game(self, chat_id, user):
def join_game(self, game_id, user):
""" Create a player from the Telegram user and add it to the game """ """ Create a player from the Telegram user and add it to the game """
self.logger.info("Joining game with id " + game_id) self.logger.info("Joining game with id " + str(chat_id))
game = self.gameid_game[game_id] try:
player = Player(game, user) game = self.chatid_game[chat_id]
self.userid_player[user.id] = player except KeyError:
self.userid_game[user.id] = game 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
def leave_game(self, user): def leave_game(self, user):
""" Remove a player from its current game """ """ Remove a player from its current game """
player = self.userid_player[user.id] try:
player = self.userid_player[user.id]
player.leave() player.leave()
del self.userid_player[user.id] del self.userid_player[user.id]
del self.userid_game[user.id] del self.userid_game[user.id]
return True
except KeyError:
return False
def end_game(self, chat_id):
"""
Generate a game join link with a unique ID and connect the game to the
group chat
"""
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]

View file

@ -77,7 +77,11 @@ class Player(object):
self.logger.debug("Last card was " + str(last)) self.logger.debug("Last card was " + str(last))
for card in self.cards: cards = self.cards
if self.drew:
cards = self.cards[-1:]
for card in cards:
if self.card_playable(card, playable): if self.card_playable(card, playable):
self.logger.debug("Matching!") self.logger.debug("Matching!")
playable.append(card) playable.append(card)
@ -85,8 +89,9 @@ class Player(object):
# You may only play a +4 if it's the only card you can play # You may only play a +4 if it's the only card you can play
self.bluffing = bool(len(playable) - 1) self.bluffing = bool(len(playable) - 1)
# You may not play a +4 as your last card # You may not play a chooser or +4 as your last card
if len(self.cards) == 1 and self.cards[0].special == c.DRAW_FOUR: if len(self.cards) == 1 and (self.cards[0].special == c.DRAW_FOUR
or self.cards[0].special == c.CHOOSE):
return list() return list()
return playable return playable