Ejemplo n.º 1
0
def onText(bot, update):

    chat = update.message.chat
    user = update.message.from_user
    try:
        game = gm.chatid_games[chat.id][-1]
    except (KeyError, IndexError):
        return
    if game.started and game.last_card.value == c.SEVEN and not (
            update.message.text.startswith("Drawing")
            or update.message.text == "Pass"):
        send_async(bot,
                   chat.id,
                   text=__(
                       "{name} falou durante o 7 e comprou uma carta",
                       multi=game.translate).format(name=display_name(user)))
        player = gm.player_for_user_in_chat(user, chat)
        logger.info(
            "Add one card for {name}".format(name=display_name(player.user)))
        try:
            player.draw_serven()
        except DeckEmptyError:
            send_async(bot,
                       chat.id,
                       text=__("Não há mais cartas para compra",
                               multi=game.translate))
Ejemplo n.º 2
0
def process_result(bot, update, job_queue):
    """
    Handler for chosen inline results.
    Checks the players actions and acts accordingly.
    """
    try:
        user = update.chosen_inline_result.from_user
        player = gm.userid_current[user.id]
        game = player.game
        result_id = update.chosen_inline_result.result_id
        chat = game.chat
    except (KeyError, AttributeError):
        return

    logger.debug("Selected result: " + result_id)

    result_id, anti_cheat = result_id.split(':')
    last_anti_cheat = player.anti_cheat
    player.anti_cheat += 1

    if result_id in ('hand', 'gameinfo', 'nogame'):
        return
    elif result_id.startswith('mode_'):
        # First 5 characters are 'mode_', the rest is the gamemode.
        mode = result_id[5:]
        game.set_mode(mode)
        logger.info("Gamemode changed to {mode}".format(mode=mode))
        send_async(bot,
                   chat.id,
                   text=__("Gamemode changed to {mode}".format(mode=mode)))
        return
    elif len(result_id) == 36:  # UUID result
        return
    elif int(anti_cheat) != last_anti_cheat:
        send_async(bot,
                   chat.id,
                   text=__("Cheat attempt by {name}",
                           multi=game.translate).format(
                               name=display_name(player.user)))
        return
    elif result_id == 'call_bluff':
        reset_waiting_time(bot, player)
        do_call_bluff(bot, player)
    elif result_id == 'draw':
        reset_waiting_time(bot, player)
        do_draw(bot, player)
    elif result_id == 'pass':
        game.turn()
    elif result_id in c.COLORS:
        game.choose_color(result_id)
    else:
        reset_waiting_time(bot, player)
        do_play_card(bot, player, result_id)

    if game_is_running(game):
        send_async(bot,
                   chat.id,
                   text=__("Next player: {name}", multi=game.translate).format(
                       name=display_name(game.current_player.user)))
        start_player_countdown(bot, game, job_queue)
Ejemplo n.º 3
0
def skip_player(bot, update):
    """Handler for the /skip command"""
    chat = update.message.chat
    user = update.message.from_user

    player = gm.player_for_user_in_chat(user, chat)
    if not player:
        send_async(bot, chat.id,
                   text=_("You are not playing in a game in this chat."))
        return

    game = player.game
    skipped_player = game.current_player
    next_player = game.current_player.next

    started = skipped_player.turn_started
    now = datetime.now()
    delta = (now - started).seconds

    if delta < skipped_player.waiting_time:
        send_async(bot, chat.id,
                   text=_("Please wait {time} seconds")
                   .format(time=(skipped_player.waiting_time - delta)),
                   reply_to_message_id=update.message.message_id)

    elif skipped_player.waiting_time > 0:
        skipped_player.anti_cheat += 1
        skipped_player.waiting_time -= 30
        try:
            skipped_player.draw()
        except DeckEmptyError:
            pass

        send_async(bot, chat.id,
                   text=__("Waiting time to skip this player has "
                           "been reduced to {time} seconds.\n"
                           "Next player: {name}", game.translate)
                   .format(time=skipped_player.waiting_time,
                           name=display_name(next_player.user)))
        game.turn()

    else:
        try:
            gm.leave_game(skipped_player.user, chat)
            send_async(bot, chat.id,
                       text=__("{name1} was skipped four times in a row "
                               "and has been removed from the game.\n"
                               "Next player: {name2}", game.translate)
                       .format(name1=display_name(skipped_player.user),
                               name2=display_name(next_player.user)))

        except NotEnoughPlayersError:
            send_async(bot, chat.id,
                       text=__("{name} was skipped four times in a row "
                               "and has been removed from the game.\n"
                               "The game ended.", game.translate)
                       .format(name=display_name(skipped_player.user)))

            gm.end_game(chat.id, skipped_player.user)
