예제 #1
0
파일: main.py 프로젝트: mikelty/tk-2048
class Wrapper():
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('2048')
        self.root.iconbitmap(default='..\\assets\\images\\icon.ico')

        self.bg = tk.Frame(self.root, bg='white', width=400, height=400)
        self.game = Game(self.bg)
        self.bg.bind('<Up>', lambda e, dir='up': self.game.step_wrapper(dir))
        self.bg.bind('<Down>',
                     lambda e, dir='down': self.game.step_wrapper(dir))
        self.bg.bind('<Left>',
                     lambda e, dir='left': self.game.step_wrapper(dir))
        self.bg.bind('<Right>',
                     lambda e, dir='right': self.game.step_wrapper(dir))
        self.bg.pack(side=tk.BOTTOM)
        self.bg.focus_set()

        menubar = tk.Menu(self.root)
        self.root.config(menu=menubar)
        menubar.add_command(label='reset', command=self.game.reset)
        menubar.add_command(label='high scores', command=self.game.high_score)
        menubar.add_command(label='about', command=self.about_game)

        self.root.mainloop()

    def about_game(self):
        about = tk.Toplevel(self.root)
        about.geometry("%dx%d%+d%+d" % (200, 30, 0, 0))
        about.title('about')
        about_text = tk.Label(about, text="made by mikey2520 on 5.24.2020")
        about_text.pack()
예제 #2
0
    async def join(self, context, union_name=None):
        """ Join a union. """
        channel = context.message.channel
        is_private = isinstance(channel, PrivateChannel)

        if is_private and union_name is None:
            return await channel.send('You must enter the name of the union you would like to join.',
                                      delete_after=settings.DEFAULT_DELETE_DELAY)

        if is_private:
            union = Game.search_unions(union_name)
        else:
            union = Game.get_union(context.message.guild)

        if union is None:
            return await channel.send('That union does not exist or is not registered.',
                                      delete_after=settings.DEFAULT_DELETE_DELAY)

        player = Game.get_player(context.author)
        if player and player.union:
            return await channel.send(f'You already belong to the union {player.union.name}',
                                      delete_after=settings.DEFAULT_DELETE_DELAY)
        elif player is None:
            # invoke the 'create' command, instead of rewriting functionality
            return await self.bot.get_command('create').invoke(context)

        await channel.send(player.join_union(union))
예제 #3
0
def main():
    g = Game()
    g.show_start_screen()
    while True:
        g.new()
        g.run()
        g.show_go_screen()
예제 #4
0
    def test_add_player(self):
        player_json = {
            "teamName":
            "Test",
            "classes": [
                {
                    "characterName": "character1",
                    "classId": "dummy_one"
                },
                {
                    "characterName": "character2",
                    "classId": "dummy_two"
                },
                {
                    "characterName": "character3",
                    "classId": "dummy_one"
                },
            ]
        }

        game = Game(500)
        response = game.add_new_player(player_json)
        print(response)

        self.assertEqual(response[0], True)
        self.assertEqual(game.teams[0].name, player_json['teamName'])
        self.assertEqual(len(game.teams[0].characters), 3)
예제 #5
0
 def start(self, starter_name):
     with self.mtx:
         if self.g is None or self.g.game_over():
             names = [p["username"] for p in self.players.values()]
             classes = [p["class"] for p in self.players.values()]
             self.g = Game(names, classes, shape)
             self.update()
     return self.g
예제 #6
0
    def test_game_init_rounds_returns_an_empty_array_if_no_questions_are_given(
            self):
        initial_questions = []

        s = Subject(Connection(), initial_questions, Questions_Asked(),
                    Player_Scores(), Timer())
        actual_questions = s.init_rounds()

        self.assertEqual(actual_questions, initial_questions)
