def game_gen_worker(*args): global WORKER_NN if not WORKER_NN: if WORKER_MODEL_ID > 0: WORKER_NN = load_net(WORKER_DNAME + fname_from_id(WORKER_MODEL_ID)) else: WORKER_NN = Net() WORKER_NN.eval() nn = WORKER_NN p1 = NNSimplePlayer('p1', nn=nn, train=True) p2 = NNSimplePlayer('p2', nn=nn, train=True) g = Game(players=[p1, p2], verbose=False) winner = g.run() extra = '' for _ in range(5): try: fname = '{:05}_{}_{}__{}.json'.format(WORKER_MODEL_ID, int(time.time()), extra, len(p1._states) + len(p2._states)) with open(f'{WORKER_DNAME}{fname}', 'x') as f: json.dump({'p1_s': p1._states, 'p2_s': p2._states, 'w': 0 if p1 == winner else 1}, f) log.info('wrote %s', fname) break except FileExistsError: log.info('file exists') extra = str(random.randint(1,1000))
def execute(participants, game_num, small_blind, num_of_members): print('\n №{}\n'.format(game_num)) if game_num == 1: fill_banks_of_members(participants, num_of_members, bank=limit) participants[0].limit = participants[0].bank participants[0].blef_rises = 0 for p in participants: p.in_game = True kol = Game(game_num, small_blind) kol.handout(num_of_members - 1) kol.make_round(participants) kol.make_round(participants) kol.make_round(participants) kol.make_round(participants) kol.make_round(participants) for p in participants: add_money(p, limit) check_banks(participants) if len(participants) == 1: print('Игра окончена: победитель {}, выигрыш ${}'.format( participants[0].nick, participants[0].bank)) exit() return kol.game_num
def execute(): ai = Player() ai.bank = 3000 ai.limit = 3000 op = Opponent() op.bank = 3000 participants = [ai, op] game = Game() game.handout(1) pre_chance, _ = game.make_round(participants) floop_chance, _ = game.make_round(participants) turn_chance, _ = game.make_round(participants) game.make_round(participants) river_chance, gess = game.make_round(participants) return gess, river_chance, turn_chance, floop_chance, pre_chance
def on_create(self, game_mode, word_length): word = self.dictionary.filter_by_length(word_length).choice() query = self.dictionary.filter_from_string(word).filter_by_length( 3, word_length) if game_mode == GameMode.TIMED_RETRIES or game_mode == GameMode.RETRIES: self.current_game = Game(word, query, mistakes=3, mode=game_mode) else: self.current_game = Game(word, query, mode=game_mode)
def test_move_1(self): game = Game('Pc7,Ke1,ke8') self.assertEqual(str(game.board.getFigure(WHITE, PAWN)), 'Pc7') with self.assertRaises(errors.NotFoundError): game.board.getFigure(WHITE, QUEEN) game.move(WHITE, (3, 7), (3, 8)) self.assertEqual(str(game.board), 'Ke1,ke8,Qc8') self.assertEqual(str(game.board.getFigure(WHITE, QUEEN)), 'Qc8') with self.assertRaises(errors.NotFoundError): game.board.getFigure(WHITE, PAWN)
def worker(p1_p2): p1, p2 = p1_p2 p1 = PLAYERS_MAP[p1] p2 = PLAYERS_MAP[p2] players = [p1(), p2()] game = Game(players, verbose=False) winner = game.run() loser = players[0] if winner == players[1] else players[1] return winner.name, loser.name
def test_move_2(self): game = Game('pc2,Ke1,ke8', BLACK) self.assertEqual(str(game.board.getFigure(BLACK, PAWN)), 'pc2') with self.assertRaises(errors.NotFoundError): game.board.getFigure(BLACK, QUEEN) game.move(BLACK, (3, 2), (3, 1)) self.assertEqual(str(game.board), 'Ke1,ke8,qc1') self.assertEqual(str(game.board.getFigure(BLACK, QUEEN)), 'qc1') with self.assertRaises(errors.NotFoundError): game.board.getFigure(BLACK, PAWN)
def process(self, *args, **kwargs): generator = self.world.get_components(c.Event, c.Velocity) for ent, (event, vel) in generator: event.action = self.handle_input() if event.action.get("exit"): Game.quit_game() move = event.action.get("move") if move: dx, dy = move vel.dx = dx vel.dy = dy
class Controller: def __init__(self, interface, dictionary_file): """ Initializes a new Controller. Args: interface (Interface): A client/view of the SWUG engine. dictionary_file (str): Path to the dictionary file to load. """ self.dictionary = Dictionary(dictionary_file) self.current_game = None self.interface = interface # Enable two-way communication between C and V # On the view side, self.controller.controller_events can # then be used to register event handlers self.interface.controller = self self.controller_events = ControllerEvents() # register view event handlerrs self.interface.view_events.create += self.on_create self.interface.view_events.answer += self.on_answer self.interface.view_events.end += self.on_end def on_create(self, game_mode, word_length): word = self.dictionary.filter_by_length(word_length).choice() query = self.dictionary.filter_from_string(word).filter_by_length( 3, word_length) if game_mode == GameMode.TIMED_RETRIES or game_mode == GameMode.RETRIES: self.current_game = Game(word, query, mistakes=3, mode=game_mode) else: self.current_game = Game(word, query, mode=game_mode) def on_answer(self, word): if self.current_game.on_board(word): self.controller_events.answer_duplicate(word) else: if self.current_game.answer(word): self.controller_events.answer_correct(word) else: self.controller_events.answer_wrong(word) if self.current_game.is_game_over: self.controller_events.end() def on_end(self): if not self.current_game.is_game_over: self.current_game.end_game() def run_interface(self): self.interface.run()
def simple_match(): win = {'p1': 0, 'p2': 0} for i in range(500): p1 = RandomPlayer('p1') p2 = RandomPlayer('p2', w=WEIGHT_MAP29) players = [p1, p2] if i % 2: players = players[::-1] g = Game(players, seed=None) winner = g.run() win[winner.name] += 1 print(win) print(win)
def test_self_discard(self): p1 = TestPlayer('p1', hand=[EXPLORER]) p2 = TestPlayer('p2') g = Game([p1, p2]) with patch.object(TestPlayer, 'choose_action') as choose_action: choose_action.return_value = UserActionPlayCard(EXPLORER) g.do_one_user_action(p1, p2) choose_action.assert_called_once() self.assertEqual(2, p1.trade) self.assertEqual(1, len(p1.remaining_actions)) self.assertSequenceEqual([(EXPLORER, EXPLORER.actions[1])], p1.remaining_actions) action = UserActionCardAction(EXPLORER, EXPLORER.actions[1]) actions = g.available_actions(p1, p2) self.assertIn(action, actions) with patch.object(TestPlayer, 'choose_action') as choose_action: choose_action.return_value = action g.do_one_user_action(p1, p2) choose_action.assert_called_once() self.assertEqual(2, p1.trade) self.assertEqual(2, p1.damage) self.assertEqual(0, len(p1.remaining_actions))
def run_match(x: np.ndarray): w = {k: v for k, v in zip(ACTIONS, x)} win = {'p1': 0, 'p2': 0} for i in range(100): p1 = RandomPlayer('p1', w=WEIGHT_MAP) p2 = RandomPlayer('p2', w=w) players = [p1, p2] if i % 2: players = players[::-1] g = Game(players, seed=None, verbose=False) try: winner = g.run() win[winner.name] += 1 except: log.exception('error running game') pct = win['p1'] / (win['p1'] + win['p2']) #log.info('match win ratio: %s', pct) return pct
def get(self, action, id=None): if action == "create": id = len(self.games) n_detectives = 4 game = Game(board_definition) mrX = MrX(game) detectives = [Detective(game) for i in range(n_detectives)] game.set_players(mrX, detectives) self.games.append(game) self.write(json.dumps({ 'id' : id, 'board' : board_definition }))
def equivalent_states(game: Game): ret_list = [] for rotation in GAME_ROTATIONS: temp_list = [] for index in rotation: temp_list.append(game.tiles[index]) ret_list.append(Game(temp_list)) return ret_list
class Perft: def __init__(self): self.game = Game() self.game.new_game() def perft(self, board, curr_player, depth): """Perft function that recursively checks nodes. Intended to be compared to predetermined values. ply 2 search time: .567 ply 3 search time: 12.1 ply 4 search time: 281.54""" nodes = 0 if curr_player.color is Color.W: num_moves = board.get_all_legal_moves(self.game.white) else: num_moves = board.get_all_legal_moves(self.game.black) if depth == 1: return len(num_moves) for move in num_moves: new_board = deepcopy(board) new_piece = new_board.get_piece_at_position(move[0].position) new_board.make_move(new_piece, move[1]) if curr_player == self.game.white: nodes += self.perft(new_board, self.game.black, depth-1) else: nodes += self.perft(new_board, self.game.white, depth-1) return nodes def run_perft(self, depth): """Perft wrapped in a timer.""" start = time() done = self.perft(self.game.board, self.game.current_turn, depth) end = time() print("Elapsed time for depth " + str(depth) + ": ") print(str(end-start)) return done
def test_full_game(self): moves = [ 'e2-e4', 'e7-e5', 'g1-f3', 'b8-c6', 'f1-c4', 'c6-d4', 'f3-e5', 'd8-g5', 'e5-f7', 'g5-g2', 'h1-f1', 'g2-e4', 'c4-e2', 'd4-f3', 'e2-f3', 'e4-e1' ] game = Game() with self.assertRaises(errors.BlackWon): for move in moves: positions = map(coors2pos, move.split('-')) game.move(game.current_player, *positions) expect = [ 'Pa2', 'Pb2', 'Pc2', 'Pd2', 'Pf2', 'Ph2', 'Ra1', 'Rf1', 'Nb1', 'Nf7', 'Bc1', 'Bf3', 'Qd1', 'pa7', 'pb7', 'pc7', 'pd7', 'pg7', 'ph7', 'ra8', 'rh8', 'ng8', 'bc8', 'bf8', 'qe1', 'ke8' ] self.assertEqual(str(game.board), ','.join(expect)) expect = [(PAWN, BLACK), (PAWN, BLACK), (PAWN, WHITE), (PAWN, WHITE), (KNIGHT, BLACK), (KING, WHITE)] self.assertEqual(game.board.cuts, expect)
class Perft: def __init__(self): self.game = Game() self.game.new_game() def perft(self, board, curr_player, depth): """Perft function that recursively checks nodes. Intended to be compared to predetermined values. ply 2 search time: .567 ply 3 search time: 12.1 ply 4 search time: 281.54""" nodes = 0 if curr_player.color is Color.W: num_moves = board.get_all_legal_moves(self.game.white) else: num_moves = board.get_all_legal_moves(self.game.black) if depth == 1: return len(num_moves) for move in num_moves: new_board = deepcopy(board) new_piece = new_board.get_piece_at_position(move[0].position) new_board.make_move(new_piece, move[1]) if curr_player == self.game.white: nodes += self.perft(new_board, self.game.black, depth - 1) else: nodes += self.perft(new_board, self.game.white, depth - 1) return nodes def run_perft(self, depth): """Perft wrapped in a timer.""" start = time() done = self.perft(self.game.board, self.game.current_turn, depth) end = time() print("Elapsed time for depth " + str(depth) + ": ") print(str(end - start)) return done
def game(): # By seed(0), random sequence for dice becomes [8, 8, 2, 6, 10, 9, 8, 6, 9, 7, 11, 5, 10, 4, 6, 4, 3, 11, 6, 10] global event_queue seed(0) event_queue = deque() ee = EventEmitterSingleton.instance() ee.remove_all_listeners() for e in [ 'transaction', 'newplayer', 'newround', 'offer', 'invoice', 'match', 'leaving' ]: ee.on(e, queue_event(e)) return Game()
def post(self): self.write_json('done') return if action == "create": id = len(self.games) n_detectives = 4 game = Game(board_definition) detectives = [Detective(game) for i in range(n_detectives)] game.set_players(detectives=detectives) self.games.append(game) self.write(json.dumps({ 'id' : id, 'board' : board_definition })) elif action == "list": self.write(json.dumps(range(len(self.games))))
async def wshandle(request): ws = web.WebSocketResponse() await ws.prepare(request) game = None log = logging.getLogger(request.remote) async for msg in ws: log.info('got: %s', msg) if msg.type == web.WSMsgType.text: event, data = msg.json() if event == 'start_game': if game: p1._q.put(STOP_GAME) # should really not do this... t.join() from players.monte_carlo import MCSimplePlayer p1 = WebPlayer(ws, 'p1') # p2 = InteractivePlayer('p2') #p2 = MCSimplePlayer('p2') p2 = SimplePlayer('p2') p2 = NNSimplePlayer('p2', '8 7') game = Game([p1, p2], seed=666) p1.game = game p1.proxy_player(p2) t = Thread(target=game.run) await ws.send_json(['status', 'game started']) t.start() elif event in ('choose_action', 'choose_piles'): # TODO: check game is started... p1._q.put([event, data]) else: log.warning('unknown event: %s; data=%s', event, data) #elif msg.type == web.WSMsgType.binary: # await ws.send_bytes(msg.data) elif msg.type == web.WSMsgType.close: break else: log.warning('unknown message type:', msg) return ws
def get_fitness(self): if self.fitness is not None: return self.fitness else: self.win_o = 0 self.draw_o = 0 self.loss_o = 0 empty_game = deepcopy(Game()) anal_queue = deque() for empty_tile in (i for i in range(9) if not empty_game.tiles[i]): empty_game_clone = deepcopy(empty_game) empty_game_clone.set_tile(empty_tile) empty_game_clone.set_tile(self.move(empty_game_clone)) anal_queue.append(empty_game_clone) while len(anal_queue): to_analyze = anal_queue.popleft() if to_analyze.winner: if to_analyze.winner == 2: self.win_o += 1 elif to_analyze.winner == 1: self.loss_o += 1 else: self.draw_o += 1 else: for empty_tile in (i for i in range(9) if not to_analyze.tiles[i]): to_analyze_clone = deepcopy(to_analyze) to_analyze_clone.set_tile(empty_tile) if not to_analyze_clone.winner: to_analyze_clone.set_tile( self.move(to_analyze_clone)) anal_queue.append(to_analyze_clone) self.fitness = (self.loss_o) / (self.win_o + self.draw_o + self.loss_o) return self.fitness
class Controller: def __init__(self, interface): """ Initializes a new Controller. """ self.current_game = None self.interface = interface # Enable two-way comms between interface and view self.interface.controller = self self.controller_events = ControllerEvents() # register view event handlerrs self.interface.view_events.create += self.on_create self.interface.view_events.move += self.on_move self.interface.view_events.keep_playing += self.on_keep_playing self.interface.view_events.end += self.on_end def game_state(self): if self.current_game is None: return {} return self.current_game.game_state() def on_create(self, *args, **kwargs): self.current_game = Game(*args, **kwargs) def on_move(self, direction): self.current_game.move_board(direction) if self.current_game.is_lost(): self.controller_events.lost() if self.current_game.is_won(): self.controller_events.won() def on_keep_playing(self): self.current_game.keep_playing() def on_end(self): self.current_game = None def run_interface(self): self.interface.run()
def test_card_optional_ally_action(self): p1 = TestPlayer('p1') p2 = TestPlayer('p2') g = Game([p1, p2]) p1.trade = 100 p1.bases.append(BlobWheel) p1.hand.append(BlobCarrier) action = UserActionCardAction(BlobCarrier, ActionFreeShipCard()) actions = g.available_actions(p1, p2) self.assertNotIn(action, actions) with patch.object(TestPlayer, 'choose_action') as choose_action: choose_action.return_value = UserActionPlayCard(BlobCarrier) g.do_one_user_action(p1, p2) choose_action.assert_called_once() self.assertEqual(1, len(p1.in_play)) actions = g.available_actions(p1, p2) self.assertIn(action, actions)
def test_attack_outpost(self): p1 = TestPlayer('p1') p2 = TestPlayer('p2') g = Game([p1, p2]) p1.damage = 10 p1.trade = 100 p2.outposts.append(Junkyard) action = UserActionAttackOutpost(Junkyard) actions = g.available_actions(p1, p2) self.assertIn(action, actions) with patch.object(TestPlayer, 'choose_action') as choose_action: choose_action.return_value = action g.do_one_user_action(p1, p2) choose_action.assert_called_once() self.assertEqual(0, len(p2.outposts)) self.assertEqual(10 - Junkyard.defence, p1.damage) actions = g.available_actions(p1, p2) self.assertNotIn(action, actions)
from engine import Game, Player from ansi import cursor, screen import tui import minmaxwrapper depth = int(input("Minmax depth: ")) weights = [0, 0, 0, 0] for i in range(4): weights[i] = float(input("Weight #{}: ".format(i))) game = Game() tui.install(game) tui.installPlayer(game, Player.P1) minmaxwrapper.install(game, Player.P2, depth, weights) game.reset()
def __init__(self): Game.__init__(self,'intro',fullscr=False) self.estados = {'intro' : Intro(self), 'gameplay' : GamePlay(self)} self.fundo = data_load("fundo2.png") self.num_estrelas = 40 self.scripts = data_load("atacc.yml")
def add_to_game_base(game: Game): logging.basicConfig(filename="it.log", filemode="w", level=logging.DEBUG) base_case = find_base_case(game) with open("python_code/game-base.txt", "a") as file: if not in_game_base(base_case): file.write(f"{repr(base_case)}\n") if __name__ == "__main__": open("python_code/game-base.txt", "w") open("it.log", "w") inspect_queue = deque([Game()]) while len(inspect_queue): game = inspect_queue.popleft() empty_tiles = tuple(i for i in range(9) if not game.tiles[i]) # print(game) add_to_game_base(game) num_unique_cases = int( subprocess.check_output("/usr/bin/wc -l python_code/game-base.txt", shell=True).split()[0]) for tile in empty_tiles: game_copy = deepcopy(game) if not game.winner:
"""Genesis: The Game.""" from config import config from engine import Game, Window, Font from objects.score import Score import stages.gameover, stages.intro, stages.stage1 import cli_parser from random import randint import pygame pygame.init() if __name__ == "__main__": game = Game(fps=config.fps) options = cli_parser.proccess_CLI() mx = sorted(pygame.display.list_modes())[-1] size = options.dimension if options.dimension else mx game.window = Window(size=size, fullscreen=not options.windowed) font = Font('media/fonts/open-24-display-st.ttf', 64) game_config = { "canvas_size": game.window.size, "mixer_config": { "mute": options.mute }, "score": Score(font, (20, 5)),
from engine import Game if __name__ == "__main__": game = Game() game.run()
def main(): g = Game(640, 480, framerate = 30, title = "Unicycle Games") g.change_scene( MainMenu(g) ) g.main_loop()
def on_create(self, *args, **kwargs): self.current_game = Game(*args, **kwargs)
pass else: pass elif status==listo: break f.close() def getAllWardrobes(): return [ Wardrobe('audiencia/boy/'), Wardrobe('audiencia/girl/'), Wardrobe('audiencia/fashion_boy/'), Wardrobe('audiencia/fashion_girl/'), Wardrobe('audiencia/goth/'), ] all_wardrobes = getAllWardrobes() def buildIndividual(level, wardrobes): if wardrobes is None: wardrobes = all_wardrobes wd=random.choice(wardrobes) i= Individual(wd) i.random(level=level+1, clothinBehavior=wd.behaviour) return i if __name__ == "__main__": wardrobes = getAllWardrobes() # x,y g = Game(*SCREEN_SIZE, **{'framerate': 200}) g.run( SampleScene(g, "Scene1", wardrobes, level=6) )
from engine import Game import writer from example_game import states, achievements if __name__ == '__main__': game = Game(states, achievements) writer.init(100) while not game.over: game.step() game.test_achievements() writer.print_game_over() input() game.save_and_quit()
ship.id].x].remove(ship) next_pos[ship.id].x = ship.x next_pos[ship.id].y = ship.y commands[ship.id] = MoveCommand(self.id, ship.id, 'O') q.extend(next_ships[ship.y][ship.x]) next_ships[ship.y][ship.x].append(ship) ret = list(commands.values()) if (len(next_ships[self.shipyard.y][self.shipyard.x]) == 0 and self.halite >= 1000 and rem > 100 and np.sum(game.cells[:, :, 0]) * 3 > self.map_starting_halite): ret.append(SpawnShipCommand(self.id, None)) return ret def __repr__(self): return f'{self.__class__.__name__}(id={self.id}, eps={self.eps}, training={self.memory is not None})' epsilon = MAX_EPSILON model = create_unet() model.load_weights('./checkpoints/cp5000_02.ckpt') mem = Memory(10000) for step_num in range(500): epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp( -LAMBDA * step_num) rl_bot = RLBot(model, memory=mem, eps=epsilon) Game.run_game([rl_bot, FastBot()], map_width=32, verbosity=0) print(f'Loss: {rl_bot.total_loss}') if step_num % 20 == 19: model.save_weights(f'./checkpoints/RL_checkpoint_{step_num}')
def main(): game = Game(_details) game.run()
def __init__(self): self.game = Game() self.game.new_game()
def main(): game = Game() game.run()
next_pos[ship.id].x][2]] else: continue # print(f'Stopped ship id {ship.id} to prevent collision') next_ships[next_pos[ship.id].y][next_pos[ship.id].x].remove( ship) next_pos[ship.id].x = ship.x next_pos[ship.id].y = ship.y commands[ship.id] = MoveCommand(self.id, ship.id, 'O') q.extend(next_ships[ship.y][ship.x]) next_ships[ship.y][ship.x].append(ship) ret = list(commands.values()) if (len(next_ships[self.shipyard.y][self.shipyard.x]) == 0 and self.halite >= (1000 if self.pd is None else 5000) and game.max_turns - game.turn > 100): ret.append(SpawnShipCommand(self.id, None)) return ret if __name__ == '__main__': bot1 = FastBot() bot2 = StandardBot() players, cell_data, bank_data, owner_data, collisions = Game.run_game( [bot1, bot2], return_replay=True, map_gen='perlin') my_replay = Replayer.from_data(players, cell_data, bank_data, owner_data, collisions) my_replay.run()