Ejemplo n.º 4
0
def leave_game(bot, update):
    """Handler for the /leave command"""
    chat = update.message.chat
    user = update.message.from_user

    player = gm.player_for_user_in_chat(user, chat)

    if player is None:
        send_async(bot,
                   chat.id,
                   text=_("You are not playing in a game in "
                          "this group."),
                   reply_to_message_id=update.message.message_id)
        return

    game = player.game
    user = update.message.from_user

    try:
        gm.leave_game(user, chat)

    except NoGameInChatError:
        send_async(bot,
                   chat.id,
                   text=_("You are not playing in a game in "
                          "this group."),
                   reply_to_message_id=update.message.message_id)

    except NotEnoughPlayersError:
        gm.end_game(chat, user)
        send_async(bot, chat.id, text=__("Game ended!", multi=game.translate))

    else:
        if game.started:
            # send message to indicate the game has randomly choosen the color
            if game._randomed_color:
                send_async(bot,
                           chat.id,
                           text=__(
                               "Color randomly choosen to: {col}",
                               multi=game.translate).format(
                                   col=c.COLOR_ICONS[game.last_card.color]),
                           reply_to_message_id=update.message.message_id)
            send_async(
                bot,
                chat.id,
                text=__("Okay. Next Player: {name}",
                        multi=game.translate).format(
                            name=display_name(game.current_player.user)),
                reply_to_message_id=update.message.message_id)
        else:
            send_async(
                bot,
                chat.id,
                text=__("{name} left the game before it started.",
                        multi=game.translate).format(name=display_name(user)),
                reply_to_message_id=update.message.message_id)
Ejemplo n.º 5
0
def process_result(bot, update):
    """
    Handler for chosen inline results.
    Checks the players actions and acts accordingly.
    """
    try:
        user = update.chosen_inline_result.from_user
        player = gm.userid_current[user.id]
        game = player.game
        result_id = update.chosen_inline_result.result_id
        chat = game.chat
    except (KeyError, AttributeError):
        return

    logger.debug("Selected result: " + result_id)

    result_id, anti_cheat = result_id.split(':')
    last_anti_cheat = player.anti_cheat
    player.anti_cheat += 1

    if result_id in ('hand', 'gameinfo', 'nogame'):
        return
    elif len(result_id) == 36:  # UUID result
        return
    elif int(anti_cheat) != last_anti_cheat:
        send_async(bot,
                   chat.id,
                   text=__("Cheat attempt by {name}",
                           multi=game.translate).format(
                               name=display_name(player.user)))
        return
    elif result_id == 'call_bluff':
        reset_waiting_time(bot, player)
        do_call_bluff(bot, player)
    elif result_id == 'draw':
        reset_waiting_time(bot, player)
        do_draw(bot, player)
    elif result_id == 'pass':
        game.turn()
    elif result_id in c.COLORS:
        try:
            game.choose_color(result_id)
        except:
            pass
    else:
        reset_waiting_time(bot, player)
        do_play_card(bot, player, result_id)

    if game in gm.chatid_games.get(chat.id, list()):
        send_async(bot,
                   chat.id,
                   text=__("Next player: {name}", multi=game.translate).format(
                       name=display_name(game.current_player.user)))
Ejemplo n.º 6
0
def leave_game(bot, update):
    """Handler for the /leave command"""
    chat = update.message.chat
    user = update.message.from_user

    player = gm.player_for_user_in_chat(user, chat)

    if player is None:
        send_async(bot,
                   chat.id,
                   text=_("You are not playing in a game in "
                          "this group."),
                   reply_to_message_id=update.message.message_id)
        return

    game = player.game
    user = update.message.from_user

    try:
        gm.leave_game(user, chat)

    except NoGameInChatError:
        send_async(bot,
                   chat.id,
                   text=_("You are not playing in a game in "
                          "this group."),
                   reply_to_message_id=update.message.message_id)

    except NotEnoughPlayersError:
        gm.end_game(chat, user)
        send_async(bot,
                   chat.id,
                   text=__("chalo hogaya aaj ka, back to bihar.",
                           multi=game.translate))

    else:
        if game.started:
            send_async(bot,
                       chat.id,
                       text="Katai Bihari. Next Player: {name}".format(
                           name=display_name(game.current_player.user)),
                       reply_to_message_id=update.message.message_id)
        else:
            send_async(
                bot,
                chat.id,
                text=__("{name} bihar laut gaye.",
                        multi=game.translate).format(name=display_name(user)),
                reply_to_message_id=update.message.message_id)
Ejemplo n.º 7
0
def leave_game(bot, update):
    """Handler for the /leave command"""
    chat = update.message.chat
    user = update.message.from_user

    player = gm.player_for_user_in_chat(user, chat)

    if player is None:
        send_async(bot, chat.id, text=_("You are not playing in a game in "
                                        "this group."),
                   reply_to_message_id=update.message.message_id)
        return

    game = player.game
    user = update.message.from_user

    try:
        gm.leave_game(user, chat)

    except NoGameInChatError:
        send_async(bot, chat.id, text=_("You are not playing in a game in "
                                        "this group."),
                   reply_to_message_id=update.message.message_id)

    except NotEnoughPlayersError:
        gm.end_game(chat, user)
        send_async(bot, chat.id, text=__("Game ended!", multi=game.translate))

    else:
        send_async(bot, chat.id,
                   text=__("Okay. Next Player: {name}",
                           multi=game.translate).format(
                       name=display_name(game.current_player.user)),
                   reply_to_message_id=update.message.message_id)