예제 #7
0
 def test_game_does_not_load_questions_in_the_questions_asked_list_to_rounds(
         self):
     initial_questions = [{
         'Round': 1,
         'Ask': "What's a Diorama?",
         'Answer': "OMG Han! Chewie! They're all here!"
     }, {
         'Round': 2,
         'Ask': 'What is your name?',
         'Answer': 'Sir Lancelot of Camelot'
     }, {
         'Round': 2,
         'Ask': 'What is your quest?',
         'Answer': 'To seek the Holy Grail'
     }, {
         'Round': 2,
         'Ask': 'What is your favorite color?',
         'Answer': 'Blue'
     }, {
         'Round': 3,
         'Ask': 'Are you a god?',
         'Answer': 'YES!'
     }]
     mock_questions_asked = Questions_Asked()
     mock_questions_asked._log = [{
         'Round':
         1,
         'Ask':
         "What's a Diorama?",
         'Answer':
         "OMG Han! Chewie! They're all here!"
     }, {
         'Round': 2,
         'Ask': 'What is your name?',
         'Answer': 'Sir Lancelot of Camelot'
     }]
     expected_questions = [
         [{
             'Round': 2,
             'Ask': 'What is your quest?',
             'Answer': 'To seek the Holy Grail'
         }, {
             'Round': 2,
             'Ask': 'What is your favorite color?',
             'Answer': 'Blue'
         }],
         [{
             'Round': 3,
             'Ask': 'Are you a god?',
             'Answer': 'YES!'
         }],
     ]
     s = Subject(Connection(), initial_questions, mock_questions_asked,
                 Player_Scores(), Timer())
     actual_questions = s.list_by_rounds(initial_questions)
     self.assertEqual(actual_questions, expected_questions)
예제 #8
0
    def test_game_clears_logs_if_it_reaches_the_end_of_the_game(self):
        questions = [{'Round': 3, 'Ask': 'Are you a god?', 'Answer': 'YES!'}]
        mock_questions_asked = Questions_Asked()

        s = Subject(Connection(), questions, mock_questions_asked,
                    Player_Scores(), Timer())
        s.start()
        s.end()

        self.assertEqual(mock_questions_asked._clear_received, True)
예제 #9
0
def test_run_action():
    g = Game(names=['Vasya'], classes=['рыцарь'], shape=(25, 25))
    p = g.active_player
    pos = p.position
    assert p.ap == p.max_ap

    g.run_action(['move_player', 'right'])

    assert p.position == RIGHT.go(pos)
    assert p.ap == p.max_ap - 1
예제 #10
0
async def on_member_remove(member):
    """ Remove the banned player from the union, do nothing if the player wasn't a member of the union. """
    player = Game.get_player(member)
    union = Game.get_union(member.guild)

    if player is None or union is None:
        return

    if player in union.members:
        message = player.leave_union()
예제 #11
0
 def test_single(self):
     game = Game()
     game._game_board._game_board = np.array([[0, 0, 0, 0], [0, 4, 0, 0],
                                              [0, 0, 4, 0], [0, 0, 0, 0]])
     game.do_action("4")
     x, y = game.get_new_pos()
     expected = [[0, 0, 0, 0], [4, 0, 0, 0], [4, 0, 0, 0], [0, 0, 0, 0]]
     expected[x][y] = 2
     print('\n', game._game_board._game_board, '\n\n', np.array(expected))
     self.assertTrue(
         np.array_equal(game._game_board._game_board, np.array(expected)))
예제 #12
0
    def test_game_tells_players_to_score_game_winners_at_the_end_of_the_game(
            self):
        questions = [{'Round': 3, 'Ask': 'Are you a god?', 'Answer': 'YES!'}]
        mock_player_scores = Player_Scores()

        s = Subject(Connection(), questions, Questions_Asked(),
                    mock_player_scores, Timer())
        s.start()
        s.end()

        self.assertEqual(mock_player_scores._winner,
                         mock_player_scores._game_winners[0][0])
예제 #13
0
    def test_game_tells_players_to_reset_scores_for_a_new_game_at_the_end_of_the_game(
            self):
        questions = [{'Round': 3, 'Ask': 'Are you a god?', 'Answer': 'YES!'}]
        mock_player_scores = Player_Scores()

        s = Subject(Connection(), questions, Questions_Asked(),
                    mock_player_scores, Timer())
        s.start()
        s.end()

        self.assertEqual(mock_player_scores._next_game_called,
                         "Game Scores Reset")
