def simulateGame(player, opponent): # Returns fitness delta game = ConnectFour() illegal_moves = 0 random_moves_left = 3 while not game.isFinished(): # TODO track stats? if game.isOurTurn(): try: pickAndMakeMove(game, player) except IndexError: illegal_moves += 1 if illegal_moves >= NUMBER_ILLEGAL_MOVES_ALLOWED: # Penalise player return -NUMBER_TO_SAMPLE else: continue if game.isFinished(): break if random_moves_left > 0: pickAndMakeMove(game, agents.RandomAgent()) random_moves_left -= 1 else: try: pickAndMakeMove(game, opponent) except IndexError: pickAndMakeMove(game, agents.RandomAgent()) else: # Not our turn if random_moves_left > 0: pickAndMakeMove(game, agents.RandomAgent()) random_moves_left -= 1 else: try: pickAndMakeMove(game, opponent) except IndexError: pickAndMakeMove(game, agents.RandomAgent()) if game.isFinished(): break try: pickAndMakeMove(game, player) except IndexError: illegal_moves += 1 if illegal_moves >= NUMBER_ILLEGAL_MOVES_ALLOWED: # Penalise player return -NUMBER_TO_SAMPLE else: continue # Game is finished (or illegal move made) # TODO debug prints, or stats return game.score()
from game import ConnectFour import agents from utilities import pickMove, pickAndMakeMove game = ConnectFour() if len(sys.argv) >= 2: print("Using opponent from {}".format(sys.argv[1])) with open(sys.argv[1], 'rb') as output: opponent = pickle.load(output) else: print("Using random agent") opponent = agents.RandomAgent() while not game.isFinished(): if game.isOurTurn(): print(game) possibles = game.possibleMoves() column = input("Which column {}? ".format(possibles)) try: game.playMove(int(column)) except Exception as e: print("error occurred", e) else: try: pickAndMakeMove(game, opponent) except Exception: print("AI chose invalid move, trying random") pickAndMakeMove(game, agents.RandomAgent()) print(game)