def test_get_label_h_pairs(self): game = Game(3) game.shuffle(333) clean_tiles = [[(1, 0)], [(2, 0)], [(3, 0)], [(4, 0)], [(5, 0)], [(6, 0)], [(7, 0)], [(8, 0)], [(9, 0)]] self.assertNotEqual(game.get_label_h_pairs(), clean_tiles) game.tiles = game.generate_tiles(3) self.assertEqual(game.get_label_h_pairs(), clean_tiles)
def test_possible_to_emerge(): game = Game() game.add_lives(Life(0, 0)) game.add_lives(Life(1, 0)) game.add_lives(Life(2, 1)) assert len(game.get_possible_to_emerge()) == 17
def test_read_message_decreases_messages_count(self): self.game = Game(self.questions_storage) self.game.next_question() start_messages_count = self.game.get_messages_count() self.game.read_message() self.assertLess(self.game.get_messages_count(), start_messages_count)
def test_request_help_adds_messages(self): self.game = Game(self.questions_storage) self.game.next_question() start_messages_count = self.game.get_messages_count() self.game.request_help() self.assertGreater(self.game.get_messages_count(), start_messages_count)
def evaluate(self, member): scr = pygame.display.set_mode((800, 600)) ac = choice(self.action) g = Game(scr, member, None, ac) a = g.start() if g.thing.life < 0: g.thing.life = 0 member.fitness = (g.thing.full - g.thing.life) / g.wave return member.fitness
def main(stdscr): with open("result.out") as f: game = Game(*json.loads(f.read())) if len(sys.argv) > 1 and sys.argv[1] == "-t": turn = int(sys.argv[2])-1 else: turn = 0 play_game(stdscr, game, turn=turn)
def run(): args = docopt(__doc__) debug.log(args) if args['-']: story = sys.stdin.read() else: story = open(args['STORY-FILE'], 'r').read() characters = open(args['CHARACTERS-FILE'], 'r').read() stats = open(args['STATS-FILE'], 'r').read() game = Game(story, characters, stats).start()
def test_slide_tile(self): game = Game(3) game.tiles = game.generate_tiles(3) print(game) self.assertFalse(game.slide_tile(1)) self.assertFalse(game.slide_tile(2)) self.assertFalse(game.slide_tile(4)) self.assertTrue(game.slide_tile(8)) self.assertTrue(game.slide_tile(7)) self.assertTrue(game.slide_tile(7)) self.assertTrue(game.slide_tile(8))
def client_on_message(self, message): """ When the client receive a message :param message: The message receive :return: None """ messages = Server.Server.decode_message(message) for message in messages: message = message.split('_') if message[0] == MESSAGE_NEED_STATE: self.client_send_player_name() self.client_send_token() elif message[0] == MESSAGE_SEND_NAME_SELECTED: self.players_entry_string_variable[0].set(message[1]) self.name_string_var_trace_write(False) elif message[0] == MESSAGE_SEND_TOKEN_SELECTED: try: # noinspection PyTypeChecker self.players_tokens[ self.opponent_id] = TokenStyle.TokenStyle( int(message[1])) self.players_tokens_images[self.opponent_id] = \ self.ui.image_getter.save_token_photos[self.opponent][self.players_tokens[self.opponent_id]] self.players_tokens_labels[self.opponent_id].config( image=self.players_tokens_images[self.opponent_id]) except ValueError: pass elif message[0] == MESSAGE_PLAYER_1_WANT_START: self.player_1_want_to_start() elif message[0] == MESSAGE_PLAY: game = Game.Game( first_player=(TokenState.Player_2, TokenState.Player_1)[message[1] == "1"]) self.export_last_game_settings() self.ui.change_panel( ServerGamePanel.ServerGamePanel, player_1=Player.Player( TokenState.Player_1, self.players_tokens[0], self.players_entry_string_variable[0].get()), player_2=Player.Player( TokenState.Player_2, self.players_tokens[1], self.players_entry_string_variable[1].get()), is_server=self.create_game, game=game)
def test_available_moves(): g = Game(Strategy(), Strategy()) s = g.state moves = available_moves(s) for m in moves: new_state = deepcopy(g.state) new_state.apply(m) new_state.show() return moves
def test_check_win_with_uncorrect_positions_0(self): test_mas = ( ("O", "O", 3, 4, 5, 6, 7, 8, "O"), (1, "O", 3, "O", 5, "O", 7, 8, 9), ("O", "O", 3, "O", 5, 6, 7, 8, 9), (1, 2, 3, 4, 5, "O", 7, 8, "O"), (1, 2, 3, "O", 5, 6, 7, 8, 9), (1, 2, "O", 4, 5, 6, "O", 8, "O"), (1, "O", 3, "O", 5, 6, "O", 8, 9), ("O", 2, "O", 4, "O", 6, 7, "O", 9), ) for it in test_mas: chw = Game(it).check_win() self.assertFalse(chw)
def test_check_win_with_uncorrect_positions_X(self): test_mas = ( (1, "X", 3, 4, 5, "X", 7, "X", 9), ("X", 2, 3, "X", "X", 6, 7, 8, 9), (1, "X", 3, "X", 5, "X", 7, 8, 9), ("X", "X", 3, 4, 5, 6, 7, 8, "X"), (1, 2, "X", 4, "X", 6, 7, "X", "X"), (1, 2, "X", "X", "X", 8, 7, 8, 9), (1, 2, "X", "X", 5, "X", "X", 8, 9), (1, "X", 3, 4, 5, 6, 7, "X", 9), ) for gb in test_mas: chw = Game(gb).check_win() self.assertFalse(chw)
def do_start(self, _): try: self.game = Game( player_1=self.player_1, player_2=self.player_2, ) except AttributeError as exc: if 'player_1' in str(exc): self.logger.error("Game cannot start: You need to create the Player 1: p1 <name> .") elif 'player_2' in str(exc): self.logger.error("Game cannot start: You need to create the Player 2: p2 <name> .") except Exception as exc: self.logger.error("Error: {}".format(str(exc)))
def run(dimensions, turns, terminal=1): """ Run a game with the chosen config - accessible through terminal """ # Run the game game = Game(dimensions, turns, terminal) # debug flag = 1 strategy1 = Castle(game) strategy2 = Ship(game, "~") # Opposing strategies game.add_strategy(strategy1).add_strategy(strategy2) # Choose the board print("Welcome to Game of Life Extended (codename golex) v.", game.VERSION) print( "This game takes GoL to the next level by bringing 2 players (strategies) together and making them fight each other.\n" ) # Start line print("Initial configuration with the chosen strategies (", strategy1.SIGN, ",", strategy2.SIGN, "):") # Set up the initial configuration game.build() # Make user see what's happening if terminal: input("Press Enter to continue") print("\nProceeding with the simulation...") # Iterate through the GoL algorithm game.run() winner = game.get_winner() print("Resulting board:") game.print_state() print() # Show the winner print("The winning strategy is '", winner, "'") # End line print() return winner
def game_loop(self): while self.running: for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False sys.exit(0) elif event.type == pygame.KEYDOWN: if event.unicode.isalpha(): self.entered_name += event.unicode elif event.key == pygame.K_BACKSPACE: self.entered_name = self.entered_name[:-1] elif event.key == pygame.K_RETURN: self.running = False Game(self.entered_name) self.display() pygame.display.update() CLOCK.tick(FPS)
def play_game(screen, game, turn=0): maxturn = len(game.record)-1 turn = min(max(turn, 0), maxturn) while True: table, score = game.record[turn] g = Game(table=table, score=score, size=game.size, turn=turn+1) render_info(g, screen) render_help(screen) action, arg = prompt_key(g, screen) if action == "next": turn += 1 elif action == "prev": turn -= 1 elif action == "skip": turn = int(arg)-1 elif action == "add": turn += int(arg) turn = min(max(turn, 0), maxturn)
def __init__(self, master, ui, is_server=False, player_1=Player.Player(TokenState.TokenState.Player_1, TokenStyle.TokenStyle.Blue), player_2=Player.Player(TokenState.TokenState.Player_2, TokenStyle.TokenStyle.Green), game=Game.Game()): """ Constructor """ super().__init__(master, ui, player_1, player_2, game, disable_end_button=not is_server) self.is_server = is_server if self.is_server: self.button_main_menu.configure( text=self.ui.translation.get_translation("quit")) # Set server functions self.ui.server.on_message_function = self.server_on_message self.ui.server.on_client_connect_function = self.server_on_client_connect_function self.ui.server.on_client_disconnect_function = self.server_on_client_disconnect_function else: tkinter.tix.Label(self.win_text_frame, text=self.ui.translation.get_translation( "server_game_wait_host")).grid(row=1, column=0) # Set client functions self.ui.client.on_message_function = self.client_on_message self.ui.client.on_connection_function = self.client_on_connection_function self.ui.client.on_disconnection_function = self.client_on_disconnection_function
def train(): record = 0 agent = Agent() game = Game(True) counter: int = 0 game.set_game_time(1) while True: state_old = game.get_state() move = agent.get_action(state_old) if move == [1, 0, 0]: final_move = TriDirections.STRAIGHT elif move == [0, 1, 0]: final_move = TriDirections.RIGHT else: final_move = TriDirections.LEFT game.set_direction(final_move) reward, done, score = game.game_logic() if reward == 0: counter += 1 else: counter = 0 state_new = game.get_state() if counter > 100: done = True reward = -10 if counter > 100: game.set_game_time(5) agent.train_short_memory(state_old, move, reward, state_new, done) agent.remember(state_old, move, reward, state_new, done) if done: counter = 0 game.reset() agent.n_games += 1 agent.train_long_memory() if score > record: record = score agent.model.save() print('Game', agent.n_games, 'Score', score, 'Record:', record)
def test_check_win_with_wit_garbage(self): test_mas = ( ("a", 2, "ty", "X", 5, 6, 7, "O", 9), (1, 2, "X", "X", "X", 6, 7, 8, 9), (1, "O", 3, "r", "67", "O", 7, 8, 9), ("O", "@", "X", "l", 5, "D", 7, "X", 9), ("*", 2, "4", "]", "|", 6, 7, 8, "X"), (1, "X", 3, 4, "O", 6, 7, "O", 9), (1, 2, 3, "X", "X", "O", 7, 0x45, 9), ( 1, "O", 3, "F", 5, "f", 7, 8, ), ) for it in test_mas: chw = Game(it).check_win() self.assertFalse(chw)
def button_play_command(self): """ When the button play (or ready is press) :return: None """ if self.create_game: if self.player_2_is_connected: if self.player_2_is_ready: self.export_last_game_settings() self.ui.change_panel( ServerGamePanel.ServerGamePanel, player_1=Player.Player( TokenState.Player_1, self.players_tokens[0], self.players_entry_string_variable[0].get()), player_2=Player.Player( TokenState.Player_2, self.players_tokens[1], self.players_entry_string_variable[1].get()), is_server=self.create_game, game=Game.Game( first_player=random.choice((TokenState.Player_1, TokenState.Player_2)))) self.ui.server.send_message_to_all( Server.Server.encode_message('_'.join( (MESSAGE_PLAY, str(self.ui.current_panel.game.current_turn.value) )))) else: self.player_1_want_to_start() else: self.set_player_2_ready(not self.player_2_is_ready) self.ui.client.send_message( Server.Server.encode_message('_'.join( (MESSAGE_SEND_READY, str(self.player_2_is_ready)))))
from main import Game from utility import NonBlockingInput, keyPressed, clearScreen as c from config import * from time import sleep, monotonic from objects import MandoBullet, BossBullet import sys g = Game(100) keys = NonBlockingInput() keys.NBISetupTerminal() counter = 0 bulletFlag = False coinLocations = [] lazerLocations = [] for location in g.screen.locationsUsed: if counter < COINB_COUNT: coinLocations.append(g.screen.map[location[0] - COIN_SIZE[0] : location[0], location[1] : location[1] + COIN_SIZE[1]]) elif counter < COINB_COUNT + HLAZER_COUNT: lazerLocations.append(g.screen.map[location[0], location[1] : location[1] + HLAZER_SIZE[1]]) elif counter < COINB_COUNT + HLAZER_COUNT + VLAZER_COUNT: lazerLocations.append(g.screen.map[location[0] - VLAZER_SIZE[0] : location[0], location[1]])
from main import Game, select_action import sys states = {} with open(sys.argv[1], "r") as f: line = f.readline() while line: data = line[:-1].split("#") states[eval(data[0])] = eval(data[1]) line = f.readline() game = Game() while 1: state = game.get_state() if not state in states.keys(): states[state] = {} for i in game.get_actions(): states[state][i] = 0.0 action = max(states[state], key=states[state].get) # print(states[state]) game.do_action(action, 1) next_state = game.get_state() if game.is_end() != -1: game.print() print(f"game end {game.is_end()}") break actions = game.get_actions()
def main(): Game().run()
def main(): print("Starting the game") game = Game() game.play() print("Game Over")
def training_loop(training_model, opponent_model, verbose=False): winner = None # for tensor board logging log_dir = ("logs/fit/" + training_model._name + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) tensorboard = ModifiedTensorBoard(log_dir=log_dir) # now execute the q learning y = 0.9 eps = 0.5 interval_size = 500 num_episodes = interval_size * 1 decay_factor = (1000 * eps)**( -1 / num_episodes ) # ensures that eps = 0.001 after `num_episodes` episodes r_avg_list = [] sse_avg_list = [] wins = [] n_moves_list = [] moves_played = [0] * BOARD_SIZE for i in tqdm(range(num_episodes), desc="Training"): as_player = random.choice([0, 1]) eps *= decay_factor g = Game(verbose=verbose) if as_player == 1: # Training as player 1 so opponent makes first move winner, board = g.move(opponent_model.move(g._board, 0)) else: board = g._board done = False r_sum = 0 sse_sum = 0 move_num = 0 while not done: random_move = False move_num += 1 preds = training_model.predict(board, as_player) # To encourage early exploration if np.random.random() < eps: move = np.random.randint(0, BOARD_SIZE - 1) random_move = True else: move = training_model.move(board, as_player) moves_played.append(move) winner, new_board = g.move(move) if winner is None: opponent_move = opponent_model.move(new_board, 1 - as_player) winner, new_board = g.move(opponent_move) # Calculate reward amount if winner == as_player: done = True wins.append(1) r = 1000 - move_num**2 elif winner == 1 - as_player: done = True wins.append(0) r = -(1000 - move_num**2) elif winner == -1: done = True wins.append(None) r = 1000 else: r = move_num if winner is None: target = r + y * np.max( training_model.predict(new_board, as_player)) else: target = r target_vec = deepcopy(preds[0]) target_vec[move] = target training_model.fit_one( as_player, board, np.array([target_vec]), epochs=1, verbose=0, callbacks=[tensorboard], ) new_preds = training_model.predict(board, as_player) sse = sum([(x - y)**2 for x, y in zip(preds[0], target_vec)]) new_sse = sum([(x - y)**2 for x, y in zip(new_preds[0], target_vec)]) sse_sum += sse if verbose: print(f""" {training_model._name} training as player: {as_player}, move: {move_num}, eps: {round(eps, 2)}, old preds: {[round(p, 2) for p in preds[0]]}, rand move: {random_move}, tgt preds: {[round(p, 2) for p in target_vec]}, reward: {r}, new preds: {[round(p, 2) for p in new_preds[0]]}, average last 20 games: {round(sum(r_avg_list[-20:])/20, 2)} sse: {round(sse, 4)} >> {round(new_sse, 4)} """) board = new_board r_sum += r if verbose and ((i % interval_size == 0 and i > 0) or (i == num_episodes - 1)): run_game(training_model, opponent_model, verbose=True) # Collect game level metrics r_avg_list.append(round(r_sum, 2)) n_moves_list.append(move_num) tensorboard.update_stats(reward_sum=r_sum, wins=wins[-1], n_moves_avg=n_moves_list[-1]) tensorboard.update_dist(moves_played=moves_played)
assert(len(W) == 10) W -= (1,2,0,0,0,0) assert(len(W) == 7) assert(W[2] == 3) W += (4,4,1,0,0,0) assert(W.overmax()) W -= (4,4,4,4,0,0) assert(W.negative() is False) if __name__ == "__main__": _BLACK = 4 C = Card(_BLACK,0,1,1,1,1,0) assert(C.cost() == (1,1,1,1,0)) assert(C.color() == 'B') assert(C.points() == 0) C.set_key(0,3) assert(C.key() == (0, 3)) if __name__ == "__main__": G = Game() P1 = G.active_player() G.collect((1,1,1,0,0,0)) P2 = G.active_player() assert(P2 is not P1) G.collect((0,1,1,1,0,0)) G.board() if __name__ == "__main__": N = Noble(3, 3, 3, 3, 0, 0) assert(N.cost() == (3, 3, 3, 0, 0))
#!/usr/bin/python3 # -*- coding: utf-8 -*- from main import Game import json, queue NBTHREADS = 4 MAXSIZE = -1 SCORETARGET = 600000 boundary = queue.LifoQueue(MAXSIZE) boundary.put(Game()) maxscore = -1 nbgames = 1 bgame = None while not boundary.empty(): game = boundary.get() game.init_turn() moves = game.avail_moves(game.table) if not moves: if game.score > maxscore: print("new maxscore (%s branch): %s" % (nbgames, maxscore)) maxscore = game.score bgame = game if maxscore > SCORETARGET: break nbgames += len(moves) - 1 for move in moves: game2 = game.copy() game2.play(move)
def setUp(self): self.game = Game()
def __init__(self, master, ui, player_1=Player.Player(TokenState.TokenState.Player_1, TokenStyle.TokenStyle.Blue), player_2=Player.Player(TokenState.TokenState.Player_2, TokenStyle.TokenStyle.Green), game=Game.Game(), disable_end_button=False, delay=Preferences.DEFAULT_DELAY): """ Constructor :param player_1: the player 1 :param player_2: the player 2 :param game: a link to the game :param disable_end_button: if need to disable end buttons (for the client) :param delay: the delay between click in ms :param master: see Panel class :param ui: see Panel class """ super().__init__(master, ui) self.turn_text_format = self.ui.translation.get_translation("game_panel_turn_format") self.win_text_format = self.ui.translation.get_translation("game_panel_win_format") self.grid_canvas = tkinter.tix.Canvas(self) self.grid_canvas.pack(expand=True, fill=tkinter.tix.BOTH) self.after(500, lambda: self.grid_canvas.bind("<Button>", self.grid_canvas_on_click)) self.game = game self.players = { TokenState.TokenState.Player_1: player_1, TokenState.TokenState.Player_2: player_2 } self.token_square_size = 0 self.height_center = 0 self.width_center = 0 self.button_main_menu = tkinter.tix.Button( self, # text=self.ui.translation.get_translation("game_panel_main_menu_button"), command=self.button_main_menu_command, image=self.ui.image_getter.door_exit_icon) self.button_main_menu.place(x=0, y=0) self.grid_image_create = [] self.turn_text_id = -1 self.turn_image_id = - 1 self.win_line_id = -1 self.win_icon_id = -1 self.win_icon_background_id = -1 self.win_text_frame = tkinter.tix.Frame(self, relief=tkinter.tix.RAISED, borderwidth=2) self.win_text_label = tkinter.tix.Label(self.win_text_frame) self.win_text_label.grid(row=0, column=0) if not disable_end_button: self.end_buttons_frame = tkinter.tix.Frame(self.win_text_frame) self.end_buttons_frame.columnconfigure(0, weight=1) self.end_buttons_frame.columnconfigure(1, weight=1) self.end_buttons_frame.grid(row=1, column=0) max_width = max(len(self.ui.translation.get_translation("back")), len(self.ui.translation.get_translation("restart")), len(self.ui.translation.get_translation("main_menu"))) self.button_main_menu_end = tkinter.tix.Button( self.end_buttons_frame, text=self.ui.translation.get_translation("main_menu"), command=self.button_main_menu_command, width=max_width ) self.button_main_menu_end.grid(row=0, column=0, sticky=tkinter.tix.NSEW, padx=5) self.back_button = tkinter.tix.Button( self.end_buttons_frame, text=self.ui.translation.get_translation("back"), command=self.button_back_command, width=max_width ) self.back_button.grid(row=0, column=1, sticky=tkinter.tix.NSEW, padx=5) self.restart_button = tkinter.tix.Button( self.end_buttons_frame, text=self.ui.translation.get_translation("restart"), command=self.button_restart_command, width=max_width ) self.restart_button.grid(row=0, column=2, sticky=tkinter.tix.NSEW, padx=5) for x in range(0, self.game.grid_width): self.grid_image_create.append([]) for y in range(0, self.game.grid_height): self.grid_image_create[x].append(-1) self.token_animation_list = [] self.delay = delay / 1000. # convert in second self.last_click_time = time.time() self.ai_turn_start_time = time.time() self.ai_progress_bar = tkinter.ttk.Progressbar(self.grid_canvas, orient=tkinter.tix.HORIZONTAL, mode='determinate') self.ai_progress_bar_show = False
def setUp(self): self.questions_storage = QuestionStorage('') self.game = Game(self.questions_storage)