def __init__(self, game): self.parser_state = "" self.network_host = "" self.start_time = time.time() self.total_received_messages = [] try: self.game_state = gamestate.GameState( json.load(open("games\\{}\\initialstate.cgs".format(game)), "utf-8")) except IOError: self.game_state = gamestate.GameState()
def test_max_value(self): # Case Player 1 (max_value) game is over (works for dim_x = 3 , dim_y = 2) game = gamestate.GameState() game._board = [[2, 0], [1, 2], [1, '/']] game._player_1_position = (2, 0) game._player_2_position = (1, 1) self.assertEqual(mmh.max_value(game), -1) # Case Player 1 (max_value) game is not over (works for dim_x = 3 , dim_y = 2) game = gamestate.GameState() game._board = [[0, 0], [1, 0], [2, '/']] game._player_1_position = (1, 0) game._player_2_position = (2, 0) self.assertEqual(mmh.max_value(game), 1)
def test_min_value(self): # Case Player 2 (min_game is over (works for dim_x = 3 , dim_y = 2) game = gamestate.GameState() game._board = [[1, 2], [1, 2], [2, '/']] game._player_1_position = (2, 0) game._player_2_position = (0, 1) game._initiative = 2 self.assertEqual(mmh.min_value(game), 1) # Case Player 2 (min_value) game is not over (works for dim_x = 3 , dim_y = 2) game = gamestate.GameState() game._board = [[1, 0], [2, 0], [0, '/']] game._player_1_position = (0, 0) game._player_2_position = (1, 0) self.assertEqual(mmh.min_value(game), -1)
def play_game(self, ANET1, ANET2, start_player): root_node = node.Node(parent=None, state=gamestate.GameState(player=1, dimensions=self.hex_dimension)) root_node.state.initialize_hexboard() if self.verbose: root_node.state.print_hexboard() agents = [ANET1, ANET2] current_player = start_player while not root_node.state.game_over(): best_move_node = agents[current_player - 1].find_move(root_node) if self.verbose: print("Move found by {}".format(agents[current_player-1].name)) root_node = best_move_node current_player = 3 - current_player if self.verbose: root_node.state.print_hexboard() winner = root_node.state.get_winner() if start_player == 2: agents[winner-2].wins += 1 else: agents[winner - 1].wins += 1 if self.verbose: if start_player == 2: print("The game is over and {} won.".format(agents[winner - 2].name)) else: print("The game is over and {} won.".format(agents[winner - 1].name))
def main(): if check_and_inform_window_size() == "return": return while True: # Global gamestate and gameaction instances gs = gamestate.GameState() ga = gameaction.GameAction(gs) main_menu.clear_screen() main_menu_choice = main_menu.main_menu() if main_menu_choice == 1: game_play.game_play(ga) elif main_menu_choice == 2: main_menu.clear_screen() ga, load_menu_choice = load_save_menu.load_game(ga) if load_menu_choice == 4: continue game_play.game_play(ga) elif main_menu_choice == 3: # insert confirmation check main_menu.clear_screen() exit_choice = main_menu.exit_game_confirmation() if exit_choice == 2: # 1 == exit, 2 == stay continue sys.stdout.write("\033[K") # clear line print("\nThanks for playing! Good-bye!") input("\nPress [Enter] to continue...\n") break
def get_state(self): while True: gamewindow = screencapturer.capture_gamewindow() gamewindow = ImageProcessor.resize_gamewindow(gamewindow) playfields = ImageProcessor.extract_playfields_from_gamewindow( gamewindow) cursor_coords = [None, None] cursor_position = [None, None] playfield_matrices = [None, None] game_active = [False, False] for player in PLAYERS: cursor_coords_player = ImageProcessor.determine_cursor_coords( playfields[player]) if cursor_coords_player is not None: cursor_coords[player] = cursor_coords_player cursor_position_player = ImageProcessor.determine_cursor_position( cursor_coords[player]) if cursor_position_player is not None: cursor_position[player] = cursor_position_player playfield_matrices_player = ImageProcessor.determine_playfield_matrices( playfields[player], cursor_coords[player]) if np.sum(playfield_matrices_player[:, :, PANELS]) > 0: playfield_matrices[ player] = playfield_matrices_player game_active[player] = True state = gamestate.GameState() state.playfield_matrices = playfield_matrices state.cursor_position = cursor_position state.game_active = game_active return state
def run_game(fog_on=False): """Runs the game through the CLI.""" game_state = gamestate.GameState(fog_on=fog_on) input_string = 'pass' while input_string != 'q': args = input_string.split(' ') command = args[0] if len(args) == 1: command_iterations = 1 elif len(args) == 2: command_iterations = int(args[1]) else: print('command not recognized') continue try: for i in range(command_iterations): handle_command(game_state, command) except InvalidCommandException as e: print(e) except gamestate.DevModeException as e: print(e) print('total points: {}'.format(game_state.points)) game_state.print_state() percepts = game_state.get_percepts() print(get_percept_message(percepts)) # print('player: {}'.format(game_state.player_location)) # print('facing: {}'.format(game_state.player_orientation)) # print(game_state.get_percepts()) input_string = input('Next move? ')
def __init__(self, width, height, title): # Call the parent class's init function super().__init__(width, height, title) # Set the background color arcade.set_background_color(BACKGROUND_COLOUR) #Flags... self.menu_flag = True self.options_flag = False self.within_game_flag = False #Button Highlighting self.highlight_play = False self.highlight_options = False self.highlight_quit = False #Game stuff self.game = gamestate.GameState() self.level = self.game.player_data['level'] self.ticks = 0 #basically a clock self.key_down_held = False self.duration = 0 #only used when holding DOWN
def get_ai_iteration_generator(agent, game_state=None, fog_on=True): """ Create a turn iteration generator. If game_state is defined, the fog will be determined by the gamestate that was given. """ if game_state: current_state = game_state else: current_state = gamestate.GameState(fog_on=fog_on) # yield turn 0 for the first move yield current_state while True: # no end condition defined by book current_percepts = current_state.get_percepts() agent_move = poll_agent(agent, current_percepts) if agent_move == 'left': current_state.turn_left() elif agent_move == 'right': current_state.turn_right() elif agent_move == 'forward': current_state.move_forward() elif agent_move == 'shoot': current_state.shoot() elif agent_move == 'grab': current_state.grab() elif agent_move == 'climb': current_state.climb() else: raise AgentException( 'Agent returned an illegal action: {}'.format(agent_move)) yield current_state
def play(game_tree: t.GameTree) -> None: p.print_line('') p.print_line('......') state = s.GameState(game_tree.scene) first_episode = game_tree.scene.episodes[0] play_episode(first_episode, state)
def __init__(self, server_address, auth_token): super(GSIServer, self).__init__(server_address, RequestHandler) self.auth_token = auth_token self.gamestate = gamestate.GameState() self.parser = payloadparser.PayloadParser() self.running = False
def initialize_gamestate(self, game_info): self.gamestate = gamestate.GameState( friendly_player=self.client.name, enemy_player='?', gameboard=gb.Gameboard(game_info['Width'], game_info['Height']), view_distance=game_info['FogOfWar']) self.gamestate.turn_number = game_info['Turn'] self.gamestate.total_food = game_info['TotalFood']
def play_game(game_idx): was_closed = False step = 0 if not os.path.isdir(str(game_idx)): os.mkdir(str(game_idx)) while not was_closed: game = gamestate.GameState() button_pressed = config.play_game_button #graphics.draw_main_menu(game) if button_pressed == config.play_game_button: game.start_pool() events = event.events() while not (events["closed"] or game.is_game_over or events["quit_to_main_menu"] or step == 10): print(step) events = event.events() collisions.resolve_all_collisions(game.balls, game.holes, game.table_sides) game.redraw_all() table = np.zeros((config.resolution[0], config.resolution[1])) for i in range(len(list(game.balls))): pos = list(game.balls)[i].ball.pos table[[ int(pos[0] + cos(i * 2 * pi / 360) * 12.5) for i in range(360) ], [ int(pos[1] + sin(i * 2 * pi / 360) * 12.5) for i in range(360) ]] = 1 plt.imshow(table, cmap='gray') plt.savefig(str(game_idx) + '/' + str(step) + '.png') step += 1 if game.all_not_moving(): game.check_pool_rules() game.cue.make_visible(game.current_player) while not ( (events["closed"] or events["quit_to_main_menu"]) or game.is_game_over) and game.all_not_moving(): game.redraw_all() events = event.events() if True: #game.cue.is_clicked(events): game.cue.cue_is_active(game, events) elif game.can_move_white_ball and game.white_ball.is_clicked( events): game.white_ball.is_active( game, game.is_behind_line_break()) was_closed = True #events["closed"] if button_pressed == config.exit_button: was_closed = True print('closing') pygame.quit() print('done')
def start(player1_type, player2_type): """human = 0, random = 1, minimax = 2,alphabeta = 3""" import gamestate as g import player as p import gameoperator as game state = g.GameState() player1 = p.Player(1, player1_type) player2 = p.Player(2, player2_type) begin = game.GameOperator() begin.startplay(state, player1, player2)
def __init__(self): self._handler = None self.suspended = {} try: profile = data.load_profile('main.profile') except IOError: profile = None self.gamestate = gamestate.GameState(profile) self.keys = key.KeyStateHandler() self.music = music.MusicManager()
def test_valid_load_game_state(self): # Values to test against self.game_state._turns_remaining = 123 self.game_state._current_location = "Gato Springs" self.game_state._current_inventory = ["key", "rock"] self.game_state._solved_puzzles = {1: "puzzle one", 5: "puzzle five"} self.game_state._obtained_clues = {3: "clue three", 7: "clue seven"} self.game_state._lair_location = "Paradise Creek" self.game_state._visited["Lemonfield"] = True # savedgame directory dirname = os.path.join(os.path.realpath('.'), "savedgames") # Create save file, and load back save file and verify data for num in range(3): # Create a saved game file save_slot = num + 1 self.game_state.save_game_state(save_slot) # Instantiate new gamestate object and assert initial values gs = gamestate.GameState() self.assertEqual(gs._turns_remaining, gamestate.INITIAL_NUMBER_OF_TURNS) self.assertEqual(gs._current_location, "City Hall") self.assertEqual(gs._current_inventory, []) self.assertEqual(gs._solved_puzzles, {}) self.assertEqual(gs._obtained_clues, {}) self.assertEqual( gs._lair_location in ('Webster Mountain', 'Paradise Creek', 'Coltwood', 'Lake Cypress'), True) self.assertEqual(gs._visited["Lemonfield"], False) # Load in saved game data and assert expected value self.assertEqual(gs.load_game_state(save_slot), 0) self.assertEqual(gs._turns_remaining, 123) self.assertEqual(gs._current_location, "Gato Springs") self.assertEqual(gs._current_inventory, ["key", "rock"]) self.assertEqual(gs._solved_puzzles, { 1: "puzzle one", 5: "puzzle five" }) self.assertEqual(gs._obtained_clues, { 3: "clue three", 7: "clue seven" }) self.assertEqual(gs._lair_location, "Paradise Creek") self.assertEqual(gs._visited["Lemonfield"], True) # Remove saved files for clean up for num in range(3): filename = "savedgame_" + str(num + 1) fullpath = os.path.join(dirname, filename) os.remove(fullpath)
def object_decoder(dct): """evaluate our dictionary and create the correct type of object then initialize that object with the dictionary """ if 'uniqID' in dct: gs_temp = gamestate.GameState() gs_temp.init_dict(dct) return gs_temp elif 'diceRolled' in dct: ts_temp = gamestate.TurnState() ts_temp.init_dict(dct) return ts_temp return dct
def test_terminal_test(self): # Case Player 1 game is not over works for dim_x = 3 , dim_y = 2) game = gamestate.GameState() self.assertEqual(mmh.terminal_test(game), False) # Case Player 1 game is over (works for dim_x = 3 , dim_y = 2) game = gamestate.GameState() game._board = [[2, 0], [1, 2], [1, '/']] game._player_1_position = (2, 0) game._player_2_position = (1, 1) self.assertEqual(mmh.terminal_test(game), True) # Case Player 2 game is not over works for dim_x = 3 , dim_y = 2) game = gamestate.GameState() game_future = game.forecast_move((0, 0)) self.assertEqual(mmh.terminal_test(game_future), False) # Case Player 2 game is over (works for dim_x = 3 , dim_y = 2) game = gamestate.GameState() game._board = [[1, 2], [1, 2], [2, '/']] game._player_1_position = (2, 0) game._player_2_position = (0, 1) game._initiative = 2 self.assertEqual(mmh.terminal_test(game), True)
def setUp(self): self.gamestate = gs.GameState() setup_data = """ turn 0 loadtime 3000 turntime 1000 rows 42 cols 38 turns 500 viewradius2 55 attackradius2 5 spawnradius2 1 player_seed 42 ready """ self.gamestate.setup(setup_data)
def play(self,x,y): self.was_closed = False while not self.was_closed: game = gamestate.GameState() button_pressed = config.play_game_button if button_pressed == config.play_game_button: game.start_pool() events = event.events() self.reward=0 while not (events["closed"] or game.is_game_over or events["quit_to_main_menu"]): events = event.events() self.reward=collisions.resolve_all_collisions(game.balls, game.holes, game.table_sides,self.reward) game.redraw_all() store_ball_list=dict() if game.all_not_moving(): print("\n*****************************") for ball in game.balls: store_ball_list[ball.number]=ball.ball.pos #print("ball {} not moving : {}".format(ball.number,ball.ball.pos)) game.check_pool_rules() game.cue.make_visible(game.current_player) if 0 not in store_ball_list: store_ball_list[0]=game.give_value() #print("如果陣列中沒有白球位置請看這裡 : {}".format(game.give_value())) print("all balls : ",store_ball_list) print("reward : {}".format(self.reward)) while not ( (events["closed"] or events["quit_to_main_menu"]) or game.is_game_over) and game.all_not_moving(): game.redraw_all() events = event.events() if 1: # x=int(input("x : ")) # y=int(input("y : ")) game.cue.cue_is_active(game, events,(x,y)) elif game.can_move_white_ball and game.white_ball.is_clicked(events): game.white_ball.is_active(game, game.is_behind_line_break()) self.return_command=str(self.reward)+"*"+str(self.was_closed) self.was_closed = True
def start_handler(data): """ start a new turn on farkle. requires the following post parameters: bet - number of credits to wager mode - LONG, NORMAL or TUTORIAL player_id - uuid of the player login_key - validation key for the player session - if continuing existing game, include session. can also start a new game with previous session """ # set our defaults if 'bet' not in data: data['bet'] = 500 if 'mode' not in data: data['mode'] = 'NORMAL' if 'session' not in data: data['session'] = '' if 'player_id' not in data: data['player_id'] = '' try: db_conn = get_dynamo() data['player_id'] = str(data['player_id']) if len(str(data['session'])) > 15: game_state = load_gamestate(db_conn, data['session']) if str(game_state.player_id) != data['player_id']: game_state.message = "wrong player id" return format_response(game_state, None, 502) if game_state.gameOver: game_state.gameMode = data['mode'] else: game_state = gamestate.GameState() # create new player if play_id not set if data['player_id'] == '': player_1 = player.Player() else: player_1 = load_player(db_conn, data['player_id']) game_state.gameMode = data['mode'] game_state.update_from_player(player_1) game_state.start_turn(int(data['bet'])) update_gamestate(db_conn, game_state) return format_response(game_state) except Exception as exception: return format_response({'message': str(exception)}, None, 502)
def run_perft(self): start_time = time.time() for j, test_case in enumerate(test_positions): answers = test_case.split()[-1].split(',')[1:] fen = ' '.join([ test_case.split()[0], test_case.split()[1], test_case.split()[2], test_case.split()[3].split(',')[0] ]) gamestate = gs.GameState(fen) gamestate.is_white_turn = True if 'w' in fen else False # Run perft test with iterative deepening to test all depths for i in range(len(answers)): if int(answers[i]) <= 1e7: nodes = self.perft(gamestate, i + 1) if int(answers[i]) != int(nodes) and answers[i] != '0': new_df = pd.DataFrame( [[test_case, i, nodes, answers[i]]], columns=self.columns) self.df = pd.concat([self.df, new_df]) self.df.to_csv('failed_tests.csv', index=False) self.test_failed = True print('Test failed:') print(test_case) print('Nodes searched:', nodes) print('Answer:', answers[i]) print('---------------------------') print(f'{j+1}/{len(test_positions)} tests performed.') end_time = time.time() - start_time print( 'Perft failed, see "failed_tests.csv" for more information about the failed test cases.' ) if self.test_failed else print( f'Perft completed successfully in {round(end_time/60, 2)} minutes.' )
def testing(test_type, player1_type, player2_type): '''test_type:get the rate 0, compare time 1 ''' import gamestate as g import player as p import gameoperator as game import experiment as e state = g.GameState() player1 = p.Player(1, player1_type) player2 = p.Player(2, player2_type) begin = game.GameOperator() m = e.TestMethod() if test_type == 0: # calculate win loss rate m.rate_calculate(state, begin, player1, player2) if test_type == 1: # calculate time gap m.compare_timing(state, begin, player1, player2)
def load_gamestate(db_conn, session): """get the game state from the db """ try: table = db_conn.Table('sessions') response = table.get_item(Key={'uniqID': session}) player_1 = load_player(db_conn, response['Item']['player_id']) game_data = load_game(db_conn) except ClientError: game_state = gamestate.GameState() game_state.uniqID = session game_state.message = "Unknown game state" return game_state else: item = response['Item'] game_state: gamestate.GameState = json.loads(json.dumps(item, cls=GameEncoder)\ , object_hook=object_decoder) game_state.update_from_player(player_1) game_state.update_from_game(game_data) return game_state
async def ticker(sock1, sock2): # A task to receive keyboard and mouse inputs from players. # This will also update the game state, gs. gs = gamestate.GameState() gs_buffer = [] t = create_task(update_from_client(gs, gs_buffer, sock2)) # Send out the game state to all players 60 times per second. try: while True: if gs_buffer: gs_state = gs_buffer.pop(0) print(gs_state.to_json()) await sock1.send_string(gs_state.to_json()) #print('.', end='', flush=True) await asyncio.sleep(1 / SERVER_UPDATE_TICK_HZ) except asyncio.CancelledError: t.cancel() await t
# -*- encoding: utf8 -*- import sys import pygame sys.path.append('./data') import gamestate import hud if __name__ == '__main__': pygame.init() pygame.mixer.pre_init(44100, -16, 2) pygame.mixer.init() screen = pygame.display.set_mode((800, 640)) pygame.display.set_caption("Space Invaders") pygame.mouse.set_visible(False) clock = pygame.time.Clock() game = gamestate.GameState(screen) hud = hud.HUD(game) last = game.level try: while True: clock.tick(30) game.update() hud.update() game.draw(screen) hud.draw(screen) pygame.display.update() if game.level != last: last = game.level hud.nextLevel(screen) except KeyboardInterrupt:
import pygame import collisions import event import gamestate import graphics import config was_closed = False while not was_closed: game = gamestate.GameState() button_pressed = graphics.draw_main_menu(game) if button_pressed == config.play_game_button: game.start_pool() events = event.events() while not (events["closed"] or game.is_game_over or events["quit_to_main_menu"]): events = event.events() collisions.resolve_all_collisions(game.balls, game.holes, game.table_sides) game.redraw_all() if game.all_not_moving(): game.check_pool_rules() game.cue.make_visible(game.current_player) while not ((events["closed"] or events["quit_to_main_menu"]) or game.is_game_over) and game.all_not_moving(): game.redraw_all() events = event.events() if game.cue.is_clicked(events):
def __init__(self, game=None): self.set_game(game) # for autocomplete if False: self._game = gamestate.GameState()
FRAMES_PER_SECOND = 30 SEGMENT_SIZE = 20 APPLE_SIZE = 30 WINDOW_SIZE = 600 PIXELS_PER_FRAME = 10 SNAKE_IMG = pygame.image.load('snake_head.png') APPLE_IMG = pygame.image.load('snake_apple.png') WINDOW_NAME = 'Slither' WINDOW_ICON = pygame.image.load('snake_apple.png') # the font with which to print out stuff to the user FONT_HEADER = pygame.font.SysFont(None, 35) FONT_SUB_HEADER = pygame.font.SysFont(None, 25) # holds the game state (i.e game over or quit or play) game_state = gamestate.GameState(PIXELS_PER_FRAME, WINDOW_SIZE, SEGMENT_SIZE, FRAMES_PER_SECOND, SNAKE_IMG, APPLE_SIZE) # to print something out : print "lala {} lulu {}".format(arg1, arg2) gameDisplay = pygame.display.set_mode((WINDOW_SIZE, WINDOW_SIZE)) # set the label for the window pygame.display.set_caption(WINDOW_NAME) # set the icon for the window pygame.display.set_icon(WINDOW_ICON) # set to clock to control the fps clock = pygame.time.Clock() def message_to_screen(msg, color, font, displace_y): screen_text = font.render(msg, True, color) gameDisplay.blit(screen_text, [
import minimax import gamestate as game best_moves = set([(0, 0), (2, 0), (0, 1)]) rootNode = game.GameState() minimax_move = minimax.minimax_decision(rootNode) print("Best move choices: {}".format(list(best_moves))) print("Your code chose: {}".format(minimax_move)) if minimax_move in best_moves: print("That's one of the best move choices. Looks like your minimax-decision function worked!") else: print("Uh oh...looks like there may be a problem.")