Exemple #1
0
    def get_move(self, board, player):
        print cf.draw(board)
        print "\t".join(map(str, range(0, 7)))
        player_move = input('Next move (Enter 0-7): \n')

        assert player_move in range(0, 7)
        return player_move
Exemple #2
0
    def get_move(self, board, player):

        possible_moves = np.zeros(cf.NUM_COLUMNS)

        for i in range(0, cf.NUM_COLUMNS):

            if cf.can_play(board, i):
                features = get_features_from_turn(player,
                                                  cf.play(board, i, player))
                win_prob = self.get_probabilities(features)[0][0]
                possible_moves[i] = win_prob

        return self.get_best_move(possible_moves)
Exemple #3
0
def visualize(args):
    with open(args.file) as f:
        data = json.loads(f.read())

    for idx, turn in enumerate(data['turns']):
        print "Turn: {} {}".format(idx, turn['player'])
        print cf.draw(turn['board'])
        print "Move: {}->{}".format(turn['player'], turn['move'])
        if args.include_features:
            print ai.get_features_from_turn(turn['player'], turn['board'])
            print ai.get_target_from_turn(turn['player'], data['winner'])

        print '\n'

    print "Winner:", data['winner']
    print cf.draw(data['final'])
Exemple #4
0
 def newGame(self):
     self.p1 = 'Player 1'
     self.p2 = 'Player 2'
     columns = 7
     rows = 6
     self.gameState = ConnectFour.ConnectFour(columns=columns, rows=rows)
     self.game = ConnectFour.C4Game(self.gameState)
     self.canvas.delete(ALL)
     self.canvas.config(width=(self.elementSize) * self.gameState.size['c'],
                        height=(self.elementSize) *
                        self.gameState.size['r'])
     self.master.update()
     self.drawGrid()
     self.draw()
     self._updateCurrentPlayer()
     self.gameOn = True
Exemple #5
0
def play_game(red, yellow):
    """
    Runs a game of ConnectFour using the given models
    Returns a list of (board, next-mode) pairs winner:

    ([(player, board), (player, board), ...], winner)
    """

    turns = []

    board = cf.create_board()

    current_player = random.choice([cf.RED, cf.YELLOW])

    while True:

        # Pick the next player to go
        current_player = cf.YELLOW if current_player == cf.RED else cf.RED

        # Determine their play
        current_model = red if current_player == cf.RED else yellow
        move = current_model.get_move(board, current_player)

        # Save the board that this player faced
        turns.append({'player': current_player, 'board': board, 'move': move})

        # Update the board
        board = cf.play(board, move, current_player)

        # Check the results
        if cf.is_tie(board):
            return {'turns': turns, 'winner': None, 'final': board}

        elif cf.is_winner(board, cf.RED):
            return {'turns': turns, 'winner': cf.RED, 'final': board}

        elif cf.is_winner(board, cf.YELLOW):
            return {'turns': turns, 'winner': cf.YELLOW, 'final': board}

        else:
            pass
Exemple #6
0
    def __init__(self):
        super().__init__()
        self.iconbitmap(default='logo.ico')
        self.title("Connect Four v1.0")
        self._rows = 6
        self._cols = 7

        # create the top canvas for the game board
        canvas = tk.Canvas(self, bg="#0055FF")
        self.create_board(canvas)
        canvas.pack(fill=tk.BOTH, expand=True)

        # create the bottom frame for the game state
        frame = tk.Frame(self)
        self.text1 = tk.Label(
            frame,
            bd=1,
            text="Round 1",
            relief=tk.RAISED,
            bg="lightgrey",
            fg="black")
        self.text2 = tk.Label(
            frame,
            bd=1,
            text="Red's turn",
            relief=tk.RAISED,
            bg="lightgrey",
            fg="black")
        self.text3 = tk.Label(
            frame,
            bd=1,
            text="Undecided",
            relief=tk.RAISED,
            bg="lightgrey",
            fg="black")
        frame.columnconfigure(0, weight=1)
        frame.columnconfigure(1, weight=1)
        frame.columnconfigure(2, weight=1)
        self.text1.grid(row=1, column=0, sticky=tk.E + tk.W)
        self.text2.grid(row=1, column=1, sticky=tk.E + tk.W)
        self.text3.grid(row=1, column=2, sticky=tk.E + tk.W)
        frame.pack(side=tk.BOTTOM, fill=tk.X)

        # create new game
        self.game = ConnectFour.Game()
