def __init__(self, player1, player2): pygame.init() pygame.font.init() self.player1 = player1 self.player2 = player2 self.neutralPlayer = Player('neutral', 10000000000000, 3, 'Neutrals') self.factory1 = UnitFactory(player1, self) self.factory2 = UnitFactory(player2, self) self.factoryNeutral = UnitFactory(self.neutralPlayer, self) self.player1.factory = self.factory1 self.player2.factory = self.factory2 self.neutralPlayer.factory = self.factoryNeutral self.board = Board(self) bw, bh = self.board.real_size_with_offsets() self.cpanel = CPanel(self, bw, self.board.top_offset, 400, self.board.real_size_with_offsets()[1]) self.screen = pygame.display.set_mode((bw + self.cpanel.width, bh)) self.clock = pygame.time.Clock() self.gamestate = GameState(player1, self) self.rules = Rules(self) self.render_mode = 'normal' self.board.generate_neutrals(Rules.NEUTRAL_GENERATING_STRATEGY())
def getNextStep(self,state): listState=[] st=time.time() if state.player==SELF_PLAYER: tmpPlayer=ENEMS_PLAYER else: tmpPlayer=SELF_PLAYER loc,dirs=self.getMoveCombinationAll(tmpPlayer, state) for i in range(len(loc)): tempLoc=loc[i] tempDirs=dirs[i] colisionMove=False for e in tempLoc: if tempLoc.count(e)>1: colisionMove=True if colisionMove: continue cMap=self.getClearMap(state,tmpPlayer) for (r,c) in tempLoc: cMap[r][c]=tmpPlayer s=GameState(cMap, tmpPlayer) s.dirs=tempDirs listKill=self.preKill(s) for (r,c,p) in listKill: s.map[r][c]=LAND s.reward=(len(self.getAnts(s,SELF_PLAYER)),len(self.getAnts(s, ENEMS_PLAYER))) listState.append(s) return listState
def __init__(self, numHumans, numComps): self.players = [] cardIds = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] r.shuffle(cardIds) self.startingDeck = [ Gaurd(cardIds[0]), Gaurd(cardIds[1]), Gaurd(cardIds[2]), Gaurd(cardIds[3]), Gaurd(cardIds[4]), Priest(cardIds[5]), Priest(cardIds[6]), Baron(cardIds[7]), Baron(cardIds[8]), Handmaid(cardIds[9]), Handmaid(cardIds[10]), Prince(cardIds[11]), Prince(cardIds[12]), King(cardIds[13]), Countess(cardIds[14]), Princess(cardIds[15])] # self.startingDeck = [Gaurd(0), Priest(1), Handmaid(2), Princess(3)] deck = self.startingDeck.copy() r.shuffle(deck) self.state = GameState(numHumans + numComps, deck) if numHumans + numComps > 4 or numHumans + numComps < 2: util.raiseException("must have 2 to 4 players") for i in range(numHumans): self.players.append(Player.createPlayer("human", i, self.state)) for i in range(numComps): self.players.append(Player.createPlayer("computer", i + numHumans, self.state)) self.state.setPlayers(self.players)
def __init__(self, saves_path: str, base_path: str, game_xml_path: str, desired_win_size_pixels: Optional[Point], tile_size_pixels: int) -> None: # Determine effective window size in both tiles and pixels # Initialize the pygame displays if desired_win_size_pixels is None: screen = pygame.display.set_mode( (0, 0), pygame.FULLSCREEN | pygame.NOFRAME | pygame.SRCALPHA) # | pygame.DOUBLEBUF | pygame.HWSURFACE) self.win_size_pixels = Point(screen.get_size()) win_size_tiles = (self.win_size_pixels / tile_size_pixels).floor() else: win_size_tiles = (desired_win_size_pixels / tile_size_pixels).floor() self.win_size_pixels = win_size_tiles * tile_size_pixels pygame.display.set_mode( self.win_size_pixels.getAsIntTuple(), pygame.SRCALPHA) # | pygame.DOUBLEBUF | pygame.HWSURFACE) self.title_image, self.title_music = \ GameInfo.static_init(base_path, game_xml_path, win_size_tiles, tile_size_pixels) self.title_screen('Loading...') self.game_state = GameState(saves_path, base_path, game_xml_path, win_size_tiles, tile_size_pixels) self.gde = GameDialogEvaluator(self.game_state.game_info, self.game_state) self.gde.update_default_dialog_font_color()
def test_secret_asks_for_two_cards_puts_the_range_in_history_and_display_the_result(self): try: old_raw_input = raw_input Interactive.raw_input = mock_raw_input('1', '9$', '1H') # opponent id, low card, high card player = HumanPlayer('joe') donna = AIPlayer('donna') donna._hand = [(1, 'L'), (3, 'L'), (6, 'L'), (2, 'H'), (8, '$'), (9, '$')] state = GameState() state.turn = 1 state.current_player = player state.players = [player, donna] state.question_cards = [(1, 'L'), (3, 'L'), (7, 'L')] with captured_output() as (out, err): turn_ended = secret_command(state) self.assertEqual('Secret\n' 'Cards in this range: 2', output(out)) turn = state.history.pop() self.assertEqual(1, turn['turn']) self.assertEqual('joe', turn['player'].name) self.assertEqual('donna', turn['opponent'].name) self.assertEqual('secret', turn['action']) self.assertEqual(['L', 'H', '$'], turn['range'].suits) self.assertEqual([9, 1], turn['range'].ranks) self.assertEqual(2, turn['result']) self.assertTrue(turn_ended) self.assertEqual(0, state.current_player.secret) finally: Interactive.raw_input = old_raw_input
def main(): # initializing and drawing background UI elements background = UIBox(g_const.screen_size, (0, 0, 0), (0, 0)) arena = UIBox(g_const.arena_size, (50, 50, 50), g_const.arena_pos) sidebar = UIBox(g_const.sidebar_size, (50, 50, 50), g_const.sidebar_pos) background.draw() sidebar.draw() evt_man = EventManager() terrain = Terrain() game_state = GameState(terrain) start = time.time() evt_man.start_world_update() while True: dt = time.time() - start if dt >= frame_length: start = time.time() # reset start tick events = evt_man.processEvents() # handle events game_state.update(events) # update game state # draw objects arena.draw() game_state.curr_shape.draw() terrain.draw() # update display pyg.display.update()
def __init__(self, player_type: type(Player), game_id: int, game_type: GameType=GameType.PROGRESSIVE): self.players = [player_type(0, Teams.TEAM_A, "Player-0"), player_type(1, Teams.TEAM_B, "Player-1"), player_type(2, Teams.TEAM_A, "Player-2"), player_type(3, Teams.TEAM_B, "Player-3")] self.game_type = game_type self.scores = [0, 0] # Indexed using TEAM_A and TEAM_B self.tricks_won = [0, 0] # Indexed using TEAM_A and TEAM_B self.deck = Deck() self.game_state = GameState(game_id) self.players[self.game_state.current_dealer].set_dealer() self.current_player_turn = (self.game_state.current_dealer + 1) % len(self.players) self.game_state.set_state(GameState.GAME_START) self.loaner_team = None self.loaner_player = None self.trick_obj = None
def play_game(): mat_init = add_two( add_two([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])) # mat_init = [[8, 4, 2, 8], [2, 16, 8, 4], [256, 32, 4, 2], [4, 2, 4, 2]] # Death matrix for debugging # mat_init = [[2,4,32,2],[4,16,512,4],[4,8,128,16],[4,16,8,2]] # Death matrix for debugging state = GameState(mat_init) # Initialize 2048 grid loop_count = 0 game_over = False # True if add_two can't add anywhere after moving while state.game_state( ) == 'not over' and game_over == False: # Run if the game is not over loop_count += 1 print("Move count: " + str(loop_count)) print("Points : " + str(state.point_count)) print(str(state)) move = UCT(root_state=state, n_search_path=50, n_search_depth=5, exploration_const=100, verbose=True) print("Best Move: " + str(move) + "\n") game_over = state.do_move(move) print("======================= Game Over =======================") print(str(state)) print(state.game_state())
def test_interrogate_asks_for_two_cards_puts_the_range_in_history_and_display_the_result(self): try: old_raw_input = raw_input Interactive.raw_input = mock_raw_input('1', '3L', '7L') # opponent id, low card, high card player = HumanPlayer('joe') tom = AIPlayer('tom') tom._hand = [(1, 'L'), (3, 'L'), (6, 'L'), (2, 'H'), (8, '$'), (9, '$')] state = GameState() state.turn = 10 state.current_player = player state.players = [player, tom] state.question_cards = [(1, 'L'), (3, 'L'), (7, 'L')] with captured_output() as (out, err): turn_ended = interrogate_command(state) self.assertEqual('Interrogate\n' 'Question cards: 1L 3L 7L\n' 'Cards in this range: 2', output(out)) turn = state.history.pop() self.assertEqual(10, turn['turn']) self.assertEqual('joe', turn['player'].name) self.assertEqual('tom', turn['opponent'].name) self.assertEqual('interrogate', turn['action']) self.assertEqual(['L'], turn['range'].suits) self.assertEqual([3, 4, 5, 6, 7], turn['range'].ranks) self.assertEqual(2, turn['result']) self.assertTrue(turn_ended) finally: Interactive.raw_input = old_raw_input
def test_accuse_bad_guess_of_cards(self): try: old_raw_input = raw_input Interactive.raw_input = mock_raw_input('1', '1L', '2L') # opponent id, first card, second card joe = HumanPlayer('joe') joe._hand = [(4, 'L'), (8, 'L'), (5, 'H'), (8, 'H')] ai = AIPlayer('ai') ai._hand = [(1, 'L'), (3, 'L'), (1, 'H'), (9, '$')] state = GameState() state.turn = 23 state.current_player = joe state.players = [joe, ai] state.evidence_cards = [(5, '$'), (5, 'L')] with captured_output() as (out, err): self.assertTrue(accuse_command(state)) self.assertEqual('Accuse\n\n' 'Your guess is: Incorrect', output(out)) accusation = state.accusations.pop() self.assertEqual('joe', accusation['player'].name) self.assertEqual('ai', accusation['accused'].name) self.assertEqual([(1, 'L'), (2, 'L')], accusation['cards']) self.assertEqual('incorrect', accusation['outcome']) self.assertEqual('ended', state.status) finally: Interactive.raw_input = old_raw_input
def test_interrogate_for_the_same_two_cards_asks_for_rank_or_suit(self): try: old_raw_input = raw_input Interactive.raw_input = mock_raw_input('1', '3L', '3L', 'suit') # opponent id, low card, high card player = HumanPlayer('joe') tom = AIPlayer('Tom') tom._hand = [(1, 'L'), (3, 'L'), (6, 'L'), (2, 'H'), (8, '$'), (9, '$')] state = GameState() state.turn = 10 state.current_player = player state.players = [player, tom] state.question_cards = [(1, '$'), (3, 'L'), (3, 'L')] with captured_output() as (out, err): turn_ended = interrogate_command(state) self.assertEqual('Interrogate\n' 'Question cards: 1$ 3L 3L\n' 'Cards in this range: 3', output(out)) turn = state.history.pop() self.assertEqual(10, turn['turn']) self.assertEqual('joe', turn['player'].name) self.assertEqual('Tom', turn['opponent'].name) self.assertEqual('interrogate', turn['action']) self.assertEqual('3L->3L [suit]', str(turn['range'])) self.assertEqual(3, turn['result']) self.assertTrue(turn_ended) finally: Interactive.raw_input = old_raw_input
def test_discard_question_cards(self): state = GameState() state.question_cards = [(2, 'H'), (7, 'H'), (5, '$')] state.discard_deck = [] discard_question_cards(state.question_cards, state.discard_deck) self.assertEqual([(2, 'H'), (7, 'H'), (5, '$')], state.discard_deck) self.assertEqual([], state.question_cards)
def test_draw_question_cards(self): state = GameState() state.interrogation_deck = [(8, 'H'), (3, '$'), (1, '$'), (1, 'L')] draw_question_cards(state) self.assertItemsEqual([(1, 'L'), (1, '$'), (3, '$')], state.question_cards) self.assertEqual([(8, 'H')], state.interrogation_deck)
def run_game(k): mean_low, mean_high = (-5, 5) stdev_low, stdev_high = (0, 3) distros = [] for _ in range(k): distros.append( Normal(random.uniform(mean_low, mean_high), random.uniform(stdev_low, stdev_high))) bandit = DistroBandit(distros) game_state = GameState(bandit) print( f"This is the k-armed bandit game for k={k}.\nThe action rewards are sampled from normal distributions, which are randomly initialized for each action with each mean uniformly sampled from ({mean_low}, {mean_high}) and each standard deviation uniformly sampled from ({stdev_low}, {stdev_high})." ) while True: selection = input( "Select an Action...\n\t\ttotal reward - prints accumulated reward\n\t\t0-k - do an action\n\t\tquit - quit the game\n" ) if selection == "quit": print("Goodbye!") break elif selection.isdigit(): if int(selection) >= game_state.bandit.k: print("Action out of range.") continue reward = game_state.select(int(selection)) print(f"\tReward gained: {reward}") elif selection == "total reward": print(f"\tTotal Reward so far: {game_state.total_reward}") else: print("\tUnrecognized action, try again.") print("___")
def test_accuse_bad_guess_of_murderer(self): try: old_raw_input = raw_input Interactive.raw_input = mock_raw_input('1', '3L', '5L') # opponent id, first card, second card joe = HumanPlayer('joe') joe._hand = [(4, 'L'), (7, 'L'), (5, 'H'), (8, 'H')] ai1 = AIPlayer('ai1') ai1._hand = [(1, 'L'), (3, 'L'), (1, 'H'), (9, '$')] ai2 = AIPlayer('ai2') ai2._hand = [(8, 'L'), (3, 'H'), (2, '$'), (3, '$')] state = GameState() state.turn = 23 state.current_player = joe state.players = [joe, ai1, ai2] state.evidence_cards = [(3, 'L'), (5, 'L')] with captured_output() as (out, err): self.assertTrue(accuse_command(state)) self.assertEqual('Accuse\n\n' 'Your guess is: Incorrect', output(out)) self.assertEqual('ended', state.status) finally: Interactive.raw_input = old_raw_input
def playTak(): currentGameState = GameState() print(currentGameState) with tf.Graph().as_default(): # make graph to apply the network # boards = tf.placeholder(tf.float32) # pieceCounts = tf.placeholder(tf.float32) # inferenceOp = TakNet.inference(boards, pieceCounts) # mimic training graph structure to load variables globalStep = tf.contrib.framework.get_or_create_global_step() # get data boards, pieceCounts, realScores = TakNet.inputs(False) # instantiate prediction graph scores = TakNet.inference(boards, pieceCounts) # calculate loss totalLoss, meanLoss = TakNet.loss(realScores, scores) # train for one batch and update parameters # noinspection PyUnusedLocal trainOp = TakNet.train(totalLoss, meanLoss, globalStep) with tf.Session() as session: # restore weights from model in Network folder tf.train.Saver().restore(session, tf.train.latest_checkpoint("Network")) tf.get_variable_scope().reuse_variables() boards2 = tf.placeholder(tf.float32) pieceCounts2 = tf.placeholder(tf.float32) inferenceOp = TakNet.inference(boards2, pieceCounts2) while True: try: if currentGameState.turnIndicator == 1: startTime = time.time() move = miniMax(currentGameState, session, inferenceOp, boards2, pieceCounts2) endTime = time.time() print("TakticalBot: " + move) print("Time: " + str(endTime - startTime)) else: move = input("Player: ") if move == "quit": break currentGameState = currentGameState.applyMove(move) print(currentGameState) winner = currentGameState.checkVictory() if winner != 2: if winner == 1: print("TakticalBot Won!") elif winner == -1: print("You Won!") else: print("It was a draw") break except TakException as exception: print(exception) continue
def main(): state = input() gameState = GameState() gameState.feed(state) ai = ClassicalAI() move = ai.makeMove(GameState) print(move.get_json())
def setUp(self) -> None: self.map0 = '../game_states/game0_repr.json' self.game_state = GameState(self.map0) self.ih = InputHandler(self.game_state) self.map_two_helmets = '../game_states/game_two_helmets.json' self.game_two_helmets = GameState(self.map_two_helmets) self.ih_two_helmets = InputHandler(self.game_two_helmets)
def setUp(self) -> None: self.map0 = '../game_states/game0_repr.json' self.game_state = GameState(self.map0) self.ih = InputHandler(self.game_state) self.map1 = '../game_states/game1_cake.json' self.game_state1 = GameState(self.map1) self.ih1 = InputHandler(self.game_state1)
def test_processes_all_keys(self): helper = GameState("Hello") process_result = helper.process_key("H") process_result = helper.process_key("e") process_result = helper.process_key("l") process_result = helper.process_key("l") process_result = helper.process_key("o") process_result = helper.process_key("!") self.assertTrue(process_result)
def __init__(self, stdscr): self.stdscr = stdscr self.game_state = GameState() self.metrics_counter = MetricsCounter() self.cursor_positions = [] self.bubble_frame_index = 0 self.init_screen() self.init_curses() self.push_cursor_position()
def test_players_except(self): state = GameState() tom = HumanPlayer('tom') tim = AIPlayer('tim') tam = AIPlayer('tam') ari = AIPlayer('ari') state.players = [tom, tim, tam, ari] self.assertEqual([tom, tam], state.players_except(tim, ari))
def __init__(self, width, height, evaluator="default", name="JJF"): self.color = "" self.width = width self.height = height self.innerstate = GameState(width, height) self.evaluator = Evaluator(evaluator) self.name = name self.innerstate.populate_bauern()
def test_draw_question_cards_when_there_are_not_enough_cards_in_the_interrogation_deck(self): state = GameState() state.interrogation_deck = [(4, 'L')] state.discard_deck = [(3, '$'), (6, 'H'), (7, 'L')] draw_question_cards(state) self.assertEqual(3, len(state.question_cards)) self.assertIn((4, 'L'), state.question_cards) self.assertEqual(0, len(state.discard_deck)) self.assertEqual(1, len(state.interrogation_deck))
def search(state, level): if level % 100 == 0: print(str(level)) if level == TEST_DEPTH: pass newState = GameState() newState.setBoard(state.copyArr()) search(newState, level + 1) pass
def parse(file_name): game_state = GameState() f = open(file_name) quest_script_source = yaml.safe_load(f) f.close() for task_source in quest_script_source["tasks"]: task = fillTask(task_source) game_state.add_task(task) return game_state
def new_game(self, layout, pacman_agent, ghost_agents): agents = [pacman_agent] + ghost_agents[:layout.get_num_ghosts()] init_state = GameState() init_state.initialize(layout, len(ghost_agents)) game = Game(agents, self, 0) game.state = init_state self.init_state = init_state.deepcopy() game.run() return game
def test_get_smallest_winning_card(self): game_state = GameState(1) game_state.lead_card = Card(Card.SUIT_HEARTS, 10) game_state.trick_cards = [game_state.lead_card] game_state.trumps = Card.SUIT_HEARTS lead_card_suit = game_state.lead_card.get_suit(game_state.trumps) smallest_winning = self.player.smallest_winning_card( Card.SUIT_HEARTS, game_state.trick_cards, game_state.get_valid_plays(self.player.hand)) self.assertIsNotNone(smallest_winning) self.assertEqual(Card.SUIT_HEARTS, smallest_winning.get_suit(game_state.trumps)) self.assertEqual( Card.ACE + Card.TRUMP_BONUS, smallest_winning.get_total_value(game_state.trumps, lead_card_suit)) game_state.lead_card = Card(Card.SUIT_HEARTS, Card.JACK) game_state.trick_cards = [game_state.lead_card] smallest_winning = self.player.smallest_winning_card( Card.SUIT_HEARTS, game_state.trick_cards, game_state.get_valid_plays(self.player.hand)) self.assertIsNone(smallest_winning)
def test_players_except_should_return_gracefully_if_player_not_in_players(self): state = GameState() tom = HumanPlayer('tom') tim = AIPlayer('tim') state.players = [tom] try: self.assertEqual([tom], state.players_except(tim)) except ValueError: self.fail("GameState.players_except(person) should not fail if person is not in players")
def __init__(self): self.board = CheckerBoard() self.view = CheckersGUI(self) self.state = GameState(GameState.WhitesTurn) self.white_player = Player.Human_Player(Player.WHITE) self.black_player = Player.AI_Player(Player.BLACK, self) self.white_win_count = 0 self.black_win_count = 0 self.last_clicked = None self.ai_active = True self.ai_color = Player.BLACK
def random_rollout_result(game_state: GameState, player_turn: int): """ Performs a random rollout from a given game state for the current player until the end of their turn :param game_state: GameState to perform rollout from :param player_turn: Player to perform rollout for. Rollout finishes when this player's turn is over :return: GameState after the player's turn is over """ while game_state.player_turn == player_turn: possible_actions = game_state.get_next_actions() game_state.resolve_action(choice(possible_actions)) return game_state
def doGame(bot1, bot2, verboseLog): gameState = GameState(verboseLog) while (gameState.isGameOver == False): currentPlayer = gameState.getCurrentPicker() if (currentPlayer == Player.PLAYER1): bot1.doMove(gameState) else: bot2.doMove(gameState) if (verboseLog): print(F"Game is over. The outcome is: {gameState.getGameState()}") return gameState.getGameState()
def __init__(self, AIs, debug = False): self.gs = GameState() self.turn = random.randint(0, 3) self.pgs = [] for i in range(4): self.pgs.append(GameState(self.gs.cards, i)) self.AIs = AIs self.debug = debug self.is_game_over = False self.score = [0]*4
def turn(self, board, state): moves = board.getAllMoves(state) if not moves: return # variables for finding the best move for this turn board_orig = copy.deepcopy(board.board) value_best = -99 end_best = 0 start_best = 0 updateGUI = 0 # search for the next best move random.shuffle(moves) for move in moves: board.board = copy.deepcopy(board_orig) end = move.pop() start = move.pop() last_cell = board.board[start.row][start.column] return_code = board.move(start, end, state) self.jumpAgain(board, state, return_code, updateGUI) # now play the other player's move if (state.get_state() == 2): state_other = GameState(GameState.WhitesTurn) self.turn_other(board, state_other) elif (state.get_state() == 1): state_other = GameState(GameState.BlacksTurn) self.turn_other(board, state_other) else: print "Invalid player state" value = board.getValue(state) print value if value > value_best: value_best = value end_best = end start_best = start # we found it so actually make the move updateGUI = 1 board.board = copy.deepcopy(board_orig) print "CHOOSE THIS MOVE" print value_best last_cell = board.board[start_best.row][start_best.column] return_code = board.move(start, end, state) self.checkers.move(start, end, last_cell, return_code) self.jumpAgain(board, state, return_code, updateGUI) board.printBoard() print "AI turn complete"
def __init__(self, players, updater=None): self.players = players self.nplayers = len(players) self.state = GameState(self.nplayers) self.validator = Validator(self.state) self.logger = logging.getLogger(__name__) if updater is not None: self.update = ViewUpdater() else: self.update = updater self.delay = 0.5 self.stalematecond = 2000
def play_turn(game_state: GameState, ai) -> None: """ Play a single turn in a game using the ai to select moves to take. :param game_state: GameState at the start of the turn :param ai: Function to choose the next action, based on the current GameState :return: None """ current_player = game_state.player_turn while game_state.player_turn == current_player: game_state.assert_valid_game_state() chosen_action = ai(game_state, game_state.get_next_actions()) game_state.resolve_action(chosen_action)
def test_secret_is_refused_if_no_secrets_left(self): player = HumanPlayer('joe') player._secret = 0 state = GameState() state.turn = 1 state.current_player = player with captured_output() as (out, err): turn_ended = secret_command(state) self.assertEqual('Secret already used!', output(out)) self.assertFalse(turn_ended)
def turn(self, board, state): moves = board.getAllMoves(state) if not moves: return # variables for finding the best move for this turn board_orig = copy.deepcopy(board.board) value_best = -99 start_best = 0 updateGUI = 0 # search for the next best move random.shuffle(moves) for move in moves: board.board = copy.deepcopy(board_orig) end = move.pop() start = move.pop() return_code = board.move(start, end, state) self.jumpAgain(board, state, return_code, updateGUI) # now play the other player's move if (state.get_state() == 2): state_other = GameState(GameState.WhitesTurn) self.turn_other(board, state_other) elif (state.get_state() == 1): state_other = GameState(GameState.BlacksTurn) self.turn_other(board, state_other) else: print "Invalid player state" value = board.getValue(state) print "The value for this board is: ", value if value > value_best: value_best = value start_best = start # we found it so actually make the move updateGUI = 1 board.board = copy.deepcopy(board_orig) print "Choose the move with this value: ", value_best last_cell = board.board[start_best.row][start_best.column] return_code = board.move(start, end, state) self.checkers.move(start, end, last_cell, return_code) # I'd like to refresh the board here #self.view.show_board() self.jumpAgain(board, state, return_code, updateGUI) board.printBoard() time.sleep(0.75) print "AI turn complete"
def draw(self,win): #TODO move to update function if self.state == die: print("Dead") if self.isDead is False: GameState.getInstance().reduce_life() self.isDead = True win.blit(playerDie, (int(self.worldToCamera()[0]), int(self.worldToCamera()[1]))) return else: self.isDead = False if self.particle.isClimb == True: self.changeState(climp) if moveSpeed == 0: self.changeState(idle) if self.direction == Right: if self.state == climp: win.blit(playerClimpRight, (int(self.worldToCamera()[0]), int(self.worldToCamera()[1]))) if self.state == shot: self.animationCount +=1 win.blit(playerFireRight, (int(self.worldToCamera()[0]), int(self.worldToCamera()[1]))) if self.animationCount >5: self.changeState(idle) if self.state==idle: win.blit(playerIdleRight, (int(self.worldToCamera()[0]),int(self.worldToCamera()[1]))) if self.state == running: if self.animationCount > 10: self.animationCount =0 self.animationCount +=1 win.blit(playerRunRight[self.animationCount//6], (int(self.worldToCamera()[0]), int(self.worldToCamera()[1]))) else: if self.state == climp: win.blit(playerClimpLeft, (int(self.worldToCamera()[0]), int(self.worldToCamera()[1]))) if moveSpeed == 0: self.changeState(idle) if self.state == shot: self.animationCount +=1 win.blit(playerFireLeft, (int(self.worldToCamera()[0]), int(self.worldToCamera()[1]))) if self.animationCount >5: self.changeState(idle) if self.state==idle: win.blit(playerIdleLeft, (int(self.worldToCamera()[0]),int(self.worldToCamera()[1]))) if self.state == running: if self.animationCount > 10: self.animationCount =0 self.animationCount +=1 win.blit(playerRunLeft[self.animationCount//6], (int(self.worldToCamera()[0]), int(self.worldToCamera()[1])))
def __init__(self): self._episode_ended = False self._state = GameState() self._action_spec = array_spec.BoundedArraySpec(shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(2, ), dtype=np.int32, minimum=0, maximum=28, name='observation')
def test_get_biggest_non_trump(self): game_state = GameState(1) game_state.trumps = Card.SUIT_HEARTS game_state.lead_card = Card(Card.SUIT_HEARTS, 10) card = self.player.get_biggest_non_trump(Card.SUIT_HEARTS, game_state.lead_card, self.player.hand) self.assertEqual(card.value, Card.KING) self.assertEqual(card._suit, Card.SUIT_SPADES) game_state = GameState(1) game_state.trumps = Card.SUIT_SPADES game_state.lead_card = Card(Card.SUIT_HEARTS, 10) card = self.player.get_biggest_non_trump(Card.SUIT_SPADES, game_state.lead_card, self.player.hand) self.assertEqual(card.value, Card.ACE) self.assertEqual(card._suit, Card.SUIT_HEARTS) result = self.player.get_biggest_non_trump(Card.SUIT_SPADES, game_state.lead_card, []) self.assertIsNone(result)
def test_print_summary_at_start(self): human = HumanPlayer('john') human._hand = [(3, 'L'), (5, 'H'), (9, '$')] state = GameState() state.human_player = human state.players = [human] with captured_output() as (out, err): print_summary(state) self.assertEqual('Game Summary\n' 'Your hand: 3L 5H 9$\n' 'Secret to play: [john: 1]', output(out))
class Game(): def __init__(self, numHumans, numComps): self.players = [] cardIds = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] r.shuffle(cardIds) self.startingDeck = [ Gaurd(cardIds[0]), Gaurd(cardIds[1]), Gaurd(cardIds[2]), Gaurd(cardIds[3]), Gaurd(cardIds[4]), Priest(cardIds[5]), Priest(cardIds[6]), Baron(cardIds[7]), Baron(cardIds[8]), Handmaid(cardIds[9]), Handmaid(cardIds[10]), Prince(cardIds[11]), Prince(cardIds[12]), King(cardIds[13]), Countess(cardIds[14]), Princess(cardIds[15])] # self.startingDeck = [Gaurd(0), Priest(1), Handmaid(2), Princess(3)] deck = self.startingDeck.copy() r.shuffle(deck) self.state = GameState(numHumans + numComps, deck) if numHumans + numComps > 4 or numHumans + numComps < 2: util.raiseException("must have 2 to 4 players") for i in range(numHumans): self.players.append(Player.createPlayer("human", i, self.state)) for i in range(numComps): self.players.append(Player.createPlayer("computer", i + numHumans, self.state)) self.state.setPlayers(self.players) def start(self): for i in range(self.state.numPlayers + 1): drawAction = DrawCard(i, setupAction=True) self.state = drawAction.execute(self.state) print(f"Set card {self.state.playerCards[self.state.numPlayers][0].id} aside") self.numTurns = 0 while self.state.state == "ongoing": if len(self.state.playerCards[self.state.playerTurn]) > 0: self.state.handMaided[self.state.playerTurn] = False drawAction = DrawCard(self.state.playerTurn) self.state = drawAction.execute(self.state) self.state = self.players[self.state.playerTurn].takeTurn(self.state) self.numTurns += 1 self.state.playerTurn = (self.state.playerTurn + 1) % self.state.numPlayers
def __init__(self): GameState.__init__(self) self.time = 0.0 self.playerSprites = pygame.sprite.Group() self.playerSprites.add(BorderPlayer( Globals.WIDTH, Globals.HEIGHT, 0, 0, Player.INDEX_DOWN)) self.playerSprites.add(BorderPlayer( Globals.WIDTH, Globals.HEIGHT, Globals.WIDTH, 0, Player.INDEX_LEFT)) self.playerSprites.add( BorderPlayer(Globals.WIDTH, Globals.HEIGHT, 0, Globals.HEIGHT, Player.INDEX_RIGHT)) self.playerSprites.add( BorderPlayer(Globals.WIDTH, Globals.HEIGHT, Globals.WIDTH, Globals.HEIGHT, Player.INDEX_UP))
def test_determine_murderer_when_its_another_player(self): state = GameState() john = HumanPlayer('john') jim = AIPlayer('jim') jack = AIPlayer('jack') state.current_player = john state.players = [john, jim, jack] state.extra_card = (8, 'L') john._hand = [(5, 'L'), (9, 'H'), (6, '$')] jim._hand = [(4, 'L'), (7, 'L'), (3, '$')] jack._hand = [(1, 'L'), (3, 'H'), (5, '$')] accusation_cards = [(5, 'L'), (7, '$')] # => murder card = 3H self.assertEqual(jack, determine_murderer(state, accusation_cards))
class Game: def __init__(self, screen, width, height): self.gameState = GameState(width, height) self.screen = screen self.agent = RandomAgent() def tick(self): action = self.agent.getAction(self.gameState) gameStateStr = str(self.gameState) reward = self.gameState.tick(action) print(action, reward)#, gameStateStr, self.gameState) def draw(self): self.gameState.draw(self.screen)
def __init__(self): GameState.__init__(self) self.size = Title.INIT_SIZE self.delta = 1 self.time_delta = 0 self.font = pygame.font.Font(None, self.size) self.title_surf = self.font.render(GAME_TITLE, True, TITLE_COLOR) self.title_rect = self.title_surf.get_rect() self.title_rect.centerx = Globals.SCREEN.get_rect().centerx self.title_rect.centery = Globals.SCREEN.get_rect().centery self.alt_surf = Title.ALT_FONT.render(Title.ALT_TITLE, True, Title.ALT_COLOR) self.alt_rect = self.alt_surf.get_rect() self.alt_rect.centerx = Globals.SCREEN.get_rect().centerx self.alt_rect.centery = self.title_rect.bottom + Title.MAX_DELTA + Title.ALT_PADDING
def __init__(self): ''' Constructor ''' self.game = GameState() self.numMoves = 0 pass
def __init__(self, inDepth): ''' Constructor ''' self.depth = inDepth self.game = GameState() self.numMoves = 0 pass
def __init__(self): GameState.__init__(self) self.size = HowToPlay.INIT_SIZE self.delta = 1 self.time_delta = 0 self.font = pygame.font.Font(None, self.size) self.title_surf = self.font.render(TITLE, True, TITLE_COLOR) self.title_rect = self.title_surf.get_rect() self.title_rect.centerx = Globals.SCREEN.get_rect().centerx self.title_rect.top = Globals.SCREEN.get_rect().top + TITLE_PADDING self.alt_surf = HowToPlay.ALT_FONT.render(HowToPlay.ALT_TITLE, True, HowToPlay.ALT_COLOR) self.alt_rect = self.alt_surf.get_rect() self.alt_rect.centerx = Globals.SCREEN.get_rect().centerx self.alt_rect.centery = self.title_rect.bottom + HowToPlay.MAX_DELTA + \ HowToPlay.ALT_PADDING
def __init__(self, inDepth): """ Constructor """ self.game = GameState() self.numMoves = 0 self.depth = inDepth pass
class GeneticBot: def __init__(self): sys.stderr = open('errors.txt', 'w') # This method is called in ants.py (can be removed) def do_setup(self, ants_instance): self.gs = GameState(ants_instance) # Keep track of important game state stuff # GENOME IS DEFINED HERE self.genome = [Genes.ExploreGene(), Genes.FoodGene()] # Called once a turn in ants.py, orders called from here def do_turn(self, ants_instance): sys.stderr.write('rem: ' + str(ants_instance.time_remaining()) + '\n') self.gs.updateAll(ants_instance) sys.stderr.write('rem (building af): ' + str(ants_instance.time_remaining()) + '\n') # Get the hill protectors to do their business # This is a necessary evil as it would be far messier to screw around with the Genes sys.stderr.write('rem (hill protection...): ' + str(ants_instance.time_remaining()) + '\n') self.gs.hp.protect(ants_instance, self.gs, self.genome) # does dispersion while staying near the hill afs = [] # see Utils.py -> AntForce # Build default ant force holders based on current ants for ant_loc in ants_instance.my_ants(): # Do not do dispersions for the normal ants if ant_loc in self.gs.hp.getProtectors(): continue row, col = ant_loc afs.append(utils.AntForce(row, col)) sys.stderr.write('rem (expressing genome...): ' + str(ants_instance.time_remaining()) + '\n') # Express the genes (not related to hill protectors) for gene in self.genome: sys.stderr.write('rem (expressing gene {0}): '.format(gene.id) + str(ants_instance.time_remaining()) + '\n') df = gene.express(ants_instance, self.gs, afs) utils.logdf(gene.id, df, self.gs.turn) sys.stderr.write('rem (applying forces): ' + str(ants_instance.time_remaining()) + '\n') # Resolve the forces to produce actions for af in afs: af.applyForces(ants_instance, self.gs) sys.stderr.write('rem: ' + str(ants_instance.time_remaining()) + '\n') sys.stderr.flush() self.gs.tickTurn()
def launch_game(): StoryGenerator.create_story() button_height = 50 battlefield = Battlefield(Battlefield.build("Battlefield/" + chosen_field + ".txt")) shop_state = ShopState(units, button_height, difficulty, gold, battlefield.get_enemy_spawn_count()) shopping_screen = pygame.display.set_mode((shop_state.window_width, shop_state.window_height)) shop_result = Shop.run(shopping_screen, shop_state) for unit in shop_result[0]: if unit not in units: units.append(unit) game_state = GameState(battlefield, button_height, units) battle_screen = pygame.display.set_mode((game_state.get_window_width(), game_state.get_window_height())) survivors = Battle.run(battle_screen, game_state) if is_game_over(survivors): return False, shop_result[1] return True, shop_result[1]
def __init__(self,playerList): self.players = playerList self.setPlanList() self.setTeams() #game is started by random player self.leaderIndex = self.getRandomPlayerIndex() self.nSuccess =0 self.nFail = 0 self.missionCounter=0 self.gameState = GameState(playerList)
def test_print_summary_with_extra_card_and_low_suit(self): human = HumanPlayer('john') human._hand = [(3, 'L'), (5, 'H'), (9, '$')] human.set_low_suit('H') state = GameState() state.human_player = human state.players = [human] state.extra_card = (5, 'L') with captured_output() as (out, err): self.assertFalse(print_summary(state)) self.assertEqual( 'Game Summary\n' 'Your hand: 3L 5H 9$\n' 'Extra card: 5L\n' 'Low Suits: [john: H]\n' 'Secret to play: [john: 1]', output(out))
def result(self,state,a): [loc,dir]=a if state.player==SELF_PLAYER: tmpPlayer=ENEMS_PLAYER else: tmpPlayer=SELF_PLAYER cMap=self.getClearMap(state,tmpPlayer) for (r,c) in loc: cMap[r][c]=tmpPlayer s=GameState(cMap, tmpPlayer) s.dirs=dir s.loc=loc self.saveSumDistance(s) listKill=self.preKill(s) for (r,c,p) in listKill: s.map[r][c]=LAND s.reward=(len(self.getAnts(s,SELF_PLAYER)),len(self.getAnts(s, ENEMS_PLAYER))) return s
def __init__(self, inDepth, zeroes): ''' Constructor ''' self.game = GameState() self.numMoves = 0 self.depth = inDepth self.zeroes = zeroes self.disagreements = 0 self.comparisons = 0 pass
def test_choose_an_opponent(self): try: old_raw_input = raw_input Interactive.raw_input = mock_raw_input('5', '2') player = HumanPlayer('joe') ai1 = AIPlayer('ai1') ai2 = AIPlayer('ai2') ai3 = AIPlayer('ai3') state = GameState() state.turn = 1 state.current_player = player state.players = [ai2, player, ai3, ai1] with captured_output() as (out, err): chosen_opponent = choose_an_opponent(state) self.assertEqual(ai3, chosen_opponent) finally: Interactive.raw_input = old_raw_input