Ejemplo n.º 8
0
def status_update(bot, update):
    """Remove player from game if user leaves the group"""
    chat = update.message.chat

    if update.message.left_chat_member:
        user = update.message.left_chat_member

        try:
            gm.leave_game(user, chat)
            game = gm.player_for_user_in_chat(user, chat).game

        except NoGameInChatError:
            pass
        except NotEnoughPlayersError:
            gm.end_game(chat, user)
            send_async(bot,
                       chat.id,
                       text=__("chalo hogaya aaj ka, back to bihar.",
                               multi=game.translate))
        else:
            send_async(
                bot,
                chat.id,
                text=__("{name} bihari ko nikalo bc",
                        multi=game.translate).format(name=display_name(user)))
Ejemplo n.º 9
0
 def on_enter_game1(self, event):
     print("I'm entering game1")
     global finalnum
     finalnum=randint(1,100)
     reply_token = event.reply_token
     username=display_name(event)
     send_text_message(reply_token, username+"發起了終極密碼的挑戰\n輸入任意鍵開始遊戲:")
Ejemplo n.º 10
0
 def on_enter_right(self, event):
     print("I'm entering right")
     username=display_name(event)
     reply_token = event.reply_token
     send_text_message(reply_token,username+" 贏得了勝利 恭喜!!!")
     push_message(event,"再次輸入menu選取要的功能吧><")
     self.go_back()
Ejemplo n.º 11
0
def do_draw(bot, player):
    """Does the drawing"""
    game = player.game
    draw_counter_before = game.draw_counter

    try:
        player.draw()
    except DeckEmptyError:
        send_async(bot,
                   player.game.chat.id,
                   text=__("There are no more cards in the deck.",
                           multi=game.translate))

    if (game.last_card.value == c.DRAW_TWO or
        game.last_card.special == c.DRAW_FOUR) and \
            draw_counter_before > 0:
        game.turn()
    else:
        playable = player.playable_cards()
        if len(playable) == 0:
            time.sleep(1)
            send_async(bot,
                       game.chat.id,
                       text='Passing for {name}'.format(
                           name=display_name(game.current_player.user)))
            game.turn()
Ejemplo n.º 12
0
def ai_turn(bot, game):
    player = game.current_player
    while player.ai:
        reply = ''

        from ISMCTS import UNOState, ISMCTS
		from utils import display_color, display_name
        chat_id = game.chat.id
        state = UNOState(game)
        move = ISMCTS(state, itermax=ai_iterations, verbose=False)
        if move == 'draw':
            reply += 'Drawing\n'
        else:
            sticker_async(bot, chat_id,
                          sticker=c.STICKERS[str(move)])
            if move.special:
                reply += "Choosing color: %s\n" % display_color(move.color)

        state.DoMove(move)
        if len(player.cards) == 1:
            reply += "UNO!\n"
        if len(player.cards) == 0:
            reply += "%s won!\n" % player.user.first_name
            if len(game.players) < 3:
                reply += "Game ended!"
                gm.end_game(chat_id, player.next.user)
            else:
                player.leave()

        player = game.current_player
        if game in gm.chatid_games.get(chat_id, list()):
            reply += "Next player: " + display_name(player.user)

        send_async(bot, chat_id, text=reply)
Ejemplo n.º 13
0
def leave_game(bot, update):
    """Handler for the /leave command"""
    chat = update.message.chat
    user = update.message.from_user

    player = gm.player_for_user_in_chat(user, chat)

    if player is None:
        send_async(bot, chat.id, text=_("You are not playing in a game in "
                                        "this group."),
                   reply_to_message_id=update.message.message_id)
        return

    game = player.game
    user = update.message.from_user

    try:
        gm.leave_game(user, chat)

    except NoGameInChatError:
        send_async(bot, chat.id, text=_("You are not playing in a game in "
                                        "this group."),
                   reply_to_message_id=update.message.message_id)

    except NotEnoughPlayersError:
        gm.end_game(chat, user)
        send_async(bot, chat.id, text=__("Game ended!", multi=game.translate))

    else:
        send_async(bot, chat.id,
                   text=__("Okay. Next Player: {name}",
                           multi=game.translate).format(
                       name=display_name(game.current_player.user)),
                   reply_to_message_id=update.message.message_id)
        ai_turn(bot, game)
