-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtictactoe.py
160 lines (136 loc) · 5.03 KB
/
tictactoe.py
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
"""A Tic-Tac-Toe Web Application
Uses bootstrap 5 to style the elements.
requirements:
reactpy
"""
from reactpy import component, html, hooks
from reactpy.backend.fastapi import configure, Options
from fastapi import FastAPI
BOOTSTRAP_CSS = html.link(
{
'rel': 'stylesheet',
'href': 'https://cdn.jsdelivr.net/npm/[email protected]/'
'dist/css/bootstrap.min.css',
'integrity': 'sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Y'
'z1ztcQTwFspd3yD65VohhpuuCOmLASjC',
'crossorigin': 'anonymous',
}
)
PAGE_TITLE = 'ReactPy-TicTactoe'
SQ_SIZE = '60px'
PC_CHAR = {'p1': 'W', 'p2': 'B'}
WIN_RESULT_PATTERN = [
[0, 1, 2], # hor
[3, 4, 5], # hor
[6, 7, 8], # hor
[0, 4, 8], # diag
[2, 4, 6], # anti-diag
[0, 3, 6], # ver
[1, 4, 7], # ver
[2, 5, 8], # ver
]
def reset_state(set_stm, set_board_status, board_status):
set_stm(True)
for i in range(len(board_status)):
set_board_status[i]('')
@component
def Tictactoe():
stm, set_stm = hooks.use_state(True) # side to move
board_status = [None] * 9 # a list from 9 squares
set_board_status = [None] * 9 # an array of 9 functions
for i in range(len(board_status)):
board_status[i], set_board_status[i] = hooks.use_state('')
def make_move(event):
btn_value = event['currentTarget']['value']
set_board_status[int(btn_value)](
PC_CHAR['p1'] if stm else PC_CHAR['p2']
)
set_stm(not stm)
def disable_buttons():
"""Disables button if game is over.
We call this function once we know that a game is over.
Board square button is disabled if its value is not an empty char.
The initial value of a square is '' and we just replace it with ' '
to disable the button.
"""
for i, v in enumerate(board_status):
if v == '':
set_board_status[i](' ')
@component
def CreateSquare(index):
"""Creates a button to represent a square."""
return html.button(
{
'style': {'width': SQ_SIZE, 'height': SQ_SIZE},
'class': 'btn shadow-none rounded-1 btn-warning \
border-secondary m-0 fw-bold fs-3 \
align-items-center justify-content-center',
'value': index,
'on_click': make_move,
'disabled': board_status[index],
},
board_status[index]
)
@component
def MakeBoardSquares(values: list):
"""Creates a row of board squares as buttons."""
return html.div(
{'class': 'd-flex flex-row'},
[CreateSquare(i) for i in values]
)
@component
def determine_winner():
result = None
for res in WIN_RESULT_PATTERN:
if all([board_status[v] == PC_CHAR['p1'] for v in res]):
result = PC_CHAR['p1']
break
if all([board_status[v] == PC_CHAR['p2'] for v in res]):
result = PC_CHAR['p2']
break
if result is not None:
disable_buttons()
return html.h5({'class': 'text-success'}, f'The winner is {result}.')
done = all([bs == PC_CHAR['p2'] or bs == PC_CHAR['p1']
for bs in board_status])
if done:
disable_buttons()
return html.h5({'class': 'text-secondary'}, 'The result is a draw.')
return html.h5({'class': 'text-muted'}, 'No winner yet.')
def new_game(event):
reset_state(set_stm, set_board_status, board_status)
return html.div(
BOOTSTRAP_CSS,
html.div(
html.div({'class': 'container justify-content-center mt-3 text-center'},
html.div(
html.h1({'class': 'text-dark'}, 'TicTacToe'),
html.h6({'class': 'text-primary'}, 'Built by ReactPy'),
html.p(),
html.div(
{'class': 'container d-flex justify-content-center'},
html.div(
{'class': 'd-flex flex-column justify-content-center'},
html.div(MakeBoardSquares([0, 1, 2])),
html.div(MakeBoardSquares([3, 4, 5])),
html.div(MakeBoardSquares([6, 7, 8])),
),
),
html.br(),
html.div({'class': 'container justify-content-center'},
determine_winner(),
html.p(),
html.button(
{
'class': 'btn btn-primary',
'on_click': new_game
},
'New game'
)
),
),
),
),
)
app = FastAPI()
configure(app, Tictactoe, options=Options(head=html.head(html.title(PAGE_TITLE))))