예제 #14
0
    def test_game_list_by_rounds_doesnt_care_about_rounds_with_names(self):
        initial_questions = [{
            'Round': "Simpsons",
            'Ask': "What's a Diorama?",
            'Answer': "OMG Han! Chewie! They're all here!"
        }, {
            'Round': "Grail",
            'Ask': 'What is your name?',
            'Answer': 'Sir Lancelot of Camelot'
        }, {
            'Round': "Grail",
            'Ask': 'What is your quest?',
            'Answer': 'To seek the Holy Grail'
        }, {
            'Round': "Grail",
            'Ask': 'What is your favorite color?',
            'Answer': 'Blue'
        }, {
            'Round': "Ghost",
            'Ask': 'Are you a god?',
            'Answer': 'YES!'
        }]
        expected_questions = [
            [{
                'Round': "Simpsons",
                'Ask': "What's a Diorama?",
                'Answer': "OMG Han! Chewie! They're all here!"
            }],
            [{
                'Round': "Grail",
                'Ask': 'What is your name?',
                'Answer': 'Sir Lancelot of Camelot'
            }, {
                'Round': "Grail",
                'Ask': 'What is your quest?',
                'Answer': 'To seek the Holy Grail'
            }, {
                'Round': "Grail",
                'Ask': 'What is your favorite color?',
                'Answer': 'Blue'
            }],
            [{
                'Round': "Ghost",
                'Ask': 'Are you a god?',
                'Answer': 'YES!'
            }],
        ]

        s = Subject(Connection(), initial_questions, Questions_Asked(),
                    Player_Scores(), Timer())
        actual_questions = s.list_by_rounds(initial_questions)

        self.assertEqual(actual_questions, expected_questions)
예제 #15
0
    def test_game_list_by_rounds_groups_rounds_by_when_they_appear_in_the_list(
            self):
        initial_questions = [{
            'Round': 2,
            'Ask': 'What is your favorite color?',
            'Answer': 'Blue'
        }, {
            'Round': 5,
            'Ask': 'Are you a god?',
            'Answer': 'YES!'
        }, {
            'Round': 2,
            'Ask': 'What is your name?',
            'Answer': 'Sir Lancelot of Camelot'
        }, {
            'Round': 1,
            'Ask': "What's a Diorama?",
            'Answer': "OMG Han! Chewie! They're all here!"
        }, {
            'Round': 2,
            'Ask': 'What is your quest?',
            'Answer': 'To seek the Holy Grail'
        }]
        expected_questions = [[{
            'Round': 2,
            'Ask': 'What is your favorite color?',
            'Answer': 'Blue'
        }, {
            'Round': 2,
            'Ask': 'What is your name?',
            'Answer': 'Sir Lancelot of Camelot'
        }, {
            'Round': 2,
            'Ask': 'What is your quest?',
            'Answer': 'To seek the Holy Grail'
        }], [{
            'Round': 5,
            'Ask': 'Are you a god?',
            'Answer': 'YES!'
        }],
                              [{
                                  'Round': 1,
                                  'Ask': "What's a Diorama?",
                                  'Answer':
                                  "OMG Han! Chewie! They're all here!"
                              }]]

        s = Subject(Connection(), initial_questions, Questions_Asked(),
                    Player_Scores(), Timer())
        actual_questions = s.list_by_rounds(initial_questions)

        self.assertEqual(actual_questions, expected_questions)
예제 #16
0
 def testNewPhrase(self):
     game = Game("", [ClueSetType.BASE])
     game.new_phrase()
     with self.subTest("Check that phrase is generated"):
         self.assertIsNotNone(game.current_phrase)
     with self.subTest("Check phrase is str"):
         self.assertTrue(isinstance(game.current_phrase, str))
     with self.subTest("Check madgab is str"):
         self.assertTrue(isinstance(game.current_madgab, str))
     with self.subTest("Check that madgab generated"):
         self.assertIsNotNone(game.current_madgab)
     with self.subTest("Check phrase has been changed"):
         self.assertNotEqual(game.current_phrase, game.current_madgab)
