Example #1
0
    def test_save_and_load(self):
        self.prepare_test()

        game = Game()
        save('a', game)
        game.new_rang(2)
        save('b', game)
        game.hot_seat = True
        save('c', game)
        game.turn.another_turn()
        save('d', game)

        new_game = Game()
        load(new_game, 3)
        assert new_game.hot_seat
        assert new_game.rang == 2
        assert new_game.turn.color == Color.Blue

        load(new_game, 2)
        assert new_game.turn.color == Color.Red

        load(new_game, 1)
        assert not new_game.hot_seat

        load(new_game, 0)
        assert new_game.rang == 11
Example #2
0
    def test_right_hex_dictionary(self):
        self.prepare_test()

        game = Game()
        game.new_rang(2)
        diction = {(0, 0): Color.White, (-1, 2): Color.Red,
                   (1, 2): Color.Red, (0, 4): Color.Blue}
        game.hex_dictionary = diction.copy()

        save('a', game)

        new_game = Game()
        load(new_game, 0)
        assert new_game.hex_dictionary == diction
    def test_game_can_be_won(self):
        # Arrange

        moves_text = self.get_text_from_file("moves.csv")
        actual_moves = moves_text[1:]
        # example line:
        # 0,0|2,0|0,1|1,1|2,2|0,2|-1

        for line in actual_moves:
            g = Game()
            print("Playing line: " + line)
            entries = line.split('|')
            winner = int(entries[-1])
            moves = entries[0:-1]
            for m in moves:
                if m and len(m.strip()) > 0:
                    parts = m.split(',')
                    print("Playing " + m)
                    r = int(parts[0])
                    c = int(parts[1])
                    g.play_cell(r, c)
                g.switch_players()
            if winner == 1:
                self.assertEquals(1, g.find_winner())
            elif winner == -1:
                self.assertEquals(-1, g.find_winner())
            else:
                self.assertFalse(g.has_won)
Example #4
0
    def test_game_shuffles_deck_on_play(self):
        mock_deck = MagicMock()
        mock_players = [MagicMock(), MagicMock()]
        game = Game(deck=mock_deck, players=mock_players)

        game.play()
        assert mock_deck.shuffle.called
Example #5
0
    def test_get_winner_return_the_winner(self):
        game = Game(self.player1, self.player2, self.pi)
        game.grid.fill(self.player2, 0, 1)
        game.grid.fill(self.player2, 1, 1)
        game.grid.fill(self.player2, 2, 1)

        self.assertEqual(self.player2, game.get_winner())
Example #6
0
 def test_check_numbers_with_different_numbers_does_not_return_size_value_as_good(
         self):
     SECRET_NUMBER = '1234'
     TEST_VALUE = '1235'
     game = Game()
     result = game.check_numbers(TEST_VALUE, SECRET_NUMBER)
     self.assertNotEqual(result['good'], SIZE)
Example #7
0
 def __init__(self):
     """Init game object."""
     super().__init__()
     try:
         self.game = Game()
     except AttributeError:
         print("Something went wrong! Start a new game.")
Example #8
0
 def test_player_play_card(self):
     player_one = MagicMock(name='p1')
     player_two = MagicMock(name='p2')
     player_one.draw_card.return_value = True
     game = Game(player_one, player_two)
     game.play_turn()
     player_one.play_cards.assert_called_once_with()
Example #9
0
 def test_player_get_damage_if_can_not_pick_card(self):
     player_one = MagicMock(name='p1')
     player_two = MagicMock(name='p2')
     player_one.draw_card.return_value = False
     game = Game(player_one, player_two)
     game.play_turn()
     game.get_players()[0].receive_damage.assert_called_once_with(1)
Example #10
0
    def test_is_won_return_the_winning_state(self):
        game = Game(self.player1, self.player2, self.pi)
        game.grid.fill(self.player1, 0, 0)
        game.grid.fill(self.player1, 0, 1)
        game.grid.fill(self.player1, 0, 2)

        self.assertTrue(game.is_won())
