def main(): display = pygame.display.set_mode( (Settings['game']['width'], Settings['game']['height'])) pygame.display.set_caption(Settings['game']['caption']) game = Game(display) game.loop()
def mcts(self, moves): results = {col: 0 for col in moves} wins = 0 for col in moves: for j in range(self.n_iter): new_b = deepcopy(self.board) p1dummy = Player(self.name, new_b, 1) opponent = 1 if self.name == 2 else 2 p2dummy = Player(opponent, new_b) g = Game(new_b, p1dummy, p2dummy) g.play_a_game(first_move=col) n_new_plays = new_b.plays - self.board.plays if g.winner == self.name: results[col] += 0.9**n_new_plays wins += 1 elif g.winner is None: results[col] += (0.5 * 0.9)**n_new_plays else: results[col] -= 0.9**(n_new_plays - 1) rounded_res = { col: round(result, 2) for col, result in results.items() } print(f'Player {self.name} results: {rounded_res}') iter_tot = self.n_iter * len(results) print(f'Player {self.name} P(win):' f' {round(wins / iter_tot * 100, 2)}%') return max(results.items(), key=lambda x: x[1])[0]
def run_game(auto, map_idx, brain_module, infile=''): if auto not in ("simple", "advanced"): print("Invalid auto mode") return (None, None, None, None) map_list = [Map0, Map1, Map2, Map3, Map4, Map5] if map_idx not in range(len(map_list)): print("Invalid map index") return (None, None, None, None) os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (500, 30) walls, checkpoints, finish_line, rocks, car_origin, hud_pos = map_list[ map_idx] car = copy.copy(car_origin) lidar = LiDAR() control = Control() database = Database(lidar, control, car) game = Game(walls, checkpoints, finish_line, rocks, car, database, hud_pos=hud_pos, close_at_end=True) if auto == "simple" and infile is None: print("No input file to run evaluation") return (None, None, None, None) if auto == "advanced" and brain_module is None: print("No brain module to run evaluation") return (None, None, None, None) ### suppress stdout from game brain stdout = sys.stdout if platform.system() == 'Windows': dev_null = open('nul', 'w') else: dev_null = open('/dev/null', 'w') sys.stdout = dev_null brain = brain_module.Brain( database) if auto == "advanced" else TimeEventBrain(database, infile) print("Loaded brain module: {}".format(brain)) brain_thread = threading.Thread(target=brain.run, args=( g_sync_cv, g_brain_cv, )) brain_thread.start() res = game.runAuto(cv=g_sync_cv, bcv=g_brain_cv) brain_thread.join() sys.stdout = stdout return res
class App(): """Manage game loop of input -> process -> render.""" def __init__(self) -> None: """Constructor.""" self.input = PlayerInput() self.game = Game() self.renderer = Renderer() self.is_app_running = True def run(self): """Game loop.""" self.renderer.render(self.game.match) while self.is_app_running: input_registered, key = self.input.wait_for_user_input() if input_registered: if self._is_user_quitting(key): self._quit_game() else: self.game.process_input(key) self.renderer.render(self.game.match) def _is_user_quitting(self, key): return (key == UserInput.KEY_Q) def _quit_game(self): self.renderer.clear_console() self.is_app_running = False
def test_get_points_draws(): team = Team('Santa Cruz Slugs') enemy = Team('Aptos FC') team.add_game(Game(team, 10, enemy, 10)) team.add_game(Game(team, 0, enemy, 0)) assert team.get_points(1) == 1 assert team.get_points(2) == 2
def __init__(self) -> None: """Constructor.""" self.input = PlayerInput() self.game = Game() self.renderer = Renderer() self.is_app_running = True
def main(): display = pygame.display.set_mode( (Config['game']['width'], Config['game']['height'])) pygame.display.set_caption(Config['game']['caption']) game = Game(display) game.loop()
def test_get_points_variety(): team = Team('Santa Cruz Slugs') enemy = Team('Aptos FC') team.add_game(Game(team, 10, enemy, 0)) team.add_game(Game(team, 5, enemy, 10)) team.add_game(Game(team, 5, enemy, 5)) team.add_game(Game(team, 10, enemy, 10)) assert team.get_points(4) == 5
def main(): game = Game() game.load_level(0) get_delta_time = delta_time_gen().__next__ while tick(get_delta_time(), game): continue
def test_draw_start_hand(self): player_names = [ 'Samuel', 'Gustav', 'Maria', 'Andrea', 'Tomas', 'Mona', 'Lennart' ] game_object = Game(player_names) game_object.draw_start_hand() for player in game_object.players: self.assertEqual(player.health, len(player.hand))
def main(): display = pygame.display.set_mode((Config['game']['height'],Config['game']['width'])) pygame.display.set_caption(Config['game']['caption']) #create a 800x600 pixel game window with title game = Game(display) #pass reference to display into game object game.start_screen()
def test_generate_points(): league = League() team1 = Team('Santa Cruz Slugs') team2 = Team('Aptos FC') league.add_game(Game(team1, 10, team2, 0)) league.add_game(Game(team1, 0, team2, 0)) league.add_game(Game(team1, 1, team2, 1)) assert league.generate_points(3) == [(team1, 5), (team2, 2)]
class Test(unittest.TestCase): def setUp(self): self.game = Game(Player("a"), Player("b"), Board("go")) self.game.player1.record( Action.put(1, 1, Position(Piece("a"), Player("a")))) self.game.player1.record(Action.see(1, 1)) def test_print_history(self): self.game.print_history()
def test_game_is_over(self, player_1, player_2, score_manager, expected): game = Game(None, None, score_manager) game.players[0].name = player_1.name game.players[0].score = player_1.score game.players[1].name = player_2.name game.players[1].score = player_2.score assert (game.is_over() == expected)
def test_teams_getting_set(): league = League() team1 = Team('Santa Cruz Slugs') team2 = Team('Aptos FC') team3 = Team('Monterey United') league.add_game(Game(team1, 10, team2, 0)) league.add_game(Game(team1, 10, team3, 0)) assert league.teams.count(team1) == 1 assert league.teams.count(team2) == 1 assert league.teams.count(team3) == 1
def rollout_game(self, player, board): new_b = deepcopy(board) p1dummy = tfPlayer(player.name, new_b, player.sess, player.pred, player.input_placeholder, True) opponent = 1 if player.name == 2 else 2 p2dummy = Player(opponent, new_b) g = Game(new_b, p1dummy, p2dummy) g.play_a_game(first_move=self.col) n_new_plays = new_b.plays - board.plays return g.winner, n_new_plays
async def top_game(message: types.Message): logger.info('top/ Chat_id:' + str(message.chat.id) + " Name: " + str(message.from_user.full_name)) id_chat = message.chat.id g = Game(chat_id=id_chat) if g.is_active(): wg = WordGame(chat_id=id_chat) await message.answer(text=wg.get_top(), parse_mode=types.ParseMode.HTML) else: await message.reply(text="<b>Інформація відсутня</b>, так як гра не активна", parse_mode=types.ParseMode.HTML)
async def stop_game(message: types.Message): logger.info('stopgame/ Chat_id:' + str(message.chat.id) + " Name: " + str(message.from_user.full_name)) id_chat = message.chat.id g = Game(chat_id=id_chat) if g.is_active(): g.deactivate() await message.answer("<i>Активну ігру зупинено</i>", parse_mode=types.ParseMode.HTML) else: await message.reply("<i>Активної ігри не знайдено</i>", parse_mode=types.ParseMode.HTML)
class testBoard(TestCase): def setUp(self): self.game = Game() def testThatAGameCanHaveZones(self): zone = Mock() self.game.addZone(zone) self.assertIn(zone, self.game.zones) def testThatAGameHasPlayers(self): player = Mock() self.game.addPlayer(player) self.assertIn(player, self.game.players)
def main(auto, map_idx): map_list = [Map0, Map1, Map2, Map3, Map4, Map5] if map_idx not in range(len(map_list)): print("Invalid map index") return os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (500, 30) walls, checkpoints, finish_line, rocks, car, hud_pos = map_list[map_idx] lidar = LiDAR() control = Control() database = Database(lidar, control, car) game = Game(walls, checkpoints, finish_line, rocks, car, database, hud_pos=hud_pos) brain_thread = None if auto is not None: brain = Brain(database) if auto == "advanced" else TimeEventBrain(database) brain_thread = threading.Thread(target=brain.run, args=(g_sync_cv, g_brain_cv,)) brain_thread.start() res_win = None # win condition status res_time = None # total time res_dist = None # total distance res_ckpt = None # checkpoints if auto: res_win, res_time, res_dist, res_ckpt = game.runAuto(cv=g_sync_cv, bcv=g_brain_cv) else: res_win, res_time, res_dist, res_ckpt = game.runManual() if brain_thread is not None: brain_thread.join() if res_win is not None: if res_win: print("Congrats! You won") else: print("Too bad! You lose") print("### REPORT ###") print("Running time: {:.3f}".format(res_time / 1000.0)) print("Running dist: {:.1f}".format(res_dist)) if res_ckpt.items(): print("Checkpoints:") for k, v in res_ckpt.items(): print("- {} : time {:.03f} - dist: {:.1f}".format(k, v["time"] / 1000.0, v["distance"])) else: print("Exit") pygame.quit() return 0
def test_game_lots(self): players = 5 games = 100 stats = {i: [0, 0] for i in range(players)} for count in range(games): g = Game(players) g.play() for i, s in g.get_stats().items(): stats[i][0] += s[0] stats[i][1] += s[1] for i, s in stats.items(): print("Player {} - Victories {} ({}%), Score {}". format(i, str(s[0]), str((s[0]*100) / (games*13)), str(s[1])))
def test_score_wrong_match_second_card_when_card_already_seen(): game = Game(Terminal(), Difficulty.NORMAL) seen_card = Card(CardValue.TWO, Suit.HEARTS) game.board[0][0] = Card(CardValue.ACE, Suit.CLUBS) game.board[0][1] = seen_card game.selected = [(0, 0), (0, 1)] game.seen[seen_card] = [(0, 1)] assert game.calculate_score() == -1 game.difficulty = Difficulty.HARD assert game.calculate_score() == -2
def smart_move(self): available_moves = self.search_available_moves() if available_moves: for col in available_moves: new_b = deepcopy(self.board) p1dummy = Player(self.name, new_b) opponent = 1 if self.name == 2 else 2 p2dummy = Player(opponent, new_b) g = Game(new_b, p1dummy, p2dummy) g.one_move(col) if g.winner == self.name: return col return random.choice(available_moves) else: return -1
def test_multiplayer_nonbust(self): """ Tests a simple two-player game of blackjack where both players stay """ g = Game(['bob', 'jane']) ace = Card('ace', [1, 11]) king = Card('king', [10]) self.assertTrue(g.hit(ace)) self.assertTrue(g.hit(king)) g.stay() self.assertTrue(g.hit(king)) self.assertTrue(g.hit(king)) g.stay() winner = g.get_winner() self.assertEqual(winner, 'bob')
def setUp(self): side0 = Side((10, 10), (10, 400), 1.0) side1 = Side((10, 400), (400, 400), 1.0) side2 = Side((400, 400), (400, 10), 1.0) side3 = Side((400, 10), (10, 10), 1.0) self.arena = Arena((side0, side1, side2, side3)) self.ball0 = Ball([250, 200], [1, 1], 3, 10) self.ball1 = Ball([200, 250], [1, -1], 2, 10) self.background_color = (0, 0, 0) self.ball0_color = (51, 255, 204) self.ball1_color = (204, 255, 51) self.game = Game((), self.arena, (self.ball0, self.ball1), (self.ball0_color, self.ball1_color))
def test_score_wrong_match_when_location_of_match_seen(): game = Game(Terminal(), Difficulty.NORMAL) card = Card(CardValue.ACE, Suit.CLUBS) other_card = Card(CardValue.TWO, Suit.HEARTS) game.board[0][0] = card game.board[0][1] = other_card game.selected = [(0, 0), (0, 1)] game.seen[card] = [(0, 2)] assert game.calculate_score() == -1 game.difficulty = Difficulty.HARD assert game.calculate_score() == -2
def test_create_players_exception(self): player_names = [ 'Samuel', 'Gustav', 'Maria', 'Andrea', 'Tomas', 'Mona', 'Lennart', 'Monna' ] with self.assertRaises(StartGameException): Game(player_names)
def set_up_game() -> Game: """ This function sets up the logic and data structures for the game by initializing relevant classes """ global GAME_MODE game_board = Board(DIMENSION) player1 = Human("Player 1", game_board) if GAME_MODE == 0: return Game(player1, Human("Player 2", game_board), game_board) elif GAME_MODE == 1: return Game(player1, EasyAI("Player 2", game_board), game_board) elif GAME_MODE == 2: return Game(player1, MediumAI("Player 2", game_board), game_board) elif GAME_MODE == 3: return Game(player1, HardAI("Player 2", game_board), game_board)
def test_score_wrong_match_and_card_not_already_seen(): game = Game(Terminal(), Difficulty.NORMAL) game.board[0][0] = Card(CardValue.THREE, Suit.SPADES) game.board[0][1] = Card(CardValue.TWO, Suit.HEARTS) game.selected = [(0, 0), (0, 1)] assert game.calculate_score() == 0 game.difficulty = Difficulty.HARD assert game.calculate_score() == -1
def eval_genomes(self, genomes, config): self.GENERATION_NUMBER += 1 for _, snake in genomes: snake.alive = True snake.fitness = 0 g = Game(genomes, config) g.loop() maxScore = 0 for _, snake in genomes: if snake.fitness > maxScore: maxScore = snake.fitness print("Max score for generation : " + str(self.GENERATION_NUMBER) + " is " + str(maxScore))
def setUp(self) -> None: self.w = Wheel() bb = BinBuilder(self.w) bb.buildBins() self.t = Table() self.p = Passenger57(self.t, self.w) self.g = Game(self.t, self.w) self.sim = Simulator(self.p, self.g)
def test_get_team_by_name(): league = League() team1 = Team('Santa Cruz Slugs') team2 = Team('Aptos FC') league.add_game(Game(team1, 10, team2, 0)) assert league.get_team_by_name('Santa Cruz Slugs') is team1 assert league.get_team_by_name('Aptos FC') is team2 assert league.get_team_by_name('missing') is None
class GameTests(): def setUp(self): side0 = Side((10,10), (10,400), 1.0) side1 = Side((10,400), (400,400), 1.0) side2 = Side((400,400), (400,10), 1.0) side3 = Side((400,10), (10,10), 1.0) self.arena = Arena((side0, side1, side2, side3)) self.ball0 = Ball([250, 200], [1, 1], 3, 10) self.ball1 = Ball([200, 250], [1, -1], 2, 10) self.background_color = (0, 0, 0) self.ball0_color = (51, 255, 204) self.ball1_color = (204, 255, 51) self.game = Game((), self.arena, (self.ball0, self.ball1), (self.ball0_color, self.ball1_color)) def run(self): self.game.render()
#!/usr/bin/env python """ Executable for starting the game. """ from src.Game import Game if __name__ == '__main__': game = Game() game.start()
def setUp(self): self.game = Game()
def test_game(self): g = Game(5) g.play(True)
def createGame(self, players, zones): game = Game() for player in players: game.addPlayer(player) for zone in zones: game.addZone(zone) return game