用pygame做一个孔明棋
时间: 2023-06-06 11:06:50 浏览: 81
没有问题,我可以为您提供编写孔明棋的代码片段,您可以在此基础上进行开发。需要提醒的是,该代码仅为示例,可能会存在不足之处,需要您根据实际情况进行完善和改进。以下是代码片段:
```python
import pygame
# 初始化pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置屏幕尺寸
SIZE = (700, 700)
screen = pygame.display.set_mode(SIZE)
# 设置窗口标题
pygame.display.set_caption("孔明棋")
# 定义棋盘格子的大小
GRID_SIZE = 80
# 初始化棋盘状态
board = [[0] * 9 for i in range(9)]
board[0][0] = board[8][8] = 1
board[0][8] = board[8][0] = 2
# 画棋盘函数
def draw_board():
for i in range(9):
for j in range(9):
x = j * GRID_SIZE
y = i * GRID_SIZE
if (i + j) % 2 == 0:
pygame.draw.rect(screen, WHITE, [x, y, GRID_SIZE, GRID_SIZE])
else:
pygame.draw.rect(screen, BLACK, [x, y, GRID_SIZE, GRID_SIZE])
pygame.display.flip()
# 画棋子函数
def draw_piece(row, col, color):
x = col * GRID_SIZE
y = row * GRID_SIZE
pygame.draw.circle(screen, color, [x + GRID_SIZE//2, y + GRID_SIZE//2], GRID_SIZE//3)
pygame.display.flip()
# 判断位置是否合法
def is_legal_position(row, col):
if row < 0 or row > 8 or col < 0 or col > 8:
return False
if board[row][col] != 0:
return False
return True
# 落子函数
def place_piece(row, col, color):
if not is_legal_position(row, col):
return False
board[row][col] = color
draw_piece(row, col, color)
return True
# 判断是否有五子连珠
def is_win(color):
for i in range(9):
for j in range(9):
if board[i][j] == color:
if j+4 < 9 and board[i][j+1] == color and board[i][j+2] == color and board[i][j+3] == color and board[i][j+4] == color:
return True
if i+4 < 9 and board[i+1][j] == color and board[i+2][j] == color and board[i+3][j] == color and board[i+4][j] == color:
return True
if i+4 < 9 and j+4 < 9 and board[i+1][j+1] == color and board[i+2][j+2] == color and board[i+3][j+3] == color and board[i+4][j+4] == color:
return True
if i+4 < 9 and j-4 >= 0 and board[i+1][j-1] == color and board[i+2][j-2] == color and board[i+3][j-3] == color and board[i+4][j-4] == color:
return True
return False
# 定义当前玩家颜色和落子状态
current_color = 1
is_placed = False
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
row, col = y // GRID_SIZE, x // GRID_SIZE
is_placed = place_piece(row, col, current_color)
# 判断游戏是否结束
if is_win(current_color):
print("游戏结束,{}方获胜!".format(current_color))
break
if is_placed:
current_color = 3 - current_color # 切换玩家
is_placed = False
# 绘制棋盘和棋子
draw_board()
for i in range(9):
for j in range(9):
if board[i][j] != 0:
draw_piece(i, j, RED if board[i][j] == 1 else GREEN)
```