Ejemplo n.º 14
0
def process_result(bot, update):
    """
    Handler for chosen inline results.
    Checks the players actions and acts accordingly.
    """
    try:
        user = update.chosen_inline_result.from_user
        player = gm.userid_current[user.id]
        game = player.game
        result_id = update.chosen_inline_result.result_id
        chat = game.chat
    except (KeyError, AttributeError):
        return

    logger.debug("Selected result: " + result_id)

    result_id, anti_cheat = result_id.split(':')
    last_anti_cheat = player.anti_cheat
    player.anti_cheat += 1

    if result_id in ('hand', 'gameinfo', 'nogame'):
        return
    elif len(result_id) == 36:  # UUID result
        return
    elif int(anti_cheat) != last_anti_cheat:
        send_async(bot, chat.id,
                   text=__("Cheat attempt by {name}", multi=game.translate)
                   .format(name=display_name(player.user)))
        return
    elif result_id == 'call_bluff':
        reset_waiting_time(bot, player)
        do_call_bluff(bot, player)
    elif result_id == 'draw':
        reset_waiting_time(bot, player)
        do_draw(bot, player)
    elif result_id == 'pass':
        game.turn()
    elif result_id in c.COLORS:
        game.choose_color(result_id)
    else:
        reset_waiting_time(bot, player)
        do_play_card(bot, player, result_id)

    if game in gm.chatid_games.get(chat.id, list()):
        send_async(bot, chat.id,
                   text=__("Next player: {name}", multi=game.translate)
                   .format(name=display_name(game.current_player.user)))
Ejemplo n.º 15
0
def game_info(game):
    players = player_list(game)
    return InputTextMessageContent(
        _("Current player: {name}").format(
            name=display_name(game.current_player.user)) + "\n" +
        _("Last card: {card}").format(card=repr(game.last_card)) + "\n" +
        _("Player: {player_list}", "Players: {player_list}", len(
            players)).format(player_list=" -> ".join(players)))
Ejemplo n.º 16
0
 def on_enter_song(self, event):
     print("I'm entering song")
     username=display_name(event)
     print(username)
     global songnum
     global songurl
     reply_token = event.reply_token
     send_audio(reply_token,str(songurl[songnum]))
Ejemplo n.º 17
0
 def on_enter_game2(self, event):
     global songnum
     global songlist
     print("I'm entering game2")
     reply_token = event.reply_token
     songnum=randint(0,len(songlist)-1)
     username=display_name(event)
     send_text_message(reply_token,username+"發起了猜歌遊戲!"+"\n輸入\"不猜了\"遊戲結束 公布正解\n輸入任意鍵開始遊戲:")
     self.go_back()
Ejemplo n.º 18
0
def reset_waiting_time(bot, player):
    """Resets waiting time for a player and sends a notice to the group"""
    chat = player.game.chat

    if player.waiting_time < 90:
        player.waiting_time = 90
        send_async(bot, chat.id,
                   text=__("Waiting time for {name} has been reset to 90 "
                           "seconds", multi=player.game.translate)
                   .format(name=display_name(player.user)))
Ejemplo n.º 19
0
def reset_waiting_time(bot, player):
    """Resets waiting time for a player and sends a notice to the group"""
    chat = player.game.chat

    if player.waiting_time < 90:
        player.waiting_time = 90
        send_async(bot, chat.id,
                   text=__("Waiting time for {name} has been reset to 90 "
                           "seconds", multi=player.game.translate)
                   .format(name=display_name(player.user)))
Ejemplo n.º 20
0
def game_info(game):
    players = player_list(game)
    players_numbered = [
        '{}. {}'.format(i + 1, p) for i, p in enumerate(players)
    ]
    return InputTextMessageContent(
        _("Current player: {name}").format(
            name=display_name(game.current_player.user)) + "\n" +
        _("Last card: {card}").format(card=repr(game.last_card)) +
        "\n" + _("Player: \n{player_list}", "Players: \n{player_list}",
                 len(players)).format(player_list="\n".join(players_numbered)))
Ejemplo n.º 21
0
def game_info(game):
    players = player_list(game)
    return InputTextMessageContent(
        _("Current player: {name}")
        .format(name=display_name(game.current_player.user)) +
        "\n" +
        _("Last card: {card}").format(card=repr(game.last_card)) +
        "\n" +
        _("Players: {player_list}")
        .format(player_list=" -> ".join(players))
    )
Ejemplo n.º 22
0
def process_auto(bot, game, job_queue):
    start_player = game.current_player

    if not game.choosing_color:
        playable = game.current_player.playable_cards()
        if len(playable) == 0 and game.draw_counter == 0:
            time.sleep(1)
            send_async(bot,
                       game.chat.id,
                       text='Drawing 1 card for {name}'.format(
                           name=display_name(game.current_player.user)))
            do_draw(bot, game.current_player)
            time.sleep(1)
            send_async(bot,
                       game.chat.id,
                       text=__(
                           "Next player: {name}", multi=game.translate).format(
                               name=display_name(game.current_player.user)))
            start_player_countdown(bot, game, job_queue)
            if (start_player != game.current_player):
                process_auto(bot, game, job_queue)