Exemple #7
0
def get_features_from_game(game_data):
    # The current player's disks ar 1
    # opponent player's disks are 0

    game_features = []
    game_targets = []
    for turn in game_data['turns']:
        # Get the board's state AFTER the player makes the move
        # The target is "Will this player win IF they make this move"
        board = turn['board']
        board_after_move = cf.play(board, turn['move'], turn['player'])

        features = ai.get_features_from_turn(turn['player'], board_after_move)
        target = ai.get_target_from_turn(turn['player'], game_data['winner'])
        game_features.append(features)
        game_targets.append(target)

    return game_features, game_targets
Exemple #8
0
    def _board_game_factory(self, choice):
        if choice == CONNECT_FOUR:
            game = ConnectFour.ConnectFour()
            self._game_manager = GameManager.GameManager(self._connection, game)
            display = ConnectFourDisplay.ConnectFourDisplay(self._game_manager, game)
            
        elif choice == OTHELLO:
            game = Othello.Othello()
            self._game_manager = GameManager.GameManager(self._connection, game)
            display = OthelloDisplay.OthelloDisplay(self._game_manager, game)
            
        elif choice == SNAKESLADDERS:
            game = SnakesLadders.SnakesLadders()
            self._game_manager = GameManager.GameManager(self._connection, game)
            display = SnakesLaddersDisplay.SnakesLaddersDisplay(self._game_manager, game)

        ############### DEBUG ######################
        else:
            game = Game.Game()
            self._game_manager = GameManager.GameManager(self._connection, game)
            display = GameDisplay.GameDisplay(self._game_manager, game)
        ############################################
            
        return (game, display)
Exemple #9
0
def main():
    pg.init()
    brd = c4.defineBoard()
    turn = 'X'
    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
                sys.exit()
        updateBoard(brd)
        pg.display.update()
        while True:
            col = int(input('Select a column to drop your piece: '))
            if c4.checkCol(brd, col):
                c4.dropPiece(brd, col, turn)
                break
        if c4.checkWinner(brd, turn):
            break
        turn = c4.changeTurn(turn)
Exemple #10
0
def play(args):

    if args.player_first:
        player = cf.RED
        red_model = ai.PlayerModel()
        yellow_model = ai.load_model(args.ai, greedy=True)
    else:
        player = cf.YELLOW
        yellow_model = ai.PlayerModel()
        red_model = ai.load_model(args.ai, greedy=True)

    board = cf.create_board()

    # Alternate between Red/Yellow

    current_player = cf.RED
    current_model = red_model

    while True:

        move = current_model.get_move(board, current_player)
        board = cf.play(board, move, current_player)

        if cf.is_winner(board, cf.RED):
            print cf.draw(board)
            print "RED ({}) WINS".format('PLAYER' if player ==
                                         cf.RED else 'COMPUTER')
            return
        elif cf.is_winner(board, cf.YELLOW):
            print cf.draw(board)
            print "YELLOW ({}) WINS".format('PLAYER' if player ==
                                            cf.YELLOW else 'COMPUTER')
            return
        elif cf.is_tie(board):
            print cf.draw(board)
            print "TIE GAME"
            return
        else:
            current_player = cf.YELLOW if current_player == cf.RED else cf.RED
            current_model = yellow_model if current_player == cf.YELLOW else red_model
Exemple #11
0
def main():

    connectFour = ConnectFour()

    connectFour.run()
Exemple #12
0
 def get_move(self, board, player):
     while True:
         to_play = random.randint(0, cf.NUM_COLUMNS - 1)
         if cf.can_play(board, to_play):
             return to_play
Exemple #13
0
 def solve_for_move(self, board):
     g = ConnectFour.Game(1, 2, self.timeout)
     return g.Solve(board)