def setUp(self): """Инициализция нужных классов из base.py для последующей проверки.""" self.game = Game() self.player = Player(self.game, 0, 0) self.wall = Wall(self.game, 0, 0) self.door = Door(self.game, 0, 0) self.exit = Exit(self.game, 0, 0) self.floor = Floor(self.game, 0, 0) self.dark = Dark(self.game, 0, 0) self.trap = Trap(self.game, 0, 0) self.enemy = Enemy(self.game, 0, 0) self.coin = Coin(self.game, 0, 0)
def reset(self): self._log.recordGameMessage("Resetting TileBag") del self._conflictTiles del self.board del self.hotels del self.tilebag del self._log self._initcomponents() for player in self._players: player.reset() # only thing from base class to reset is the "started" flag Game.reset(self)
def readGameStates(): games = [Game(id) for id in ["this", "is", "a", "game", "id"]] from games.tilebag.tilebag import TileBagGame, TileBagPlayer tbg = createGame("TileBag", "test") tbg.addPlayer(TileBagPlayer("513", "Colleen", money=5000)) tbg.addPlayer(TileBagPlayer("514", "Geoff", money=5000)) tbg.addPlayer(TileBagPlayer("515", "Higgs", money=5000)) tbg.addPlayer(TileBagPlayer("516", "FS&SnB", money=5000)) tbg.run()
def evaluate(node: Node, game: Game, network: Network, use_cpu: bool = False): ''' We use the neural network to obtain a value and policy prediction. ''' ego_rep = game.ego_board_representation() ego_value, ego_policy_logits = network.single_inference(ego_rep, use_cpu=use_cpu) # Transform ego-centric to absolute is_first_player = game.is_first_player_turn() value = game.ego2abs_value(is_first_player, ego_value) policy_logits = game.ego2abs_policy(is_first_player, ego_policy_logits) # Expand the node. node.is_first_player = is_first_player # print('eval', '%0.2f' % policy_logits.max()) policy = {a: math.exp(policy_logits[a]) for a in game.legal_actions()} policy_sum = sum(policy.values()) for action, p in policy.items(): node.children[action] = Node(p / policy_sum) # node.children[action] = Node(0) return value
def garbageDeleteMe(): global games if os.path.isfile(_SAVEDSTATES): print("file is there, let's give it a try") with open(_SAVEDSTATES, 'r') as f: print("Recovering server state from file") # TODO: recreate server state from the info in the file #games = json.load(f) #games=[Game(id) for id in range(0,2)] games = [Game(id) for id in ["this", "is", "a", "game", "id"]] from games.tilebag.tilebag import TileBagGame, TileBagPlayer tbg = createGame("TileBag") tbg.addPlayer(TileBagPlayer(513, "Colleen", money=5000)) tbg.addPlayer(TileBagPlayer(514, "Geoff", money=5000)) tbg.addPlayer(TileBagPlayer(515, "Higgs", money=5000)) tbg.addPlayer(TileBagPlayer(516, "FS&SnB", money=5000)) tbg.run() else: print("no saved state, create one") # games=[Game(id) for id in range(0,2)] games = [Game(id) for id in ["this", "is", "a", "game", "id"]] saveGameStates()
def play_game(config: AlphaZeroConfig, Game, network: Network, discount: float = 1): t0 = time.time() game = Game() while not game.terminal() and len(game.history) < config.max_moves: action, root = run_mcts(config, game, network, discount=discount) game.apply(action) game.store_search_statistics(root) if config.max_moves <= len(game.history): # XXX: Set the game value to draw if it continues for too long game.game_value = 0 # Logging game.ch.print_board() print('value', game.game_value, 'time', '%.2f' % (time.time() - t0), 'len', len(game.history)) return game
def run_mcts(config: AlphaZeroConfig, game: Game, network: Network, discount: float = 1, use_cpu: bool = False): ''' Core Monte Carlo Tree Search algorithm. To decide on an action, we run N simulations, always starting at the root of the search tree and traversing the tree according to a modified UCB formula until we reach a leaf node. This implementation keeps the rollout statistics in a separate tree structure. ''' root = Node(0) evaluate(root, game, network, use_cpu=use_cpu) add_exploration_noise(config, root) for _ in range(config.num_simulations): node = root # NOTE: Clone a game possibly without its history. Only its game state is needed scratch_game = game.clone() search_path = [node] # TODO Handle draws due to infinite loops? The random behavior will likely prevent looping for too long. while node.expanded(): # Tree policy, greedy with respect to modified UCB scores action, node = select_child(config, node) scratch_game.apply(action) # NOTE: search path is within the expanded region of nodes search_path.append(node) # Expand and evaluate (Done with a rollout policy in vanilla MCTS) # NOTE: Instead of running a simulation (MC evaluation) for an unexpanded node, we evaluate it by the value network. value = evaluate(node, scratch_game, network, use_cpu=use_cpu) backpropagate(search_path, value, discount=discount) # # Log # for ac, child in root.children.items(): # print(game.actions[ac], child.is_first_player == root.is_first_player, '%.2f' % child.sampled_value(), child.visit_count) return select_action(config, game, root), root
# File: run.py # Organizes user interface, runs the game # Created by Ivan Kosarevych # 18.02.2017 19:06:57 """ from base import Game import time, os # get players' names player1_name = input('Player 1, enter your name: ') os.system('clear') player2_name = input('Player 2, enter your name: ') # start the game game = Game(player1_name, player2_name) while True: os.system('clear') input('Press any key to start') # check whether we have a winner and if so finish if game.check_winner((game._current_player - 1) % 2) or game.check_winner( game._current_player): winner = game._players[game._current_player]._name break print('\n') game.field_with_ships(game._current_player) print('\n') game.field_without_ships((game._current_player - 1) % 2)
# Объявление глобальной переменной для подсчета монет all_collected_coins = 0 myPath = os.path.abspath(os.path.dirname(sys.argv[0])) if myPath[-12:] != "/GameProject": myPath += "/GameProject" # Считывание из общей директории карты комнат with open(myPath + '/RoomsInDungeon/map.in', 'r') as f: map = f.read() map_list = map.splitlines() # Объявление начальной комнаты if __name__ == "__main__": cached_dir = "" try: g = Game() g.menu.menu.mainloop(g.screen) playerName = g.playerName path = os.getcwd() cached_dir = shutil.copytree(str(myPath + "/RoomsInDungeon"), str(myPath + "/CachedRoomsInDungeon")) PATH_TO_ROOMS = myPath + "/CachedRoomsInDungeon/" CURRENT_ROOM = PATH_TO_ROOMS + \ map_list[CURRENT_MAP_POSITION[1]][CURRENT_MAP_POSITION[0]] + '.in' g.new(CURRENT_ROOM) # Основной цикл игры. while g.running: g.main() # Считывание новой комнаты при переходе через двери. if g.player.go_down: # Если персонаж вошел в нижнюю дверь, поменяй комнату на нижнюю.
class TestBase(unittest.TestCase): """Инициализация класса для тестирования.""" mypath = os.path.abspath(os.path.dirname(sys.argv[0])) + '/GameProject/RoomsInDungeon/' def setUp(self): """Инициализция нужных классов из base.py для последующей проверки.""" self.game = Game() self.player = Player(self.game, 0, 0) self.wall = Wall(self.game, 0, 0) self.door = Door(self.game, 0, 0) self.exit = Exit(self.game, 0, 0) self.floor = Floor(self.game, 0, 0) self.dark = Dark(self.game, 0, 0) self.trap = Trap(self.game, 0, 0) self.enemy = Enemy(self.game, 0, 0) self.coin = Coin(self.game, 0, 0) def test_01_room_objects(self): """Проверка на то, нет ли в файлах комнат *.in неопознанных объектов.""" # print(os.getcwd()) rooms_list = [f for f in os.listdir( self.mypath) if os.path.isfile(os.path.join(self.mypath, f))] for room in rooms_list: if (self.mypath + str(room)) == self.mypath + "map.in": continue self.game.new(self.mypath + str(room)) try: self.game.read_room_file(self.mypath + str(room)) except ValueError: self.assertTrue(False) def test_02_gameSize(self): """Проверка на то, совпадают ли размеры окна с имеющимися константами, заданными в base.py.""" self.assertEqual(self.game.screen.get_size(), (SCREEN_WIDTH, SCREEN_HEIGHT)) def test_03_menu(self): """Проверка на то, корректно ли заданы параметры menu.""" self.assertEqual(vars(self.game.menu.menu)["_window_size"], (SCREEN_WIDTH, SCREEN_HEIGHT)) self.assertEqual(vars(vars(vars(self.game.menu.menu)["_theme"])[ "background_color"])["_filepath"], self.mypath[:-16] + "/Screens/intro.png") self.assertEqual(vars(vars(self.game.menu.menu)["_theme"])[ "title_background_color"], (76, 36, 25, 255)) self.assertEqual(vars(vars(self.game.menu.menu)["_theme"])["widget_padding"], 25) self.assertEqual(vars(vars(self.game.menu.menu)["_theme"])["widget_font"], "Arial") self.assertEqual(vars(vars(self.game.menu.menu)["_theme"])["title_font_shadow"], True) self.assertEqual(vars(vars(self.game.menu.menu)["_theme"])[ "focus_background_color"], (217, 140, 63, 255)) self.assertEqual(vars(vars(self.game.menu.menu)["_theme"])[ "selection_color"], (217, 178, 63, 255)) self.assertEqual(vars(vars(self.game.menu.menu)["_theme"])[ "title_font_color"], (217, 178, 63, 255)) self.assertEqual(vars(vars(self.game.menu.menu)["_theme"])[ "widget_font_color"], (217, 178, 63, 255)) def test_04_menu_obj(self): """Проверка на то, корректно ли работают виджеты в menu.""" self.assertEqual(len((vars(self.game.menu.menu)["_widget_columns"])[0]), 5) def test_05_png_names(self): """Проверка на то, все ли файлы *.png используемые для прорисовки скриптов выбранных классов имеются в репозитории.""" # print(os.getcwd()) for name in self.game.png_names: self.assertTrue(os.path.exists(name)) def test_06_player_class(self): """Проверка правильной инициализации класса Player.""" self.assertEqual(self.game, self.player.game) self.assertEqual(PLAYER_LAYER, self.player._layer) self.assertEqual(self.player.width, TILESIZE) self.assertEqual(self.player.height, TILESIZE) self.assertEqual(self.player.x_change, 0) self.assertEqual(self.player.y_change, 0) self.assertEqual(self.player.facing, 'down') self.assertEqual(self.player.alive, True) self.assertEqual(self.player.win, False) self.assertEqual(self.player.collision_immune, False) self.assertEqual(self.player.collision_time, 0) self.assertEqual(self.player.attacking, False) self.assertEqual(self.player.attacking_time, 0) self.assertEqual(len(self.player.image_down), 8) self.assertEqual(len(self.player.image_up), 8) self.assertEqual(len(self.player.image_right), 8) self.assertEqual(len(self.player.image_left), 8) self.assertEqual(len(self.player.attackloop), 4) def test_07_wall_class(self): """Проверка правильной инициализации класса Wall.""" self.assertEqual(self.game, self.wall.game) self.assertEqual(PLAYER_LAYER, self.wall._layer) self.assertEqual(self.wall.width, TILESIZE) self.assertEqual(self.wall.height, TILESIZE) def test_08_door_class(self): """Проверка правильной инициализации класса Door.""" self.assertEqual(self.game, self.door.game) self.assertEqual(PLAYER_LAYER, self.door._layer) self.assertEqual(self.door.width, TILESIZE) self.assertEqual(self.door.height, TILESIZE) def test_09_exit_class(self): """Проверка правильной инициализации класса Exit.""" self.assertEqual(self.game, self.exit.game) self.assertEqual(PLAYER_LAYER, self.exit._layer) self.assertEqual(self.exit.width, TILESIZE) self.assertEqual(self.exit.height, TILESIZE) def test_10_floor_class(self): """Проверка правильной инициализации класса Floor.""" self.assertEqual(self.game, self.floor.game) self.assertEqual(FLOOR_LAYER, self.floor._layer) self.assertEqual(self.floor.width, TILESIZE) self.assertEqual(self.floor.height, TILESIZE) def test_11_dark_class(self): """Проверка правильной инициализации класса Dark.""" self.assertEqual(self.game, self.dark.game) self.assertNotEqual(FLOOR_LAYER, self.dark._layer) self.assertEqual(self.dark.width, TILESIZE) self.assertEqual(self.dark.height, TILESIZE) def test_12_coin_class(self): """Проверка правильной инициализации класса Coin.""" self.assertEqual(self.game, self.coin.game) self.assertEqual(PLAYER_LAYER, self.coin._layer) self.assertEqual(self.coin.width, TILESIZE) self.assertEqual(self.coin.height, TILESIZE) def test_13_trap_class(self): """Проверка правильной инициализации класса Trap.""" self.assertEqual(self.game, self.trap.game) self.assertNotEqual(FLOOR_LAYER, self.trap._layer) self.assertEqual(self.trap.width, TILESIZE) self.assertEqual(self.trap.height, TILESIZE) def test_14_enemy_class(self): """Проверка правильной инициализации класса Enemy.""" self.assertEqual(self.game, self.enemy.game) self.assertEqual(PLAYER_LAYER, self.enemy._layer) self.assertEqual(self.enemy.width, TILESIZE) self.assertEqual(self.enemy.height, TILESIZE) self.assertTrue(0 == self.enemy.randdirect or self.enemy.randdirect == 1) self.assertTrue((0 == self.enemy.x_direction and self.enemy.y_direction == 1 ) or (1 == self.enemy.x_direction and self.enemy.y_direction == 0)) self.assertEqual(self.enemy.facing, 'down') self.assertEqual(self.enemy.lifes, 1) self.assertEqual(len(self.enemy.image_slime), 4) def test_15_game_methods(self): """Проверка методов класса Game – new() и read_room_file().""" rooms_list = [f for f in os.listdir( self.mypath) if os.path.isfile(os.path.join(self.mypath, f))] try: self.game.new(self.mypath + str(rooms_list[4])) self.game.read_room_file = MagicMock() self.game.new(self.mypath + str(rooms_list[4])) except Exception: self.assertTrue(False) else: self.game.read_room_file.assert_called_once_with(self.mypath + str(rooms_list[4])) self.assertIsNotNone(self.game.wall_list) self.assertIsNotNone(self.game.player) self.assertIsNotNone(self.game.doors_list) self.assertIsNotNone(self.game.floors_list)
def __del__(self): # todo, delete all of our things print("Deleting TileBagGame") Game.__del__(self)
def __init__(self, id): Game.__init__(self, id) self._initcomponents() self._log.recordGameMessage("Game Created") blah = TileBagGame.BuyStocks