Ejemplo n.º 23
0
def do_skip(bot, player, job_queue=None):
    game = player.game
    chat = game.chat
    skipped_player = game.current_player
    next_player = game.current_player.next

    if skipped_player.waiting_time > 0:
        skipped_player.anti_cheat += 1
        skipped_player.waiting_time -= TIME_REMOVAL_AFTER_SKIP
        if (skipped_player.waiting_time < 0):
            skipped_player.waiting_time = 0

        # if player get skipped after playing wildcard or +4
        # before getting to choose color, then choose color randomly
        if game.choosing_color:
            game.last_card.color = random.choice(c.COLORS)

        try:
            skipped_player.draw()
        except DeckEmptyError:
            pass

        n = skipped_player.waiting_time
        send_async(bot,
                   chat.id,
                   text="Waiting time to skip this player has "
                   "been reduced to {time} seconds.\n"
                   "Next player: {name}".format(time=n,
                                                name=display_name(
                                                    next_player.user)))
        logger.info(
            "{player} was skipped!. ".format(player=display_name(player.user)))
        game.turn()
        if job_queue:
            start_player_countdown(bot, game, job_queue)

    else:
        try:
            gm.leave_game(skipped_player.user, chat)
            send_async(bot,
                       chat.id,
                       text="{name1} ran out of time "
                       "and has been removed from the game!\n"
                       "Next player: {name2}".format(
                           name1=display_name(skipped_player.user),
                           name2=display_name(next_player.user)))
            logger.info("{player} was skipped!. ".format(
                player=display_name(player.user)))
            if job_queue:
                start_player_countdown(bot, game, job_queue)

        except NotEnoughPlayersError:
            send_async(bot,
                       chat.id,
                       text="{name} ran out of time "
                       "and has been removed from the game!\n"
                       "The game ended.".format(
                           name=display_name(skipped_player.user)))

            gm.end_game(chat, skipped_player.user)
Ejemplo n.º 24
0
 def on_enter_hit(self, event):
     global highest
     global lowest
     global guess
     print("I'm entering hit")
     reply_token = event.reply_token
     send_image(reply_token)
     username=display_name(event)
     push_message(event,username+" 引爆了炸彈!!")
     highest=100
     lowest=1
     guess=0
     push_message(event,"再次輸入menu選取要的功能吧><")
     self.go_back()
Ejemplo n.º 25
0
def do_skip(bot, player, job_queue=None):
    game = player.game
    chat = game.chat
    skipped_player = game.current_player
    next_player = game.current_player.next

    if skipped_player.waiting_time > 0:
        skipped_player.anti_cheat += 1
        skipped_player.waiting_time -= TIME_REMOVAL_AFTER_SKIP
        if (skipped_player.waiting_time < 0):
            skipped_player.waiting_time = 0

        try:
            skipped_player.draw()
        except DeckEmptyError:
            pass

        n = skipped_player.waiting_time
        send_async(bot,
                   chat.id,
                   text="Ye khiladi {time} seconds ke"
                   "liye hilane gaya hain\n"
                   "Agla chu: {name}".format(time=n,
                                             name=display_name(
                                                 next_player.user)))
        logger.info(
            "{player} was skipped!. ".format(player=display_name(player.user)))
        game.turn()
        if job_queue:
            start_player_countdown(bot, game, job_queue)

    else:
        try:
            gm.leave_game(skipped_player.user, chat)
            send_async(bot,
                       chat.id,
                       text="{name1} ran out of time "
                       "and has been removed from the game!\n"
                       "Next player: {name2}".format(
                           name1=display_name(skipped_player.user),
                           name2=display_name(next_player.user)))
            logger.info("{player} was skipped!. ".format(
                player=display_name(player.user)))
            if job_queue:
                start_player_countdown(bot, game, job_queue)

        except NotEnoughPlayersError:
            send_async(bot,
                       chat.id,
                       text="{name} ran out of time "
                       "and has been removed from the game!\n"
                       "The game ended.".format(
                           name=display_name(skipped_player.user)))

            gm.end_game(chat, skipped_player.user)
Ejemplo n.º 26
0
def game_info(game):
    if game.mode == 'score':
        players = score_list(game)
    else:
        players = player_list(game)
    players_numbered = [
        '{}. {}'.format(i + 1, p) for i, p in enumerate(players)
    ]
    return InputTextMessageContent(
        _("Current player: {name}").format(
            name=display_name(game.current_player.user)) + "\n" +
        _("Last card: {card}").format(
            card=repr(game.last_card).replace('Draw Four', '+4').replace(
                'Draw', '+2').replace('Colorchooser', 'Color Chooser')) +
        "\n" + "Points to win: {points}".format(points=game.win_score) +
        "\n" + _("Player: \n{player_list}", "Players: \n{player_list}",
                 len(players)).format(player_list="\n".join(players_numbered)))
Ejemplo n.º 27
0
def play_next(game, bot, chat, job_queue):
    if game_is_running(game):
        nextplayer_message = (__(
            "Next player: {name}", multi=game.translate).format(
                name=display_name(game.current_player.user)))
        choice = [[
            InlineKeyboardButton(text=_("Make your choice!"),
                                 switch_inline_query_current_chat='')
        ]]
        send_async(bot,
                   chat.id,
                   text=nextplayer_message,
                   reply_markup=InlineKeyboardMarkup(choice))
        start_player_countdown(bot, game, job_queue)

        if game.current_player.user.id == bot.id:
            playBot(game.current_player, bot, chat, game, job_queue)
