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.

98 lines
3.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import pygame
# 初始化pygame只需一次
pygame.init()
screen = pygame.display.set_mode((600, 600)) # 修正括号
pygame.display.set_caption('五子棋-EduCoder')
space = 20
cell_size = 40
cell_num = 15
chess_arr = []
flag = 1
game_state = 1
def get_one_dire_num(lx, ly, dx, dy, m):
tx = lx
ty = ly
s = 0
while True:
tx += dx
ty += dy
if tx < 0 or tx >= cell_num or ty < 0 or ty >= cell_num or m[ty][tx] == 0:
return s
s += 1
def check_win(chess_arr, flag):
m = [[0] * cell_num for _ in range(cell_num)]
for x, y, c in chess_arr:
if c == flag:
m[y][x] = 1
lx = chess_arr[-1][0]
ly = chess_arr[-1][1]
dire_arr = [[(-1, 0), (1, 0)], [(0, -1), (0, 1)],
[(-1, -1), (1, 1)], [(-1, 1), (1, -1)]]
for dire1, dire2 in dire_arr:
dx, dy = dire1
num1 = get_one_dire_num(lx, ly, dx, dy, m)
dx, dy = dire2
num2 = get_one_dire_num(lx, ly, dx, dy, m)
if num1 + num2 + 1 >= 5:
return True
return False
# 主循环
while True:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if game_state == 1 and event.type == pygame.MOUSEBUTTONUP:
x, y = pygame.mouse.get_pos()
xi = int(round((x - space) / cell_size))
yi = int(round((y - space) / cell_size))
if 0 <= xi < cell_num and 0 <= yi < cell_num:
# 检查是否已有棋子(使用生成式提高效率)
if not any(c[0] == xi and c[1] == yi for c in chess_arr):
chess_arr.append((xi, yi, flag)) # 修正append语法
if check_win(chess_arr, flag):
game_state = 2 if flag == 1 else 3
else:
flag = 2 if flag == 1 else 1
# 绘制部分
screen.fill((204, 153, 102)) # 修正颜色参数
# 绘制棋盘
for i in range(cell_num):
start_pos = (space + i * cell_size, space)
end_pos = (space + i * cell_size, space + (cell_num - 1) * cell_size)
pygame.draw.line(screen, (200, 200, 200), start_pos, end_pos, 1)
start_pos = (space, space + i * cell_size)
end_pos = (space + (cell_num - 1) * cell_size, space + i * cell_size)
pygame.draw.line(screen, (200, 200, 200), start_pos, end_pos, 1)
# 绘制棋子
for x, y, c in chess_arr:
color = (30, 30, 30) if c == 1 else (225, 225, 225)
pos = (x * cell_size + space, y * cell_size + space)
pygame.draw.circle(screen, color, pos, 16, 0)
# 绘制星位(优化判断逻辑)
star_points = [(4, 4), (10, 10), (10, 4), (4, 10), (7, 7)]
for px, py in star_points:
if not any(c[0] == px and c[1] == py for c in chess_arr):
pos = (px * cell_size + space, py * cell_size + space)
pygame.draw.circle(screen, (0, 0, 0), pos, 2, 0)
# 显示胜利文字
if game_state != 1:
font = pygame.font.Font(None, 60)
text = font.render(f"{'Black' if game_state == 2 else 'White'} Win!",
True, (210, 210, 0))
screen.blit(text, (180, 280))
pygame.display.update()