请你用python编写一个五子棋程序
时间: 2023-09-11 15:08:42 浏览: 114
下面是一个简单的五子棋程序示例,使用 Python 语言编写。它使用 Pygame 库来构建 GUI 界面,支持两个人在同一计算机上进行游戏。
```python
import pygame
import sys
# 初始化 Pygame
pygame.init()
# 定义棋盘大小和单元格大小
BOARD_SIZE = (480, 480)
CELL_SIZE = 60
# 定义棋子颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 创建棋盘表格
board = [[0] * 8 for i in range(8)]
# 定义当前玩家和下一位玩家
current_player = 1
next_player = 2
# 定义 Pygame 窗口
screen = pygame.display.set_mode(BOARD_SIZE)
# 画棋盘
def draw_board():
for row in range(8):
for col in range(8):
x = col * CELL_SIZE
y = row * CELL_SIZE
pygame.draw.rect(screen, BLACK, (x, y, CELL_SIZE, CELL_SIZE), 2)
# 画棋子
def draw_piece(row, col, player):
x = col * CELL_SIZE + CELL_SIZE // 2
y = row * CELL_SIZE + CELL_SIZE // 2
if player == 1:
pygame.draw.circle(screen, BLACK, (x, y), CELL_SIZE // 2 - 4)
else:
pygame.draw.circle(screen, WHITE, (x, y), CELL_SIZE // 2 - 4)
# 检查是否有五子连珠
def check_win(row, col, player):
# 检查行
count = 0
for i in range(8):
if board[row][i] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 检查列
count = 0
for i in range(8):
if board[i][col] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 检查正斜线
count = 0
r = row
c = col
while r > 0 and c > 0:
r -= 1
c -= 1
while r < 8 and c < 8:
if board[r][c] == player:
count += 1
if count == 5:
return True
else:
count = 0
r += 1
c += 1
# 检查反斜线
count = 0
r = row
c = col
while r > 0 and c < 7:
r -= 1
c += 1
while r < 8 and c >= 0:
if board[r][c] == player:
count += 1
if count == 5:
return True
else:
count = 0
r += 1
c -= 1
# 没有连珠
return False
# 主游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
# 获取鼠标点击的位置
pos = pygame.mouse.get_pos()
row = pos[1] // CELL_SIZE
col = pos[0] // CELL_SIZE
# 检查该位置是否为空
if board[row][col] == 0:
# 下棋
board[row][col] = current_player
draw_piece(row, col, current_player)
# 检查是否胜利
if check_win(row, col, current_player):
print(f'Player {current_player} wins!')
# 更新玩家
temp = current_player
current_player = next_player
next_player = temp
# 绘制界面
draw_board()
for row in range(8):
for col in range(8):
if board[row][col] != 0:
draw_piece(row, col, board[row][col])
pygame.display.update()
```
这个程序使用 Pygame 库创建了一个窗口和一个棋盘。它使用一个二维数组 `board` 来表示棋盘状态,其中 0 表示空白,1 表示黑子,2 表示白子。程序还定义了几个函数来绘制棋盘和棋子,以及检查是否有五子连珠。在主游戏循环中,程序等待玩家点击棋盘上的位置,并在点击时下棋,更新棋盘状态,并检查是否有五子连珠。程序还支持两个人交替下棋。
阅读全文