def mock_hs(results_queue): while 1: winner = Player('winner#0', 0.55) loser = Player('loser#99', 0.55) res = {'winner': winner, 'loser': loser} results_queue.put(res) time.sleep(1)
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 __init__(self, first_player_name, second_player_name, score_manager): self.players = [ Player(first_player_name, 0), Player(second_player_name, 0) ] self.score_manager = score_manager
def setUp(self): self.player = Player("player") self.player.history.append( Action.put(1, 1, Position(Piece("a"), Player("a")))) self.player.history.append( Action.put(1, 2, Position(Piece("a"), Player("a")))) self.player.history.append(Action.see(1, 1))
def __init__(self, game, model_name=None): self.game = game self.net = NeuralNetwork(game) self.eval_net = NeuralNetwork(game) self.p1, self.p2 = Player(1), Player(2) self.init_train_data() if model_name: self.net.load_model(model_name)
def setUp(self): self.p1 = Player("test1") self.p1.deck = sampleDeck1 self.p2 = Player("test2") self.p2.deck = sampleDeck2 self.ge = GameEngine(self.p1, self.p2) print("\n\n", self._testMethodName)
def setUp(self): suites = [Suite.HEART, Suite.TILES] ranks = [ Rank.ACE, Rank.KING, ] self.initial_deck = createPlayingDeck(suites, ranks) player_one = Player("Mario", Deck()) player_two = Player("Luigi", Deck()) self.players = [player_one, player_two] self.shuffle_strategy = SimpleShuffleStrategy() self.ranking_strategy = RankScore()
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 initalize(args): # Build the resources/lookup tables that the game needs r = {} with open('resources/items.json') as f: r['items'] = json.load(f) with open('resources/equipment.json') as f: r['equipment'] = json.load(f) with open('resources/story.json') as f: r['story'] = json.load(f) # Get the map fn = f'saves/{args.mapSave}.json' if args.mapSave and os.path.isfile(fn): with open(fn) as f: m = Map(json.load(f), r) print(f'Map loaded from {fn}') else: with open('saves/map.json') as f: m = Map(json.load(f), r) startingRoom = 'start' # Get the player fn = f'saves/{args.playerSave}.json' if args.playerSave and os.path.isfile(fn): # Read in the JSON data with open(fn) as f: pJSON = json.load(f) # Create a new player with the data p = Player('temp', 'temp') p.toPlayer(pJSON, r) startingRoom = pJSON['location'] print(f'Player loaded from {fn}') else: pDetails = introSequence() p = Player(pDetails[0], pDetails[1]) # Get the achievements fn = f'saves/{args.achievementSave}.json' if args.achievementSave and os.path.isfile(fn): with open(fn) as f: aJSON = json.load(f) print(f'Achievement loaded from {fn}') else: with open('saves/achievements.json') as f: aJSON = json.load(f) a = Achievements(aJSON) return GameEngine(m, p, a, r, startingRoom)
def __init__(self): pygame.init() self.background_color = (200, 200, 200) self.main_screen = Screen(background_color=self.background_color) self.controller = Controller() self.player = Player(pygame.Vector2(0, 0)) self.clock = pygame.time.Clock() self.running = False self.action = "" self.value = 0 self.level_one = LevelOne(30, self.background_color) self.player.set_init_pos(self.level_one.player_init) self.player.set_current_level(self.level_one) enemy_mov_period = 1.5 self.enemies = [ Enemy(self.level_one.enemies_init[i], self.level_one.enemies_init_direct[i], 'h', enemy_mov_period, self.level_one.enemies_trajectory[i][0], self.level_one.enemies_trajectory[i][1]) for i in range(len(self.level_one.enemies_init)) ] self.score = Score() pygame.mixer.music.load("SoundTrack/hardestGameThemeSong.mp3") pygame.mixer.music.play(-1) pygame.mixer.music.set_volume(0.5)
def start_search(self): if self.maze.create_maze( ): # Verifica se conseguiu ler o arquivo e criar a matriz do labirinto self.player = Player(self.maze.get_start( )) # Posiciona o jogador no inicio do labirinto self.root_node = Node(self.player.get_position(), None, 0, 0) # Cria o no raiz da árvore self.calculate_cost(self.root_node) self.opened_list.append( self.root_node) # Adiciona o nó raiz na lista de abertos success = False while len(self.opened_list) != 0: self.print_fluxograma() current_node = self.opened_list.pop( 0) # Pega o primeiro nó da lista de abertos self.player.set_position(current_node.get_position()) if not self.is_success( current_node): # Se não for sucesso, explora esse nó self.explore_node(current_node) else: success = True print("------------- Final ---------------") self.create_success_way(current_node) print("\n O custo real eh: {}".format( current_node.get_real_cost())) print("\n A arvore gerada eh: ") self.pprint_tree(self.root_node, "", True) print("\n O caminho no labirinto sera: \n") self.maze_solution() break if not success: print('Não encontrou solução') else: print('Não foi possível criar o labirinto')
def main(width: float, height: float) -> None: pygame.display.set_caption("River Hell") screen = pygame.display.set_mode((width, height)) game = Game(screen, width, height) # Puts a big ass river in the middle of the screen for x in range(int(width * 0.15), int(width * 0.85), 25): for y in range(0, height, 25): game.register_object(River(x, y)) player = Player(50, 50) game.register_object(player) while True: game.tick() game.clear() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() game.update() pygame.display.update()
def __init__(self, width: int, height: int) -> None: pygame.init() os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.display.set_caption("Bee Island") self.__FPS = 60 self.__size = self.width, self.height = width, height self.__screen = pygame.display.set_mode(self.size) icon = pygame.image.load("{0}/icon.ico".format( resource_path("res/images/"))) pygame.display.set_icon(icon) Localization.set_locale(LocalList.RU) self.database = Database() self.main_player = Player() self.__scene_map = { "Map": MapScene(self, name="Map", player=self.main_player), "Farm": FarmScene(self, name="Farm", player=self.main_player), "Main": MainMenuScene(self, name="Main", player=self.main_player) } self.__current_scene = self.__scene_map["Map"] self.change_scene("Main") self.__prev_scene = None self.__done = False self.__clock = Clock()
def test_game_score(score_player_1: int, score_player_2: int, expected_result: str): player1 = Player("player1") player2 = Player("player2") game = Game(player1, player2) score_max = max(score_player_1, score_player_2) for score in range(0, score_max): print(score) if score < score_player_1: game.won_point(player1) if score < score_player_2: game.won_point(player2) score = game.get_score() assert score == expected_result
def CrearJugadores(): arrPlayer = [] print("Cantidad de jugadores que van a jugar:") cantJugadores = int(input()) for h in range(0, cantJugadores): print("Introduce el nombre del jugador ", h, ":") arrPlayer.append(Player(input())) return arrPlayer
def test_add_card(self): character = Character(name='Billie the Kid', health=5) player_samuel = Player(name='Samuel', role='Sheriff', character=character) self.assertEqual(len(player_samuel.hand), 0) player_samuel.add_cards(['Fake card1']) self.assertEqual(len(player_samuel.hand), 1) player_samuel.add_cards(['Fake card2']) self.assertEqual(len(player_samuel.hand), 2)
def test_player_deck(self): deck = Deck() player = Player("Mustapha", deck) #:: cards = [Card(Rank.ACE, Suite.HEART), Card(Rank.TWO, Suite.PIKES)] player.addToDeckBottom(cards) self.assertEqual(player.popDeckTopCard(), cards[0]) self.assertEqual(player.popDeckTopCard(), cards[1])
def test_init(self): character = Character(name='Billie the Kid', health=5) player_samuel = Player(name='Samuel', role='Sheriff', character=character) self.assertEqual(player_samuel.health, 5) self.assertEqual(player_samuel.name, 'Samuel') self.assertEqual(player_samuel.role, 'Sheriff') self.assertIsNone(player_samuel.equipment) self.assertIsNone(player_samuel.weapon) self.assertEqual(len(player_samuel.hand), 0)
def pudding_points(self): max_pudding_count = 0 max_pudding_player = Player("player") for player in self.players: if player.get_pudding() > max_pudding_count: max_pudding_count = player.get_pudding() max_pudding_player = player max_pudding_player.add_points(6)
def maki_points(self): max_maki_count = 0 max_maki_player = Player("player") second_maki_count = 0 second_maki_player = Player("player") for player in self.players: if player.get_maki() > max_maki_count: max_maki_count = player.get_maki() max_maki_player = player elif player.get_maki() > second_maki_count: second_maki_count = player.get_maki() second_maki_player = player max_maki_player.add_points(6) second_maki_player.add_points(3)
def init_player(name): # -- Reading of the XML file tree = etree.parse("data/characters.xml").getroot() player_t = tree.xpath(name)[0] player_class = player_t.find('class').text.strip() race = player_t.find('race').text.strip() lvl = player_t.find('lvl') if lvl is None: # If lvl is not informed, default value is assumes to be 1 lvl = 1 else: lvl = int(lvl.text.strip()) defense = int(player_t.find('initDef').text.strip()) res = int(player_t.find('initRes').text.strip()) hp = int(player_t.find('initHP').text.strip()) strength = int(player_t.find('initStrength').text.strip()) move = int(player_t.find('move').text.strip()) sprite = 'imgs/dungeon_crawl/player/' + player_t.find( 'sprite').text.strip() compl_sprite = player_t.find('complementSprite') if compl_sprite is not None: compl_sprite = 'imgs/dungeon_crawl/player/' + compl_sprite.text.strip( ) equipment = player_t.find('equipment') equipments = [] for eq in equipment.findall('*'): equipments.append( LoadFromXMLManager.parse_item_file(eq.text.strip())) gold = int(player_t.find('gold').text.strip()) # Creating player instance player = Player(name, sprite, hp, defense, res, move, strength, [player_class], equipments, race, gold, lvl, compl_sprite=compl_sprite) # Up stats according to current lvl player.stats_up(lvl - 1) # Restore hp due to lvl up player.healed() inventory = player_t.find('inventory') for it in inventory.findall('item'): item = LoadFromXMLManager.parse_item_file(it.text.strip()) player.set_item(item) return player
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
def test_player_die(self): beer_card = BeerCard(Suit.HEARTS, 5) character = Character(name='Billie the Kid', health=1) player_samuel = Player(name='Samuel', role='Sheriff', character=character) self.assertEqual(player_samuel.health, 1) player_samuel.add_cards(beer_card) player_samuel.change_health(-1) self.assertEqual(player_samuel.health, 1) with self.assertRaises(PlayerDeadException): player_samuel.change_health(-1)
def load_player(name): # -- Reading of the XML file tree = etree.parse("data/characters.xml").getroot() player_t = tree.xpath(name)[0] player_class = player_t.find('class').text.strip() race = player_t.find('race').text.strip() lvl = player_t.find('level') if lvl is None: # If lvl is not informed, default value is assumes to be 1 lvl = 1 else: lvl = int(lvl.text.strip()) defense = int(player_t.find('defense').text.strip()) res = int(player_t.find('resistance').text.strip()) hp = int(player_t.find('hp').text.strip()) strength = int(player_t.find('strength').text.strip()) sprite = 'imgs/' + player_t.find('sprite').text.strip() compl_sprite = player_t.find('complementSprite') if compl_sprite is not None: compl_sprite = 'imgs/dungeon_crawl/player/' + compl_sprite.text.strip() equipments = [] for eq in player_t.findall('equipment/*'): equipments.append(parse_item_file(eq.text.strip())) gold = int(player_t.find('gold').text.strip()) skills = Character.classes_data[player_class][ 'skills'] + Character.races_data[race]['skills'] # Creating player instance player = Player(name, sprite, hp, defense, res, strength, [player_class], equipments, race, gold, lvl, skills, compl_sprite=compl_sprite) # Up stats according to current lvl player.stats_up(lvl - 1) # Restore hp due to lvl up player.healed() inventory = player_t.find('inventory') if inventory is not None: for it in inventory.findall('item'): item = parse_item_file(it.text.strip()) player.set_item(item) return player
def __init__(self, player1name, player1Gender, player2name, player2Gender): # Creation of the card's instances spy_card = Card("Spy", 0, 2) guard_card = Card("Guard", 1, 6) priest_card = Card("Priest", 2, 2) baron_card = Card("Baron", 3, 2) handmaid_card = Card("Handmaid", 4, 2) prince_card = Card("Prince", 5, 2) chancellor_card = Card("Chancellor", 6, 2) king_card = Card("King", 7, 1) countess_card = Card( "Countess", 8, 1, ) princess_card = Card("Princess", 9, 1) # List of cards we will put in the deck self.listOfCards = [ spy_card, guard_card, priest_card, baron_card, handmaid_card, prince_card, chancellor_card, king_card, countess_card, princess_card ] # List of the card we will put on the side at the beginning of each round self.hiddenCard = None self.isolatedCards = [] self.deck = [] # Creation of the players self.player1 = Player(player1name, player1Gender, self.hiddenCard, self.isolatedCards, self.listOfCards) self.player2 = Player(player2name, player2Gender, self.hiddenCard, self.isolatedCards, self.listOfCards) # Assigns the opposite player self.player1.oppositePlayer(self.player2) self.player2.oppositePlayer(self.player1)
def createNewPlayer(self): print("You are cerating a new player\n") first_name = self.safeStrInput("First name : ") last_name = self.safeStrInput("Last name : ") birth_date = self.safeDateInput("Birth date :") sexe = self.safeCharInput("Sexe : ") elo = self.safeIntInput("Elo : ") self.tournament.addPlayerToTab( Player(first_name, last_name, birth_date, sexe, elo)) self.view.clearConsole()
def init_new_level(self): """ :return: None """ self.game_objects.reset() self.game_objects.player = Player((400, 300)) self._generate_level_objects(levels[self.game_state.current_level]) self.game_objects.buttons.extend([ Button(self.ui, "Restart", "restart", (10, 500)), Button(self.ui, "Exit", "exit", (200, 500)) ])
def main(): #:: for a longer game play(longer because of the number of cards in deck), # uncomment and use this input below # suites = [Suite.HEART, Suite.TILES, Suite.CLOVERS, Suite.PIKES] # ranks = [ # Rank.ACE, Rank.KING, Rank.QUEEN, Rank.JACK, # Rank.TEN, Rank.NINE, Rank.EIGHT, Rank.SEVEN, # Rank.SIX, Rank.FIVE, Rank.FOUR, Rank.THREE, # Rank.TWO # ] # initial_deck = createPlayingDeck(suites, ranks) initial_deck_list = [ Card(Rank.ACE, Suite.HEART), Card(Rank.ACE, Suite.CLOVERS), Card(Rank.ACE, Suite.PIKES), Card(Rank.TWO, Suite.CLOVERS) ] initial_deck = Deck() initial_deck.extend(initial_deck_list) #:: create a list of players. player_one = Player("Mario", Deck()) player_two = Player("Luigi", Deck()) players = [player_one, player_two] #:: create your shuffle strategy shuffleStrategy = SimpleShuffleStrategy() #:: create your ranking strategy rankingStrategy = RankScore() #:: create game game = Game(initial_deck, players, shuffleStrategy, rankingStrategy) #:: call game.start() game.start()
def update_game(self): pygame.init() window = pygame.display.set_mode((self.width, self.height)) player1 = Player(10, 10, "Gabe") self.all_sprites.add(player1) self.all_sprites.draw(window) while (self.is_running): for event in pygame.event.get(): if event.type == pygame.QUIT: self.is_running = False pygame.display.update() pygame.time.Clock().tick(self.FPS)
def create_players(self): roles = [Roles.SHERIFF, Roles.OUTLAW, Roles.RENEGADE, Roles.DEPUTY, Roles.OUTLAW, Roles.OUTLAW, Roles.DEPUTY] amount_of_players = len(self.player_names) players = [] if amount_of_players <= len(roles): roles = roles[:amount_of_players] random.shuffle(roles) i = 0 for player, role in zip(self.player_names, roles): players.append(Player(name=player, role=role, character=self.get_character())) if role == Roles.SHERIFF: self.active_player_index = i i += 1 return players else: raise StartGameException('Maximum amount of players is 7 you entered {} players.'.format(amount_of_players))