CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day01-15/code/Day10/renju.py
Views: 729
1
import pygame
2
3
EMPTY = 0
4
BLACK = 1
5
WHITE = 2
6
7
black_color = [0, 0, 0]
8
white_color = [255, 255, 255]
9
10
11
class RenjuBoard(object):
12
13
def __init__(self):
14
self._board = [[]] * 15
15
self.reset()
16
17
def reset(self):
18
for row in range(len(self._board)):
19
self._board[row] = [EMPTY] * 15
20
21
def move(self, row, col, is_black):
22
if self._board[row][col] == EMPTY:
23
self._board[row][col] = BLACK if is_black else WHITE
24
return True
25
return False
26
27
def draw(self, screen):
28
for index in range(1, 16):
29
pygame.draw.line(screen, black_color,
30
[40, 40 * index], [600, 40 * index], 1)
31
pygame.draw.line(screen, black_color,
32
[40 * index, 40], [40 * index, 600], 1)
33
pygame.draw.rect(screen, black_color, [36, 36, 568, 568], 4)
34
pygame.draw.circle(screen, black_color, [320, 320], 5, 0)
35
pygame.draw.circle(screen, black_color, [160, 160], 5, 0)
36
pygame.draw.circle(screen, black_color, [480, 480], 5, 0)
37
pygame.draw.circle(screen, black_color, [480, 160], 5, 0)
38
pygame.draw.circle(screen, black_color, [160, 480], 5, 0)
39
for row in range(len(self._board)):
40
for col in range(len(self._board[row])):
41
if self._board[row][col] != EMPTY:
42
ccolor = black_color \
43
if self._board[row][col] == BLACK else white_color
44
pos = [40 * (col + 1), 40 * (row + 1)]
45
pygame.draw.circle(screen, ccolor, pos, 20, 0)
46
47
48
def main():
49
board = RenjuBoard()
50
is_black = True
51
pygame.init()
52
pygame.display.set_caption('五子棋')
53
screen = pygame.display.set_mode([640, 640])
54
screen.fill([255, 255, 0])
55
board.draw(screen)
56
pygame.display.flip()
57
running = True
58
while running:
59
for event in pygame.event.get():
60
if event.type == pygame.QUIT:
61
running = False
62
elif event.type == pygame.KEYUP:
63
pass
64
elif event.type == pygame.MOUSEBUTTONDOWN\
65
and event.button == 1:
66
x, y = event.pos
67
row = round((y - 40) / 40)
68
col = round((x - 40) / 40)
69
if board.move(row, col, is_black):
70
is_black = not is_black
71
screen.fill([255, 255, 0])
72
board.draw(screen)
73
pygame.display.flip()
74
pygame.quit()
75
76
77
if __name__ == '__main__':
78
main()
79
80