-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpygame-tictactoe.py
More file actions
83 lines (67 loc) · 2.37 KB
/
Copy pathpygame-tictactoe.py
File metadata and controls
83 lines (67 loc) · 2.37 KB
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
import pygame
import sys
import COLORS
pygame.init()
width = 600
height = 600
weight = 1
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Tic Tac Toe')
table = [[None, None, None], [None, None, None], [None, None, None]]
cur_player = 'x'
font_size = 100
font = pygame.font.SysFont(None, font_size)
game_over = False
def draw_table():
screen.fill(COLORS.WHITE_1)
pygame.draw.line(screen, COLORS.BLACK_1, (width//3, 0), (width//3, height), weight)
pygame.draw.line(screen, COLORS.BLACK_1, (width//3*2, 0), (width//3*2, height), weight)
pygame.draw.line(screen, COLORS.BLACK_1, (0, height//3), (height, height//3), weight)
pygame.draw.line(screen, COLORS.BLACK_1, (0, height//3*2), (height, height//3*2), weight)
def draw_symbols():
for line in range(3):
for column in range(3):
if table[line][column] != None:
text = font.render(table[line][column], True, COLORS.BLUE_1)
screen.blit(text, (column * (width//3) + 80, line * (height//3) + 60))
def check_winner():
for line in range(3):
if table[line][0] != None and table[line][0] == table[line][1] == table[line][2]:
return table[line][0]
for col in range(3):
if table[0][col] != None and table[0][col] == table[1][col] == table[2][col]:
return table[0][col]
if table[0][0] != None and table[0][0] == table[1][1] == table[2][2]:
return table[0][0]
if table[0][2] != None and table[0][2] == table[1][1] == table[2][0]:
return table[0][2]
return None
def play(line, column):
global game_over, cur_player
if table[line][column] is None:
table[line][column] = cur_player
cur_player = 'o' if cur_player == 'x' else 'x'
winner = check_winner()
if winner != None:
print('Player', winner, 'wins!')
game_over = True
def handle_quit():
pygame.quit()
sys.exit()
def handle_mouse_click():
x, y = pygame.mouse.get_pos()
line = y // (height // 3)
column = x // (width // 3)
play(line, column)
def handle_events():
for event in pygame.event.get():
if event.type == pygame.QUIT:
handle_quit()
if event.type == pygame.MOUSEBUTTONDOWN:
handle_mouse_click()
while game_over != True:
draw_table()
draw_symbols()
handle_events()
pygame.display.update()
pygame.quit()