File size: 4,888 Bytes
c78c7d0
 
 
 
648fc8c
 
 
 
 
 
 
 
c78c7d0
648fc8c
c78c7d0
 
2de04bc
648fc8c
 
2de04bc
 
c78c7d0
 
 
2de04bc
c78c7d0
648fc8c
 
 
 
 
c78c7d0
 
648fc8c
 
 
 
 
c78c7d0
 
648fc8c
 
 
 
 
 
 
 
 
 
c78c7d0
2de04bc
0060ecb
648fc8c
 
 
 
c78c7d0
 
 
 
648fc8c
 
 
 
1e4c6d3
c78c7d0
648fc8c
1e4c6d3
c78c7d0
1e4c6d3
c78c7d0
 
648fc8c
 
c78c7d0
 
648fc8c
c78c7d0
1e4c6d3
c78c7d0
1e4c6d3
c78c7d0
1e4c6d3
c78c7d0
648fc8c
 
 
 
49bca44
648fc8c
 
 
 
49bca44
 
648fc8c
 
 
49bca44
 
648fc8c
49bca44
 
648fc8c
5c2bd98
648fc8c
49bca44
5c2bd98
 
 
648fc8c
 
 
 
 
 
 
49bca44
648fc8c
 
 
c78c7d0
c63dd1f
c78c7d0
0060ecb
c78c7d0
 
80c047d
5c2bd98
 
49bca44
 
1e4c6d3
80c047d
 
c78c7d0
80c047d
2de04bc
80c047d
405528f
0060ecb
49bca44
5c2bd98
c78c7d0
80c047d
c78c7d0
 
 
 
49bca44
c78c7d0
 
 
 
 
 
 
 
 
 
49bca44
c78c7d0
 
 
 
 
648fc8c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import gradio as gr
import numpy as np
from game_logic import my_agent, Configuration, Observation

# Constants
EMPTY = 0
PLAYER = 1
AI = 2
SYMBOLS = {EMPTY: "⚪", PLAYER: "🔴", AI: "🟡"}
BOARD_SIZE = (6, 7)
WIN_LENGTH = 4

def initialize_game():
    return np.zeros(BOARD_SIZE, dtype=int)

def make_move(board, column, player):
    """Make a move on the board"""
    for row in range(BOARD_SIZE[0] - 1, -1, -1):
        if board[row][column] == EMPTY:
            board[row][column] = player
            return board
    return board

def check_winner(board):
    """Check if there's a winner"""
    # Horizontal
    for row in range(BOARD_SIZE[0]):
        for col in range(BOARD_SIZE[1] - 3):
            window = board[row, col:col + 4]
            if np.all(window == PLAYER) or np.all(window == AI):
                return True

    # Vertical
    for row in range(BOARD_SIZE[0] - 3):
        for col in range(BOARD_SIZE[1]):
            window = board[row:row + 4, col]
            if np.all(window == PLAYER) or np.all(window == AI):
                return True

    # Diagonals
    for row in range(BOARD_SIZE[0] - 3):
        for col in range(BOARD_SIZE[1] - 3):
            # Positive diagonal
            window = board[range(row, row + 4), range(col, col + 4)]
            if np.all(window == PLAYER) or np.all(window == AI):
                return True
            # Negative diagonal
            window = board[range(row, row + 4), range(col + 3, col - 1, -1)]
            if np.all(window == PLAYER) or np.all(window == AI):
                return True

    return False

def format_board(board):
    """Convert board to emoji representation"""
    return [[SYMBOLS[cell] for cell in row] for row in board]

def play_game(board, col, state):
    if state["game_over"]:
        return board, "Game is over! Click 'New Game' to play again."
    
    # Convert display format to game logic format
    board_array = np.array([[0 if cell == SYMBOLS[EMPTY] else 
                            1 if cell == SYMBOLS[PLAYER] else 2 
                            for cell in row] for row in board.values.tolist()])
    
    # Player move
    board_array = make_move(board_array, col, PLAYER)
    if check_winner(board_array):
        state["game_over"] = True
        return format_board(board_array), "You win! 🎉"
    
    # AI move
    config = Configuration({"rows": BOARD_SIZE[0], "columns": BOARD_SIZE[1], "inarow": WIN_LENGTH})
    obs = Observation({"board": board_array.flatten().tolist(), "mark": AI})
    
    ai_col = my_agent(obs, config)
    board_array = make_move(board_array, ai_col, AI)
    
    if check_winner(board_array):
        state["game_over"] = True
        return format_board(board_array), "AI wins! 🤖"
    
    return format_board(board_array), "Your turn!"

css = """
#board {
    max-width: 400px;
    margin: 20px auto;
    overflow: visible !important;
}
#board table {
    width: 100%;
    table-layout: fixed;
    border-collapse: separate;
    border-spacing: 4px;
}
#board td {
    text-align: center;
    font-size: 28px;
    padding: 8px;
    width: 14.28%;
    height: 40px;
    vertical-align: middle;
}
.button-container {
    max-width: 400px;
    margin: 0 auto 20px auto;
    padding: 10px;
}
.button-row {
    display: flex;
    justify-content: space-between;
    gap: 10px;
}
.button-row button {
    flex: 1;
    min-width: 40px;
    height: 40px;
}
"""

def create_ui():
    with gr.Blocks(css=css) as demo:
        gr.Markdown("# Play Connect Four Against AI")
        gr.Markdown(f"You are {SYMBOLS[PLAYER]}, AI is {SYMBOLS[AI]}")
        
        state = gr.State({"game_over": False})
        
        # Simplified button container
        with gr.Row(elem_classes="button-container"):
            with gr.Row(elem_classes="button-row"):
                buttons = [gr.Button(str(i), size="sm") for i in range(BOARD_SIZE[1])]
        
        board = gr.Dataframe(
            value=format_board(initialize_game()),
            interactive=False,
            show_label=False,
            headers=None,
            wrap=True,
            elem_id="board",
            row_count=BOARD_SIZE[0],
            col_count=BOARD_SIZE[1],
            max_rows=BOARD_SIZE[0]
        )
        
        message = gr.Textbox(value="Your turn!", label="Status")
        new_game = gr.Button("New Game")
        
        def reset_game():
            return format_board(initialize_game()), "Your turn!", {"game_over": False}
        
        new_game.click(
            reset_game,
            outputs=[board, message, state]
        )
        
        for i, button in enumerate(buttons):
            button.click(
                play_game,
                inputs=[board, gr.Number(value=i, visible=False), state],
                outputs=[board, message, state]
            )
    
    return demo

demo = create_ui()
demo.launch()