예제 #17
0
    def testResetTurn(self):
        game = Game("", [ClueSetType.BASE])

        game.start_turn()
        game.increment_active_state(True)
        with self.subTest("Check current turn clue"):
            self.assertEqual(len(game.current_turn_clues), 1)
        with self.subTest("Check current phrase"):
            self.assertIsNotNone(game.current_phrase)
        with self.subTest("Check current madgab"):
            self.assertIsNotNone(game.current_madgab)
        with self.subTest("Check counter"):
            self.assertEqual(game.current_turn_counter, 2)
        with self.subTest("Check correct"):
            self.assertEqual(game.current_turn_correct, 1)

        game._reset_turn()
        with self.subTest("Check current turn clue reset"):
            self.assertEqual(len(game.current_turn_clues), 0)
        with self.subTest("Check current phrase reset"):
            self.assertEqual(game.current_phrase, "")
        with self.subTest("Check current madgab reset"):
            self.assertEqual(game.current_madgab, "")
        with self.subTest("Check counter reset"):
            self.assertEqual(game.current_turn_counter, 0)
        with self.subTest("Check correct reset"):
            self.assertEqual(game.current_turn_correct, 0)
예제 #18
0
    async def inventory(self, context, name, amount):
        """ Command only available to developers.

        Set the player's max inventory amount.
        """
        try:
            amount = int(amount)
        except ValueError:
            return await context.send(f'Inventory amount must be an integer, you entered "{amount}".',
                                      delete_after=settings.DEFAULT_DELETE_DELAY)

        if amount < 1:
            return await context.send('Inventory amount can not be less than 1.',
                                      delete_after=settings.DEFAULT_DELETE_DELAY)

        player = Game.get_player_by_name(name)
        if player is None:
            return await context.send(f'Player "{name}" does not exist.',
                                      delete_after=settings.DEFAULT_DELETE_DELAY)

        inventory = player.inventory
        inventory.max_materials = amount
        inventory.save()

        await context.send(f'Set max materials for "{player.username}" to {inventory.max_materials}.',
                           delete_after=settings.DEFAULT_DELETE_DELAY)
예제 #19
0
def load_board(data: Dict[Any, Any]):
    """Loads the current game board, or creates on if none exists.
    Args:
        data (Dict[Any, Any]): {
            "name": ([str, number]) The name of the game.
        }
    """
    schema = {
        "type": "object",
        "properties": {
            "name": {
                "type": ["string", "number"]
            }
        },
        "required": ["name"],
    }
    try:
        validate(data, schema=schema)
    except ValidationError as e:
        if "name" in data:
            emit_error(data["name"], str(e))
        else:
            logger.error("No game specified in input.")
    else:
        game_name = data["name"]

        if game_name not in all_games:
            cur_game = Game(game_name, [ClueSetType.BASE])
            all_games[game_name] = cur_game
        else:
            game = all_games[game_name]
            emit_game(game_name, game, "Game loaded.")
예제 #20
0
 def test_lose(self):
     game = Game()
     game._game_board._game_board = np.array([[2, 256, 2, 256],
                                              [4, 128, 4, 128],
                                              [8, 64, 8, 64],
                                              [16, 32, 16, 32]])
     self.assertTrue(game.game_over)
예제 #21
0
 async def start_game(self):
     print("game start!")
     self.game = Game(self.max_player, self.initial_card_amount)
     for index, player in enumerate(self.players.values()):
         self.player_role[player] = self.game.player_list[index]
         self.role_player[self.game.player_list[index]] = player
     await self.broadcast(game_start_event)