Example #11
0
    async def cmd____play(self, msg):
        if msg.chat_id > 0:  # нельзя играть одному
            await self.telebot.sendMessage(
                msg.chat_id,
                f"{msg.sender.first_name}, игру можно создать только в групповом чате не менее, чем на 4 человек."
            )
            return

        if self.app["games"].get(msg.chat_id,
                                 None) is not None:  # нельзя пересоздать игру
            return

        assert msg.chat_id < 0
        game = Game(msg.chat_id, self.app)
        game.add_player(msg.sender.id)
        self.app["games"][msg.chat_id] = game

        await self.telebot.sendMessage(
            msg.chat_id,
            f"*{msg.sender.first_name} {msg.sender.last_name}* желает начать новую игру.",
            reply_markup={
                "inline_keyboard": [[{
                    "text": "✔️ Присоединиться",
                    "callback_data": "/play:join"
                }, {
                    "text": "👎 Отказаться",
                    "callback_data": "/play:decline"
                }]]
            })
        # await self.sendAnimation("https://eva-bot.ru/res/small_timer_00_30.gif")
        self.app.loop.create_task(
            self.set_timeout_function(msg.chat_id, game.start, timer=1))
        return
Example #12
0
 def test_check_with_life(self):
     g = Game()
     g.initialize_enemies()
     ewl = g.check_with_life(g.list_enemies)
     cwl = g.check_with_life(g.list_characters)        
     self.assertEqual(ewl, False) 
     self.assertEqual(cwl, True)       
Example #13
0
 def test_attack_1to1(self):
     g = Game()
     one = PartialExam()
     uno = Worker()
     before = uno.hp
     g.attack(one, uno)
     self.assertTrue(before > uno.hp)
Example #14
0
    def test_game_deals_two_initial_cards_from_deck_to_each_player(self):
        mock_deck = MagicMock()
        mock_players = [MagicMock(), MagicMock()]
        game = Game(deck=mock_deck, players=mock_players)

        game.play()
        mock_deck.remove_cards.assert_has_calls([call(2), call(2)])
Example #15
0
    def test_game_stores_deck_and_players(self):
        mock_deck = MagicMock()
        mock_players = [MagicMock(), MagicMock()]
        game = Game(deck=mock_deck, players=mock_players)

        assert game.deck == mock_deck
        assert game.players == mock_players
    def test_can_create_empty_game(self):
        #Arrange
        g = Game()

        # Assert
        for row in g.board:
            for col in row:
                self.assertEquals(0, col)
Example #17
0
    def setUp(self):
        """Create instances at the beginning of tests cases."""
        self.game = Game()
        self.player = Player(str, bool)
        self.score_list = []
        self.dice = Dice()

        self.fake_die = random.randint(1, 6)
Example #18
0
    def test_playing_may_fill_an_empty_cell_with_first_player_on_first_play(self):
        self.pi.choose_cell = MagicMock(return_value=(0, 1))
        game = Game(self.player1, self.player2, self.pi)

        game.play()

        self.assertFalse(game.grid.is_empty())
        self.assertEqual('romain', game.grid.cells[0][1].player.name)
    def test_game_does_not_allow_playing_same_cell_twice(self):
        # Arrange
        g = Game()

        with self.assertRaises(Exception):
            g.play_cell(1, 1)
            g.switch_players()
            g.play_cell(1, 1)
Example #20
0
    def test_playing_a_filled_cell_raise_a_bad_cell_error(self):
        game = Game(self.player1, self.player2, self.pi)
        self.pi.choose_cell = MagicMock(return_value=(0, 1))

        game.play()

        with self.assertRaises(BadCellError):
            game.play()
    def test_cell_can_be_played(self):
        # Arrange
        g = Game()

        # Act
        g.play_cell(1, 2)

        # Assert
        self.assertEquals(g.current_player, g.get_cell(1, 2))
