def test_Choice_ordering(): computer_choice = Choice(MoveCompleted(computer, Move(computer, 5)), Game()) human_choice = Choice(MoveCompleted(human, Move(human, 5)), Game()) noone_choice = Choice(MoveCompleted(noone, Move(computer, 5)), Game()) choices = [computer_choice, human_choice, noone_choice] assert max(choices) == computer_choice assert min(choices) == human_choice
def test_Minimax_game_almost_complete(): game = Game(list("OX_" "OXO" "XOX")) print("initial game = ", game) minimax = Minimax(game, computer) choice = minimax.get_best_choice() print(choice) assert choice.move == MoveCompleted(computer, Move(computer, 2))
def make_move(): # let the player move_dict = request.args move = f"{move_dict['from']}{move_dict['to']}" # handling for promotion if move_dict["piece"] == "p" and move[-1] in ["1", "8"]: move = move + "q" move = Move(move) done, res = game.step(move) print("move", move, game.board.fen()) if done: res = "You Win" if res == "win" else "Game Draw" response = make_response(jsonify(content=res)) return response # player makes the move and board gets updated move, _, _ = player.move(game) done, res = game.step(move) print("move", move, game.board.fen()) move = str(move) if done: res == "You Lose Sucker" if res == "win" else "Game Draw" response = make_response(jsonify(content=res)) return response # response response = make_response( jsonify(board_state=game.board.fen(), from_square=move[:2], to_square=move[2:])) response.headers["Access-Control-Allow-Origin"] = "*" return response
def test_Minimax_game_incomplete(): """ This case should be complete in one step by the machine """ game = Game(list("_O_" "OX_" "XOX")) # computer minimax = Minimax(game, computer) choice = minimax.get_best_choice() game.move(choice.move.move_initiated) # human h_move = game.get_available_slots()[0] game.move(Move(human, h_move)) assert game.is_done() assert game.determine_winner() == computer
def parsing(config, state_str): results = state_str.split("_", 2) if len(results) == 3: move, reward, snapshot = results elif len(results) == 2: move, reward = results snapshot = "" else: raise AssertionError("State str representation is wrong. Got: %s", results) move = Move.parsing(move) reward = float(reward) return TrainingState(config, snapshot=SnapshotView.parsing(config, snapshot), next_player_color=move.color, position=move.position, reward=reward)
def decide_turn(self, card, **info): player = None if self.current_card == 7 and card in [5, 6]: self.current_card, card = card, 7 if card in targetting_cards: available = [p for p in self.others if p not in info['immune']] if available: player = available[0] elif not available and card == 5: player = self guess = None if card == 1: guess = 2 return Move("im dum", card, player, guess)
def move(): LOGGER.info('hit!!') board = request.form['board'] print(board) game = Game(list(board)) print(game) choice = Minimax(game, computer).get_best_choice() pos = choice.move.move_initiated.pos if not game.is_done(): game.move(Move(computer, pos)) response = { "pos": pos, "end": game.is_done(), "winner": game.determine_winner().piece } return jsonify(response)
def test_outside_of_range_move(): b = Game() m = Move(computer, 10) with raises(InvalidMoveException): b.move(m)
def decide_turn(self, card, **info): preferred_order = [2, 4, 1, 3, 7, 5, 6, 8] my_card_pair = sorted([self.current_card, card], key=lambda c: preferred_order.index(c)) card = my_card_pair[0] discards = flatten([self.discards[p] for p in [self] + self.others]) def rotated(l): return l[1:] + [l[0]] def exclude(cards, excluded): while cards and excluded: to_exclude = excluded.pop() for _ in xrange(len(cards)): if cards[0] == to_exclude: cards = cards[1:] break cards = rotated(cards) return cards def possible_cards(player): if player in self.known: return [self.known[player]] other_hand_cards = my_card_pair + [ self.known[p] for p in self.known if p != player ] excluded_cards = other_hand_cards + discards return exclude(full_deck, excluded_cards) def possible_higher_cards(player): return [c for c in possible_cards(player) if c != 1] def avg(l): return float(sum(l)) / len(l) target = None guess = None if card in targetting_cards: available = [p for p in self.others if p not in info['immune']] if available: if card == 1: # get a list of [ [player1, card1, card2, ...], [player2, card1, card2, ...] ... ] options = [[p] + possible_higher_cards(p) for p in available] options = [o for o in options if len(o) >= 2 ] # eliminate known guard-only hands options.sort(key=lambda l: len(l)) if options: #print '---', options target, guess = options[0][0], options[0][1] else: #print '--- just a legal one' # if there are no possibilities, just make a legal move. # we probably shouldn't be playing a guard in the first place target, guess = available[0], 2 elif card == 2: target = ([ p for p in self.others if p not in self.known and p in available ] + available)[0] else: #print '---', [[p, possible_cards(p)] for p in available] options = [[p, avg(possible_cards(p))] for p in available] if card == 3: options.sort(key=lambda pair: pair[1]) else: options.sort(key=lambda pair: -pair[1]) #print '---', options target = options[0][0] elif not available and card == 5: target = self self.current_card = my_card_pair[1] return Move("Probably a reasonable move", card, target, guess)
def ajax(): req = request.get_json() move = Move.fromRequest(req) if move: game.move(move) return game.toJSON()
def show_board(screen): # screen.fill((255,255,255)) grid=Grid() ticgame=TicTacToe() running=True while running: for event in pygame.event.get(): pos=pygame.mouse.get_pos() position=[] if event.type==pygame.QUIT: running=False elif event.type==pygame.MOUSEBUTTONDOWN: if pos[0]<=220 and pos[1]<=220: position=[0,0] elif pos[0]>220 and pos[0]<=440 and pos[1]<=220: position=[0,1] elif pos[0]>440 and pos[0]<=700 and pos[1]<=220: position=[0,2] elif pos[0]<=200 and pos[1]<=440: position=[1,0] elif pos[0]>220 and pos[0]<=440 and pos[1]<=440: position=[1,1] elif pos[0]>440 and pos[0]<=700 and pos[1]<=440: position=[1,2] elif pos[0]<=220 and pos[1]>440: position=[2,0] elif pos[0]>220 and pos[0]<=440 and pos[1]>440: position=[2,1] elif pos[0]>440 and pos[0]<=700 and pos[1]>440: position=[2,2] font=pygame.font.Font(None,700//18) text=font.render('X',True,(255,0,0)) screen.blit(text,pos) pygame.display.update() comp_mov=Move(-1,-1) print(position) ticgame.board[position[0]][position[1]]='x' score=ticgame.utility() if score==1 or score==-1 or (score==0 and ticgame.movesLeft==False): gameoverscreen(screen,score) break ticgame.board[position[0]][position[1]]='_' comp_mov=ticgame.game_move(position) if comp_mov.x==0 and comp_mov.y==0: pos2=[110,110] elif comp_mov.x==0 and comp_mov.y==1: pos2=[330,110] elif comp_mov.x==0 and comp_mov.y==2: pos2=[620,110] elif comp_mov.x==1 and comp_mov.y==0: pos2=[110,330] elif comp_mov.x==1 and comp_mov.y==1: pos2=[330,330] elif comp_mov.x==1 and comp_mov.y==2: pos2=[620,330] elif comp_mov.x==2 and comp_mov.y==0: pos2=[110,620] elif comp_mov.x==2 and comp_mov.y==1: pos2=[330,620] elif comp_mov.x==2 and comp_mov.y==2: pos2=[620,620] font = pygame.font.Font(None,700//18) text = font.render('O', True, (0,0,0)) screen.blit(text,pos2) pygame.display.update() score=ticgame.utility() if score==1 or score==-1 or (score==0 and ticgame.movesLeft==False): gameoverscreen(screen,score) break screen.fill((255,255,255)) grid.draw(screen) pygame.display.flip()
from game import ONITAMA_CARDS, Game, Move, OnitamaAI, Point, visualize_bitboard, count_trailing_zeroes, CARD_INDEX, INDEX_CARD import numpy as np v = np.vectorize(visualize_bitboard) monkey = ONITAMA_CARDS["monkey"] frog = ONITAMA_CARDS["frog"] move = Move(Point(0, 0), Point(1, 1), "monkey") g = Game() h = Game.from_string("""rrRr.\n...r.\n.....\n..B..\nbb.bb""", red_cards=["frog", "mantis"], neutral_card="crane", blue_cards=["rabbit", "dragon"], starting_player=0)
def __str__(self): return "%s_%2.0f_%s" % (Move( self.position, self.next_player_color), self.reward, self.snapshot)
from game import Game, Move, Piece from ai import AI g = Game() g.make_move(Move(1, 1, Piece.X)) g.make_move(Move(0, 0, Piece.O)) g.make_move(Move(1, 0, Piece.X)) g.make_move(Move(0, 1, Piece.O)) g._board.print() next_move = g.find_best_move() g.make_move(next_move) g._board.print() next_move = g.find_best_move() g.make_move(next_move) g._board.print() next_move = g.find_best_move() g.make_move(next_move) g._board.print() # g.make_move(0, 0) # g.make_move(0, 2) # g.make_move(2, 0) # g.make_move(1, 0) # g.find_best_move()
def play_games(config, players, num_epochs=1, writer=None, avoid_dup=False): ebuf = ExperienceBuffer(config, writer=writer) dup_detector = DupDetector() i = 0 while i < num_epochs: if num_epochs != 1: print("========================") print("Epoch: %3d/%d" % (i+1, num_epochs)) b = config.new_board() b.draw() black_policy, white_policy = players(b) ebuf.start_epoch() dup_detector.new_game() aborted = False color = 'b' winner = None while True: policy = black_policy if color == 'b' else white_policy print("\n==> Inquiry", policy.name) position = policy.next_position() row, column = position.x, position.y print("Placed at (%2d, %2d)" % (row, column)) move = Move((row, column), color) ebuf.add_move(move) b.new_move(move) b.draw() found_dup = dup_detector.add_move(move) if avoid_dup and found_dup: aborted = True break winner = b.winner_after_last_move() if winner == None: pass elif winner == Color.NA: print("Tie") break else: print("Found winner: %s" % winner) break color = 'w' if color == 'b' else 'b' dup_detector.end_game() if not aborted: ebuf.end_epoch(winner) ebuf.report() i += 1 else: print("Abort the game as it is a dup.") ebuf.abort_epoch() ebuf.summary() return ebuf.history()