写一个py程序,用来下五子棋
时间: 2024-05-15 14:14:38 浏览: 73
python实现五子棋游戏程序
4星 · 用户满意度95%
好的,我可以帮你写一个下五子棋的Python程序。你需要使用pygame库来绘制棋盘和棋子,以及检查胜负情况。下面是一个示例代码:
```
import pygame
# 初始化pygame
pygame.init()
# 设置棋盘大小
WIDTH = 600
HEIGHT = 600
# 设置颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
# 设置棋盘格子大小
GRID_SIZE = 60
# 设置网格数量
GRID_NUM = WIDTH // GRID_SIZE
# 创建窗口
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
# 设置窗口标题
pygame.display.set_caption('五子棋')
# 创建棋盘
board = [[0 for i in range(GRID_NUM)] for j in range(GRID_NUM)]
# 判断胜负的函数
def check_win(board, row, col, player):
# 数组越界或者该位置已经有棋子,返回False
if row < 0 or col < 0 or row >= GRID_NUM or col >= GRID_NUM or board[row][col] != player:
return False
# 判断横向五子是否连通
count = 0
for i in range(col - 4, col + 1):
if i < 0 or i + 4 >= GRID_NUM:
continue
if board[row][i:i+5] == [player]*5:
return True
# 判断纵向五子是否连通
count = 0
for i in range(row - 4, row + 1):
if i < 0 or i + 4 >= GRID_NUM:
continue
if [board[j][col] for j in range(i,i+5)] == [player]*5:
return True
# 判断左上到右下方向的五子是否连通
count = 0
for i in range(-4, 1):
x, y = row + i, col + i
if x < 0 or y < 0 or x + 4 >= GRID_NUM or y + 4 >= GRID_NUM:
continue
if [board[x+j][y+j] for j in range(5)] == [player]*5:
return True
# 判断右上到左下方向的五子是否连通
count = 0
for i in range(-4, 1):
x, y = row + i, col - i
if x < 0 or y < 0 or x + 4 >= GRID_NUM or y - 4 < 0:
continue
if [board[x+j][y-j] for j in range(5)] == [player]*5:
return True
# 没有连五子,返回False
return False
# 绘制棋盘
def draw_board():
# 绘制背景
WINDOW.fill(WHITE)
# 绘制网格线
for i in range(GRID_NUM):
pygame.draw.line(WINDOW, BLACK, (GRID_SIZE, GRID_SIZE * (i+1)), (WIDTH-GRID_SIZE, GRID_SIZE * (i+1)), 1)
pygame.draw.line(WINDOW, BLACK, (GRID_SIZE * (i+1), GRID_SIZE), (GRID_SIZE * (i+1), HEIGHT-GRID_SIZE), 1)
# 绘制棋子
def draw_chess(row, col, player):
# 计算棋子半径
radius = GRID_SIZE // 2 - 4
# 计算棋子位置
x = col * GRID_SIZE + GRID_SIZE
y = row * GRID_SIZE + GRID_SIZE
# 绘制黑色棋子
if player == 1:
pygame.draw.circle(WINDOW, BLACK, (x, y), radius)
# 绘制白色棋子
else:
pygame.draw.circle(WINDOW, WHITE, (x, y), radius)
# 更新屏幕显示
pygame.display.update()
# 下棋函数
def play(player):
# 等待鼠标点击
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] // GRID_SIZE
y = pos[1] // GRID_SIZE
# 判断该位置是否已经有棋子
if board[y][x] != 0:
continue
# 绘制棋子
draw_chess(y, x, player)
# 更新棋盘数据
board[y][x] = player
# 判断胜负
if check_win(board, y, x, player):
msg = '黑方' if player == 1 else '白方'
msg += '获胜!'
print(msg)
pygame.display.set_caption(msg)
# 等待一段时间,然后退出游戏
pygame.time.wait(3000)
pygame.quit()
exit()
# 切换下棋方
play(2 if player == 1 else 1)
# 开始游戏
draw_board()
pygame.display.update()
play(1)
```
以上代码实现了一个基本的五子棋游戏,你可以尝试运行它并和AI程序一起玩一局。
当然,也欢迎您自己扩展这个程序,添加更多功能,比如:AI对战、悔棋功能等等。
阅读全文