怎么用python实现五子棋游戏
时间: 2023-08-02 07:43:23 浏览: 47
五子棋游戏的实现可以分为两个部分,一个是游戏逻辑的实现,另一个是游戏界面的实现。下面是一个简单的五子棋游戏实现代码示例:
```python
import pygame
import sys
# 初始化 Pygame
pygame.init()
# 定义游戏面板大小
WIDTH = 640
HEIGHT = 640
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋盘格子大小
GRID_SIZE = int(WIDTH / BOARD_SIZE)
# 定义棋子半径大小
RADIUS = int(GRID_SIZE / 2 - 2)
# 定义棋盘线条颜色
LINE_COLOR = (0, 0, 0)
# 定义黑白棋子颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 创建屏幕对象
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 设置窗口标题
pygame.display.set_caption('五子棋')
# 创建棋盘
board = [[0 for x in range(BOARD_SIZE)] for y in range(BOARD_SIZE)]
# 定义当前下棋方
current_player = 1
# 绘制棋盘
def draw_board():
for x in range(BOARD_SIZE):
for y in range(BOARD_SIZE):
pygame.draw.rect(screen, (255, 206, 158), (x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE))
pygame.draw.circle(screen, LINE_COLOR, (x * GRID_SIZE + GRID_SIZE // 2, y * GRID_SIZE + GRID_SIZE // 2), RADIUS, 1)
# 绘制棋子
def draw_piece():
for x in range(BOARD_SIZE):
for y in range(BOARD_SIZE):
if board[x][y] == 1:
pygame.draw.circle(screen, BLACK, (x * GRID_SIZE + GRID_SIZE // 2, y * GRID_SIZE + GRID_SIZE // 2), RADIUS)
elif board[x][y] == 2:
pygame.draw.circle(screen, WHITE, (x * GRID_SIZE + GRID_SIZE // 2, y * GRID_SIZE + GRID_SIZE // 2), RADIUS)
# 判断是否胜利
def check_win(x, y, player):
# 判断横向是否连续五个棋子
count = 0
for i in range(BOARD_SIZE):
if board[i][y] == player:
count += 1
else:
count = 0
if count == 5:
return True
# 判断纵向是否连续五个棋子
count = 0
for j in range(BOARD_SIZE):
if board[x][j] == player:
count += 1
else:
count = 0
if count == 5:
return True
# 判断左上到右下是否连续五个棋子
count = 0
for i in range(BOARD_SIZE):
if x + i < BOARD_SIZE and y + i < BOARD_SIZE and board[x + i][y + i] == player:
count += 1
else:
count = 0
if count == 5:
return True
# 判断左下到右上是否连续五个棋子
count = 0
for i in range(BOARD_SIZE):
if x + i < BOARD_SIZE and y - i >= 0 and board[x + i][y - i] == player:
count += 1
else:
count = 0
if count == 5:
return True
return False
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
# 获取鼠标点击位置
x, y = event.pos[0] // GRID_SIZE, event.pos[1] // GRID_SIZE
# 判断该位置是否已经有棋子
if board[x][y] == 0:
# 在该位置下棋
board[x][y] = current_player
# 绘制棋子
draw_piece()
# 判断是否胜利
if check_win(x, y, current_player):
print('Player', current_player, 'wins!')
sys.exit()
# 切换下棋方
current_player = 3 - current_player
# 绘制棋盘
draw_board()
# 刷新屏幕
pygame.display.flip()
```
这个示例代码使用 Pygame 模块实现了一个简单的五子棋游戏,具体实现过程可以参考代码注释。该代码只是一个简单的示例,您可以根据自己的需求进行修改和扩展。