Example #22
0
def main():
    FPSCLOCK = 60
    pygame.init()
    fps_clock = pygame.time.Clock()

    screen = pygame.display.set_mode((1080, 700))
    pygame.display.set_caption("COMMET FALL GAME".upper())

    background = pygame.image.load("src/bg.jpg").convert()
    background_position = background.get_rect()
    background_position.x = 0
    background_position.y = -200

    banner = pygame.image.load("src/banner.png")
    banner = pygame.transform.scale(banner, (500, 500))
    banner_rect = banner.get_rect()
    banner_rect.x = math.ceil(screen.get_width() / 4)

    play_button = pygame.image.load("src/button.png")
    play_button = pygame.transform.scale(play_button, (400, 150))
    play_button_rect = play_button.get_rect()
    play_button_rect.x = math.ceil(screen.get_width() / 3.33)
    play_button_rect.y = math.ceil(screen.get_height() / 2)

    game = Game()

    while True:
        screen.blit(background, background_position)

        if game.is_playing:
            game.start_game(screen)
        else:
            screen.blit(play_button, play_button_rect)
            screen.blit(banner, banner_rect)
        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                game.pressed[event.key] = True
                if event.key == pygame.K_SPACE:
                    if game.is_playing:
                        game.player.launch_weapon()
                    else:
                        game.start()
                        game.sound_manager.play('click')
            elif event.type == pygame.KEYUP:
                game.pressed[event.key] = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if play_button_rect.collidepoint(event.pos):
                    game.start()
                    game.sound_manager.play('click')

        fps_clock.tick(FPSCLOCK)
        pygame.display.update()
Example #23
0
 def test_1_rang_field(self):
     game = Game()
     game.rang = 1
     game.hex_dictionary = {(0, 0): Color.White}
     random_computer_turn(game)
     assert (game.hex_dictionary == {(0, 0): Color.Red})
     game.hex_dictionary = {(0, 0): Color.White}
     smart_computer_turn(game)
     assert (game.hex_dictionary == {(0, 0): Color.Red})
Example #24
0
 def test_2_rang_field(self):
     game = Game()
     game.rang = 2
     game.hex_dictionary = {
         (0, 0): Color.White,
         (-1, 2): Color.Red,
         (1, 2): Color.Red,
         (0, 4): Color.Blue
     }
     assert (is_winner(game))
Example #25
0
def main():
    num_rounds = 5
    num_decks = 6

    game = Game(num_decks)
    for k in range(0, num_rounds):
        game.round()

    print("Total wins = {}, win rate = {:.1%}".format(game.player.wins, game.player.wins / num_rounds))
    input("Press Enter to exit...")
Example #26
0
def start():
    input = bytes.decode(request.data)
    inputDict = json.loads(input)
    x, y = int(inputDict['x']), int(inputDict['y'])
    g = Game(x, y)
    level = g.grid.serialize_level()
    session['level'] = level
    return jsonify(level=session['level'],
                   endgame=False,
                   size=[g.grid.height, g.grid.width])
Example #27
0
    def test_playing_change_the_current_user(self):
        game = Game(self.player1, self.player2, self.pi)

        self.pi.choose_cell = MagicMock(return_value=(0, 1))
        game.play()
        self.pi.choose_cell = MagicMock(return_value=(0, 2))
        game.play()

        self.assertFalse(game.grid.is_empty())
        self.assertEqual('romain', game.grid.cells[0][1].player.name)
        self.assertEqual('tristan', game.grid.cells[0][2].player.name)
Example #28
0
    def setUp(self):
        """Run at the beginning of the test."""
        self.game = Game()
        self.game.set_game_status(True)
        self.dice = Dice()

        self.player1 = Player(str, bool)
        self.player2 = Player(str, bool)
        self.computer_player = Player(str, bool)

        self.highscore = Highscore(self.player1, self.player2)
Example #29
0
def main():
    num_learning_rounds = 40000
    game = Game(num_learning_rounds, DQNLearner())  #Deep Q Network Learner
    #game = Game(num_learning_rounds, Learner()) #Q learner
    number_of_test_rounds = 1000
    for k in range(0, num_learning_rounds + number_of_test_rounds):
        game.run()

    df = game.p.get_optimal_strategy()
    print(df)
    df.to_csv('optimal_policy.csv')
Example #30
0
 def test_second_player_get_damage(self):
     player_one = MagicMock(name='p1')
     player_two = MagicMock(name='p2')
     player_one.get_life_point.side_effect = [2, 1]
     player_one.draw_card.return_value = True
     damage = random.randint(1111, 9999)
     player_one.play_cards.return_value = damage
     game = Game(player_one, player_two)
     is_defeat = game.play_turn()
     player_two.receive_damage.assert_called_once_with(damage)
     self.assertTrue(is_defeat)