Ejemplo n.º 28
0
def status_update(bot, update):
    """Remove player from game if user leaves the group"""
    chat = update.message.chat

    if update.message.left_chat_member:
        user = update.message.left_chat_member

        try:
            gm.leave_game(user, chat)
            game = gm.player_for_user_in_chat(user, chat).game

        except NoGameInChatError:
            pass
        except NotEnoughPlayersError:
            gm.end_game(chat, user)
            send_async(bot, chat.id, text=__("Game ended!", game.translate))
        else:
            send_async(bot, chat.id, text=__("Removing {name} from the game",
                                             game.translate)
                       .format(name=display_name(user)))
Ejemplo n.º 29
0
def start_player_countdown(bot, game, job_queue):
    player = game.current_player
    time = player.waiting_time

    if time < MIN_FAST_TURN_TIME:
        time = MIN_FAST_TURN_TIME

    if game.mode == 'fast':
        if game.job:
            game.job.schedule_removal()

        job = job_queue.run_once(
            #lambda x,y: do_skip(bot, player),
            skip_job,
            time,
            context=Countdown(player, job_queue))

        logger.info(
            "Started countdown for player: {player}. {time} seconds.".format(
                player=display_name(player.user), time=time))
        player.game.job = job
Ejemplo n.º 30
0
def status_update(bot, update):
    """Remove player from game if user leaves the group"""
    chat = update.message.chat

    if update.message.left_chat_member:
        user = update.message.left_chat_member

        try:
            game = gm.player_for_user_in_chat(user, chat).game
            gm.leave_game(user, chat)

        except NoGameInChatError:
            pass
        except NotEnoughPlayersError:
            gm.end_game(chat, user)
            send_async(bot, chat.id, text=__("Game ended!",
                                             multi=game.translate))
        else:
            send_async(bot, chat.id, text=__("Removing {name} from the game",
                                             multi=game.translate)
                       .format(name=display_name(user)))
Ejemplo n.º 31
0
def start_game(bot, update, args):
    """Handler for the /start command"""

    if update.message.chat.type != 'private':
        chat = update.message.chat

        try:
            game = gm.chatid_games[chat.id][-1]
        except (KeyError, IndexError):
            send_async(bot, chat.id,
                       text=_("There is no game running in this chat. Create "
                              "a new one with /new"))
            return

        if game.started:
            send_async(bot, chat.id, text=_("The game has already started"))

        elif len(game.players) < 2:
            send_async(bot, chat.id,
                       text=_("At least two players must /join the game "
                              "before you can start it"))

        else:
            game.play_card(game.last_card)
            game.started = True

            first_message = (
                __("First player: {name}\n"
                   "Use /close to stop people from joining the game.\n"
                   "Enable multi-translations with /enable_translations",
                   multi=game.translate)
                .format(name=display_name(game.current_player.user)))

            @run_async
            def send_first():
                """Send the first card and player"""

                bot.sendSticker(chat.id,
                                sticker=c.STICKERS[str(game.last_card)],
                                timeout=TIMEOUT)

                bot.sendMessage(chat.id,
                                text=first_message,
                                timeout=TIMEOUT)

            send_first()

    elif len(args) and args[0] == 'select':
        players = gm.userid_players[update.message.from_user.id]

        groups = list()
        for player in players:
            title = player.game.chat.title

            if player is gm.userid_current[update.message.from_user.id]:
                title = '- %s -' % player.game.chat.title

            groups.append(
                [InlineKeyboardButton(text=title,
                                      callback_data=str(player.game.chat.id))]
            )

        send_async(bot, update.message.chat_id,
                   text=_('Please select the group you want to play in.'),
                   reply_markup=InlineKeyboardMarkup(groups))

    else:
        help(bot, update)
Ejemplo n.º 32
0
def kick_player(bot, update):
    """Handler for the /kick command"""

    if update.message.chat.type == 'private':
        help_handler(bot, update)
        return

    chat = update.message.chat
    user = update.message.from_user

    try:
        game = gm.chatid_games[chat.id][-1]

    except (KeyError, IndexError):
        send_async(bot,
                   chat.id,
                   text=_("kardi jatin bihari pruthi wali baat "
                          "Naya game bana /new "),
                   reply_to_message_id=update.message.message_id)
        return

    if not game.started:
        send_async(
            bot,
            chat.id,
            text=_(
                "kardi bihari wali baat, /join karke start kar aise /start "),
            reply_to_message_id=update.message.message_id)
        return

    if user_is_creator_or_admin(user, game, bot, chat):

        if update.message.reply_to_message:
            kicked = update.message.reply_to_message.from_user

            try:
                gm.leave_game(kicked, chat)

            except NoGameInChatError:
                send_async(
                    bot,
                    chat.id,
                    text=_("Player {name} is not found in the current game.".
                           format(name=display_name(kicked))),
                    reply_to_message_id=update.message.message_id)
                return

            except NotEnoughPlayersError:
                gm.end_game(chat, user)
                send_async(bot,
                           chat.id,
                           text=_("{0} was kicked by {1}".format(
                               display_name(kicked), display_name(user))))
                send_async(bot,
                           chat.id,
                           text=__("chalo hogaya aaj ka, back to bihar.",
                                   multi=game.translate))
                return

            send_async(bot,
                       chat.id,
                       text="{1} ne {0} ko bihar bhej diya".format(
                           display_name(kicked), display_name(user)))

        else:
            send_async(
                bot,
                chat.id,
                text=
                _("Please reply to the person you want to kick and type /kick again."
                  ),
                reply_to_message_id=update.message.message_id)
            return

        send_async(bot,
                   chat.id,
                   text="Okay. Agla Bihari: {name}".format(
                       name=display_name(me.current_player.user)),
                   reply_to_message_id=update.message.message_id)

    else:
        send_async(
            bot,
            chat.id,
            text=_("Only the game creator ({name}) and admin can do that."
                   ).format(name=game.starter.first_name),
            reply_to_message_id=update.message.message_id)
