You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
2.3 KiB

import pygame
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption('五子棋-EduCoder')
space = 20
cell_size = 40
cell_num = 15
board = [[0 for _ in range(cell_num)] for _ in range(cell_num)]
current_player = 1
def check_winner(board, x, y):
directions = [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)]
for dx, dy in directions:
count = 1
for i in range(-1, 2):
if i != 0:
nx, ny = x + i * dx, y + i * dy
while 0 <= nx < cell_num and 0 <= ny < cell_num and board[ny][nx] == current_player:
count += 1
nx, ny = nx + dx, ny + dy
if count >= 5:
return True
return False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
x = (pos[0] - space) // cell_size
y = (pos[1] - space) // cell_size
if 0 <= x < cell_num and 0 <= y < cell_num and board[y][x] == 0:
board[y][x] = current_player
if check_winner(board, x, y):
print(f"Player {current_player} wins!")
current_player = 2 if current_player == 1 else 1
screen.fill((204, 153, 102))
for x in range(0, cell_size * cell_num, cell_size):
pygame.draw.line(screen, (200, 200, 200), (x + space, 0 + space),
(x + space, cell_size * (cell_num - 1) + space), 1)
for y in range(0, cell_size * cell_num, cell_size):
pygame.draw.line(screen, (200, 200, 200), (0 + space, y + space),
(cell_size * (cell_num - 1) + space, y + space), 1)
for x in range(cell_num):
for y in range(cell_num):
if board[y][x] == 1:
pygame.draw.circle(screen, (0, 0, 0), ((x * cell_size) + space + cell_size // 2, (y * cell_size) + space + cell_size // 2), cell_size // 2 - 2)
elif board[y][x] == 2:
pygame.draw.circle(screen, (255, 255, 255), ((x * cell_size) + space + cell_size // 2, (y * cell_size) + space + cell_size // 2), cell_size // 2 - 2)
pygame.display.update()