请你用python编写一个围棋程序
时间: 2023-09-11 11:08:43 浏览: 72
下面是一个简单的围棋程序示例,使用 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_liberty(row, col):
if row > 0 and board[row - 1][col] == 0:
return True
if row < 7 and board[row + 1][col] == 0:
return True
if col > 0 and board[row][col - 1] == 0:
return True
if col < 7 and board[row][col + 1] == 0:
return True
return False
# 检查是否可以吃子
def check_capture(row, col, player):
if row > 0 and board[row - 1][col] == 3 - player and not check_liberty(row - 1, col):
return True
if row < 7 and board[row + 1][col] == 3 - player and not check_liberty(row + 1, col):
return True
if col > 0 and board[row][col - 1] == 3 - player and not check_liberty(row, col - 1):
return True
if col < 7 and board[row][col + 1] == 3 - player and not check_liberty(row, col + 1):
return True
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
if not check_liberty(row, col) and not check_capture(row, col, current_player):
board[row][col] = 0
continue
# 检查是否吃子
if check_capture(row, col, current_player):
if row > 0 and board[row - 1][col] == 3 - current_player and not check_liberty(row - 1, col):
board[row - 1][col] = 0
if row < 7 and board[row + 1][col] == 3 - current_player and not check_liberty(row + 1, col):
board[row + 1][col] = 0
if col > 0 and board[row][col - 1] == 3 - current_player and not check_liberty(row, col - 1):
board[row][col - 1] = 0
if col < 7 and board[row][col + 1] == 3 - current_player and not check_liberty(row, col + 1):
board[row][col + 1] = 0
# 下棋
draw_piece(row, col, current_player)
# 更新玩家
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 表示白子。程序还定义了几个函数来绘制棋盘和棋子,以及检查是否有气和可吃子。在主游戏循环中,程序等待玩家点击棋盘上的位置,并在点击时下棋,更新棋盘状态,并检查是否有气和可吃子。程序还支持两个人交替下棋。