Ejemplo n.º 33
0
def start_game(bot, update, args, job_queue):
    """Handler for the /start command"""

    if update.message.chat.type != 'private':
        chat = update.message.chat

        try:
            game = gm.chatid_games[chat.id][-1]
        except (KeyError, IndexError):
            send_async(bot,
                       chat.id,
                       text=_("There is no game running in this chat. Create "
                              "a new one with /new"))
            return

        if game.started:
            send_async(bot, chat.id, text=_("The game has already started"))

        elif len(game.players) < MIN_PLAYERS:
            send_async(
                bot,
                chat.id,
                text=__(
                    "At least {minplayers} players must /join the game "
                    "before you can start it").format(minplayers=MIN_PLAYERS))

        else:
            # Set winning score
            player_num = len(game.players)
            if player_num == 2:
                game.win_score = SCORE_DUEL
            else:
                game.win_score = ADDITIONAL_POINT * player_num
            # Starting a game
            game.start()

            for player in game.players:
                player.draw_first_hand()

            first_message = (__(
                "First player: {name}\n"
                "Use /close to stop people from joining the game.\n"
                "Enable multi-translations with /enable_translations",
                multi=game.translate).format(
                    name=display_name(game.current_player.user)))

            @run_async
            def send_first():
                """Send the first card and player"""

                bot.sendSticker(chat.id,
                                sticker=c.STICKERS[str(game.last_card)],
                                timeout=TIMEOUT)

                bot.sendMessage(chat.id, text=first_message, timeout=TIMEOUT)

            send_first()
            start_player_countdown(bot, game, job_queue)

    elif len(args) and args[0] == 'select':
        players = gm.userid_players[update.message.from_user.id]

        groups = list()
        for player in players:
            title = player.game.chat.title

            if player is gm.userid_current[update.message.from_user.id]:
                title = '- %s -' % player.game.chat.title

            groups.append([
                InlineKeyboardButton(text=title,
                                     callback_data=str(player.game.chat.id))
            ])

        send_async(bot,
                   update.message.chat_id,
                   text=_('Please select the group you want to play in.'),
                   reply_markup=InlineKeyboardMarkup(groups))

    else:
        help_handler(bot, update)
Ejemplo n.º 34
0
def kick_player(bot, update):
    """Handler for the /kick command"""

    if update.message.chat.type == 'private':
        help_handler(bot, update)
        return

    chat = update.message.chat
    user = update.message.from_user

    try:
        game = gm.chatid_games[chat.id][-1]

    except (KeyError, IndexError):
        send_async(bot,
                   chat.id,
                   text=_("No game is running at the moment. "
                          "Create a new game with /new"),
                   reply_to_message_id=update.message.message_id)
        return

    if not game.started:
        send_async(
            bot,
            chat.id,
            text=_("The game is not started yet. "
                   "Join the game with /join and start the game with /start"),
            reply_to_message_id=update.message.message_id)
        return

    if user_is_creator_or_admin(user, game, bot, chat):

        if update.message.reply_to_message:
            kicked = update.message.reply_to_message.from_user

            try:
                gm.leave_game(kicked, chat)

            except NoGameInChatError:
                send_async(
                    bot,
                    chat.id,
                    text=_("Player {name} is not found in the current game.".
                           format(name=display_name(kicked))),
                    reply_to_message_id=update.message.message_id)
                return

            except NotEnoughPlayersError:
                gm.end_game(chat, user)
                send_async(bot,
                           chat.id,
                           text=_("{0} was kicked by {1}".format(
                               display_name(kicked), display_name(user))))
                send_async(bot,
                           chat.id,
                           text=__("Game ended!", multi=game.translate))
                return

            send_async(bot,
                       chat.id,
                       text=_("{0} was kicked by {1}".format(
                           display_name(kicked), display_name(user))))

        else:
            send_async(
                bot,
                chat.id,
                text=
                _("Please reply to the person you want to kick and type /kick again."
                  ),
                reply_to_message_id=update.message.message_id)
            return

        send_async(bot,
                   chat.id,
                   text=__("Okay. Next Player: {name}",
                           multi=game.translate).format(
                               name=display_name(game.current_player.user)),
                   reply_to_message_id=update.message.message_id)

    else:
        send_async(
            bot,
            chat.id,
            text=_("Only the game creator ({name}) and admin can do that."
                   ).format(name=game.starter.first_name),
            reply_to_message_id=update.message.message_id)
