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())
def __init__(self): """Init game object.""" super().__init__() try: self.game = Game() except AttributeError: print("Something went wrong! Start a new game.")
def check_answer_correct(button_name: str, game: Game) -> None: if game.game_on and game.question_shown and not game.question_answered: game.question_answered = True letter = button_name[-1] answer_widget = get_widget(answers_localization + letter) confirm_final_answer(answer_widget) final_ans_sound = game.get_music_for_question()[2] if game.double_dip == game.question_number: play(game.lifeline_themes[4]) change_button_image(ddip_localization, "doubledipused.png") elif final_ans_sound is not None: play(final_ans_sound) user_answer = answer_widget.get("1.0", "end-1c") time_verification = 0 if game.question_number < game.guaranteed_questions[0]: time_verification = 2000 elif game.question_number == game.guaranteed_questions[0]: time_verification = 3000 elif game.question_number < game.guaranteed_questions[1]: time_verification = 4500 elif game.question_number == game.guaranteed_questions[2]: time_verification = 6000 else: time_verification = 7000 gui.after( time_verification, lambda: verify_correct_answer( game, user_answer, answers, answers_localization))
class TestHigscore(unittest.TestCase): """Test Higscore Class.""" def setUp(self): """Run at the beginning of the test.""" self.game = Game() self.mock_player1 = Mock(spec=Player, name="player1", score=42, decision=False) self.mock_player2 = Mock(spec=Player, name="Computer", score=65, decision=True) self.assertIsInstance(self.mock_player1, Player) self.assertIsInstance(self.mock_player2, Player) self.score = Highscore(self.mock_player1, self.mock_player2) def test_write_file(self): """Test write_file.""" self.player1 = Player("score1", False) self.game.set_playing_now(self.game.player1) self.player1.change_score(5) self.score.write_file() self.player2_name = Player("score2", False) self.game.set_playing_now(self.game.player2) self.player1.change_score(4) def test_get_path(self): """Test get_path.""" exp = self.score.get_path() self.assertTrue(exp, 'score.txt')
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)])
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()
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
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
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)
def test_attack_1to1(self): g = Game() one = PartialExam() uno = Worker() before = uno.hp g.attack(one, uno) self.assertTrue(before > uno.hp)
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())
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_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})
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))
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))
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...")
def verify_correct_answer(game: Game, user_answer: str, answers: List[str], localization: str) -> None: green_answer(answers, localization) if game.answer_correct(user_answer, game.current_question): winning_sequence() else: losing_sequence() game.question_answered = False game.question_shown = False
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))
def test_players_can_swap_between_current_player(self): # Arrange g = Game() # Act first = g.current_player g.switch_players() second = g.current_player # Assert self.assertNotEqual(first, second)
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')
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)
def test_player_defeat_if_has_one_lv_but_no_card(self): player_one = MagicMock(name='p1') player_two = MagicMock(name='p2') player_one.get_life_point.side_effect = [1, 0] player_one.draw_card.return_value = False game = Game(player_one, player_two) is_defeat = game.play_turn() player_one.get_life_point.assert_called_with() player_one.draw_card.assert_called_once_with() player_one.add_mana.assert_called_once_with(1) self.assertFalse(is_defeat)
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)
def main(): num_learning_rounds = 20000 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")
def move(): data = bottle.request.json game1 = Game(data['height'], data['width'], data['game_id']) game1.parse_data(data) move = game1.move() # TODO: Do things with data directions = ['up', 'down', 'left', 'right'] taunt = taunts(game1.snakes[0]["health_points"]) return {'move': move, 'taunt': taunt}
def on_create(data): """Create a game lobby""" app.logger.info("Creating a new game!") curr_game = Game() # TODO: check for duplicate names player = Player(data['name'], curr_game, request.sid) curr_game.players[data['name']] = player ROOMS[curr_game.id] = curr_game USERS[player.sid] = player join_room(curr_game.id) emit('set_username', data['name']) emit('user_data', player.to_json()) emit('join_room', {'room': curr_game.to_json()})
def test_init(self): game = Game(6, 6) cell_01 = game.grid.get_cell(0, 1) cell_01.state = 1 print(game.grid) game.event_grid(cell_01.pos[0], cell_01.pos[1]) print(game.grid) self.assertCountEqual([1, 1, 1], [ game.grid.get_cell(r[0], r[1]).state for r in [(0, 2), (0, 0), (1, 1)] ])
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)
def setUp(self): """Run at the beginning of the test.""" self.game = Game() self.mock_player1 = Mock(spec=Player, name="player1", score=42, decision=False) self.mock_player2 = Mock(spec=Player, name="Computer", score=65, decision=True) self.assertIsInstance(self.mock_player1, Player) self.assertIsInstance(self.mock_player2, Player) self.score = Highscore(self.mock_player1, self.mock_player2)
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)
def __init__(self): self.logger.debug("Init App...") self.title = self._HINT_IN_TITLE self.state = AppState() self.__init_pygame() self.events = EventManager() self.events.subscribe(event_type=pygame.QUIT, callback=self.state.stop, ) self.events.subscribe(event_type=pygame.KEYDOWN, callback=self.state.stop, conditions={"key": pygame.K_q}) self.events.subscribe(event_type=pygame.KEYDOWN, callback=self.state.stop, conditions={"key": pygame.K_ESCAPE}) self.game = Game()
def process_user_input(self, state): for event in pygame.event.get(): if event.type == self.music.song_end: print("song has ended") self.music.play_next_song() if event.type == pygame.QUIT: state = States.QUIT if state == States.MENU: state = States.MENU.process_user_input(event) if state == States.BOARD_GAME: self.game = Game(self.screen, self.surface, self.music) elif state == States.BOARD_GAME: state = self.game.process_user_input(event) return state
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)
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)
def on_message(self, data): print 'message received %s' % data message = tornado.escape.json_decode(data) Game.on_message(message, self)