예제 #22
0
    async def resources(self, context):
        """ Display information about the resources on the current island. """
        channel = context.message.channel
        island = Game.get_player(context.author).get_location

        if not isinstance(island, Island):
            return await channel.send('You are currently not on an island.')

        if not island.resources:
            return await channel.send(
                'This island does not have any resources.')

        msg = '```'
        msg += f'ISLAND {island.union_number}'
        if island.resources:
            header = f'{"RESOURCE".ljust(10)} : AMT : MAX'
            msg += '\n' + header
            msg += '\n' + '-' * len(header)
            for resource in sorted(island.resources,
                                   key=attrgetter('name', 'number')):
                full_name = resource.name.title() + '#' + str(resource.number)
                material_amount = str(resource.material_amount).zfill(3)
                max_material_amount = str(
                    resource.max_material_amount).zfill(3)

                msg += f'\n{full_name.ljust(10)} : {material_amount} : {max_material_amount}'
        msg += '\n```'

        await channel.send(msg, delete_after=settings.DEFAULT_DELETE_DELAY)
예제 #23
0
    async def info(self, context):
        """ Display info about yourself. """
        if context.invoked_subcommand is None:
            player = Game.get_player(context.author)

            msg = '```'
            if player.union:
                msg += f'\nUNION  : {player.union.name}'
            else:
                msg += f'\nUNION  : NONE'

            if player.on_island:
                msg += f'\nISLAND : {player.on_island.name}'
            else:
                msg += f'\nISLAND : NONE'

            msg += f'\nACTION : {str(player.get_action)}'
            msg += '```'

            if not isinstance(context.channel, PrivateChannel):
                await context.send(msg,
                                   delete_after=settings.DEFAULT_DELETE_DELAY)
                # we can't delete the other user's direct message, so we save the sleep call
                await asyncio.sleep(60)
                # # delete the bot and user after a minute so chat doesn't get clogged
                await context.message.delete()
            else:
                await context.send(msg)
예제 #24
0
async def ask_guild_to_join_game(bot, guild, channel=None):
    if channel is None:
        channel = find_open_channel(guild)

    # we don't to pollute our database with random guilds that are inactive, so ask first if they want to join
    confirm_msg = ConfirmMenu(
        bot,
        channel,
        [
            'Welcome, would you like this guild to be registered within the game?',
            'This guild will not be registered.',  # message when dismissed
            'This guild is now registered.'
        ])  # message when confirmed
    await confirm_msg.send()
    logger.log(
        f'Asking guild "{guild.name}" [id:{guild.id}] to join the game.')
    confirmed = await confirm_msg.wait_for_user_reaction()

    if confirmed:
        # create a new guild for the guild
        union = Game.create_union(guild)
        logger.log(f'Created a new Union under the name "{union.name}"')
    else:
        await channel.send(
            'I am leaving this guild, as I am no longer needed. '
            'If you change your mind and would like to register this guild, just add me back.'
        )
        try:
            guild.leave()
        except HTTPException as exception:
            logger.log(exception)
            await channel.send(
                'Sorry to bother you, this is kind of embarrassing. '
                'I am having some trouble leaving, would you mind kicking me please?'
            )
예제 #25
0
def socket_client():
    app.config["TESTING"] = True
    all_games["TEST_GAME"] = Game("TEST_GAME", [ClueSetType.BASE])
    client = app.test_client()
    socket_client = socketio.test_client(app, flask_test_client=client)
    socket_client.emit("join", {"name": "TEST_GAME"})
    yield socket_client
예제 #26
0
    def testCalculateBonus(self):
        game = Game("", [ClueSetType.BASE])
        seconds = game.seconds_per_turn

        game._calculate_bonus(seconds * 2 / 3 + 1)
        with self.subTest("Big bonus"):
            self.assertEqual(game.team_1_score, 3)

        game._calculate_bonus(seconds * 1 / 2)
        with self.subTest("Medium bonus"):
            self.assertEqual(game.team_1_score, 5)

        game._calculate_bonus(seconds * 1 / 4)
        with self.subTest("Small bonus"):
            self.assertEqual(game.team_1_score, 6)

        game._calculate_bonus(seconds * 1 / 6 - 1)
        with self.subTest("No bonus"):
            self.assertEqual(game.team_1_score, 6)