Ejemplo n.º 35
0
def do_skip(bot, player, job_queue=None):
    game = player.game
    chat = game.chat
    skipped_player = game.current_player
    next_player = game.current_player.next

    if skipped_player.waiting_time > 0:
        skipped_player.anti_cheat += 1
        skipped_player.waiting_time -= TIME_REMOVAL_AFTER_SKIP
        if (skipped_player.waiting_time < 0):
            skipped_player.waiting_time = 0

        # skip drawing if current player should choose color
        # which means current player has played a card
        try:
            if not game.choosing_color:
                skipped_player.draw()
        except DeckEmptyError:
            pass

        n = skipped_player.waiting_time
        send_async(bot,
                   chat.id,
                   text=__(
                       "Waiting time to skip this player has "
                       "been reduced to {time} seconds.\n"
                       "Next player: {name}",
                       multi=game.translate).format(time=n,
                                                    name=display_name(
                                                        next_player.user)))
        logger.info(
            "{player} was skipped!. ".format(player=display_name(player.user)))
        game.turn()

        # send message to indicate the game has randomly choosen the color
        if game._randomed_color:
            send_async(bot,
                       chat.id,
                       text=__("Color randomly choosen to: {col}",
                               multi=game.translate).format(
                                   col=c.COLOR_ICONS[game.last_card.color]))

        if job_queue:
            start_player_countdown(bot, game, job_queue)

    else:
        try:
            gm.leave_game(skipped_player.user, chat)
            send_async(bot,
                       chat.id,
                       text=__(
                           "{name1} ran out of time "
                           "and has been removed from the game!\n"
                           "Next player: {name2}",
                           multi=game.translate).format(
                               name1=display_name(skipped_player.user),
                               name2=display_name(next_player.user)))
            logger.info("{player} was skipped!. ".format(
                player=display_name(player.user)))
            if job_queue:
                start_player_countdown(bot, game, job_queue)

        except NotEnoughPlayersError:
            send_async(bot,
                       chat.id,
                       text=__(
                           "{name} ran out of time "
                           "and has been removed from the game!\n"
                           "The game ended.",
                           multi=game.translate).format(
                               name=display_name(skipped_player.user)))

            gm.end_game(chat, skipped_player.user)
Ejemplo n.º 36
0
 def on_enter_again(self, event):
     print("I'm entering again")
     username=display_name(event)
     print(username)
     reply_token = event.reply_token
     send_text_message(reply_token,username+'答錯啦 再猜猜看')
Ejemplo n.º 37
0
def skip_player(bot, update):
    """Handler for the /skip command"""
    chat = update.message.chat
    user = update.message.from_user

    player = gm.player_for_user_in_chat(user, chat)
    if not player:
        send_async(bot,
                   chat.id,
                   text=_("You are not playing in a game in this chat."))
        return

    game = player.game
    skipped_player = game.current_player
    next_player = game.current_player.next

    started = skipped_player.turn_started
    now = datetime.now()
    delta = (now - started).seconds

    if delta < skipped_player.waiting_time:
        n = skipped_player.waiting_time - delta
        send_async(bot,
                   chat.id,
                   text=_("Please wait {time} second",
                          "Please wait {time} seconds", n).format(time=n),
                   reply_to_message_id=update.message.message_id)

    elif skipped_player.waiting_time > 0:
        skipped_player.anti_cheat += 1
        skipped_player.waiting_time -= 30
        try:
            skipped_player.draw()
        except DeckEmptyError:
            pass

        n = skipped_player.waiting_time
        send_async(bot,
                   chat.id,
                   text=__(
                       "Waiting time to skip this player has "
                       "been reduced to {time} second.\n"
                       "Next player: {name}",
                       "Waiting time to skip this player has "
                       "been reduced to {time} seconds.\n"
                       "Next player: {name}",
                       n,
                       multi=game.translate).format(time=n,
                                                    name=display_name(
                                                        next_player.user)))
        game.turn()

    else:
        try:
            gm.leave_game(skipped_player.user, chat)
            send_async(bot,
                       chat.id,
                       text=__(
                           "{name1} was skipped four times in a row "
                           "and has been removed from the game.\n"
                           "Next player: {name2}",
                           multi=game.translate).format(
                               name1=display_name(skipped_player.user),
                               name2=display_name(next_player.user)))

        except NotEnoughPlayersError:
            send_async(bot,
                       chat.id,
                       text=__(
                           "{name} was skipped four times in a row "
                           "and has been removed from the game.\n"
                           "The game ended.",
                           multi=game.translate).format(
                               name=display_name(skipped_player.user)))

            gm.end_game(chat.id, skipped_player.user)