예제 #27
0
    def _make_move(self, game: Game):
        total_simulations = 20
        games_per_move = total_simulations // 4

        valid_actions = game.valid_actions()

        scores = self._calculate_random(game, valid_actions, games_per_move)

        best_move_idx = scores.index(max(scores))
        best_move = valid_actions[best_move_idx]
        return best_move
예제 #28
0
    def test_init(self):
        # Test the win threshold
        params_threshold = [
            (30, 30, "Standard threshold"),
            (0, 10, "Threshold lower bound"),
            (75, 50, "Threshold upper bound"),
        ]
        for thresh, test, msg in params_threshold:
            with self.subTest(msg):
                self.assertEqual(
                    Game("", [ClueSetType.BASE],
                         win_threshold=thresh).win_threshold,
                    test,
                )

        # Test the words per turn threshold
        params_words_per_turn = [
            (3, 3, "Standard words_per_turn"),
            (0, 3, "words_per_turn lower bound"),
            (6, 5, "words_per_turn upper bound"),
        ]
        for words_per_turn, test, msg in params_words_per_turn:
            with self.subTest(msg):
                self.assertEqual(
                    Game("", [ClueSetType.BASE],
                         words_per_turn=words_per_turn).words_per_turn,
                    test,
                )

        params_seconds_per_turn = [
            (90, 90, "Standard seconds_per_turn"),
            (50, 60, "seconds_per_turn upper bound"),
            (130, 120, "seconds_per_turn upper bound"),
        ]
        for seconds_per_turn, test, msg in params_seconds_per_turn:
            with self.subTest(msg):
                self.assertEqual(
                    Game("", [ClueSetType.BASE],
                         seconds_per_turn=seconds_per_turn).seconds_per_turn,
                    test,
                )
예제 #29
0
    async def island(self, context, *guild_name):
        """ Command only available to developers.

        Add a new island to the current guild_name.
        """
        if not guild_name:
            union = Game.get_union(context.guild)
        else:
            guild_name = ' '.join(guild_name)
            union = Game.search_unions(guild_name)
            if union is None:
                return await context.send(f'Could not find any union under the name "{guild_name}"',
                                          delete_after=settings.DEFAULT_DELETE_DELAY)

        island = Island.create()

        union.max_islands += 1
        if union.claim_island(island):
            return await context.send(f'"{union.name}" claimed {island.name}',
                                      delete_after=settings.DEFAULT_DELETE_DELAY)
        await context.send(f'Failed to claim {island.name} for "{union.name}"',
                           delete_after=settings.DEFAULT_DELETE_DELAY)
예제 #30
0
    def test_game_lets_the_chat_know_the_game_is_over_with_who_won(self):
        questions = [{
            'Round': 1,
            'Ask': "What's a Diorama?",
            'Answer': "OMG Han! Chewie! They're all here!"
        }, {
            'Round': 2,
            'Ask': 'What is your name?',
            'Answer': 'Sir Lancelot of Camelot'
        }, {
            'Round': 2,
            'Ask': 'What is your quest?',
            'Answer': 'To seek the Holy Grail'
        }, {
            'Round': 2,
            'Ask': 'What is your favorite color?',
            'Answer': 'Blue'
        }, {
            'Round': 3,
            'Ask': 'Are you a god?',
            'Answer': 'YES!'
        }]
        mock_connection = Connection()
        mock_player_scores = Player_Scores()
        mock_questions_asked = Questions_Asked()
        gold = f"{mock_player_scores._game_winners[0][0]}: {mock_player_scores._game_winners[0][1]}"
        silver = f"{mock_player_scores._game_winners[1][0]}: {mock_player_scores._game_winners[1][1]}"
        bronze = f"{mock_player_scores._game_winners[2][0]}: {mock_player_scores._game_winners[2][1]}"

        s = Subject(mock_connection, questions, mock_questions_asked,
                    mock_player_scores, Timer())
        s.go()
        s.go()
        s.go()

        self.assertTrue(gold in mock_connection._message)
        self.assertTrue(silver in mock_connection._message)
        self.assertTrue(bronze in mock_connection._message)