用python 写一个五子棋 游戏
时间: 2023-07-18 16:34:05 浏览: 106
好的,我可以为您提供一个基于 Python 的简单五子棋游戏的代码示例,代码如下:
```python
# 导入必要的库
import numpy as np
import pygame
# 定义常量
BOARD_SIZE = 15
CELL_SIZE = 50
LINE_WIDTH = 2
WINDOW_SIZE = (BOARD_SIZE * CELL_SIZE, BOARD_SIZE * CELL_SIZE)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)
# 初始化游戏
pygame.init()
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("五子棋")
font = pygame.font.SysFont(None, 30)
# 创建棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
# 定义函数:绘制棋盘
def draw_board():
# 绘制背景
screen.fill(WHITE)
# 绘制线条
for i in range(BOARD_SIZE):
pygame.draw.line(screen, BLACK, (0, i * CELL_SIZE), (BOARD_SIZE * CELL_SIZE, i * CELL_SIZE), LINE_WIDTH)
pygame.draw.line(screen, BLACK, (i * CELL_SIZE, 0), (i * CELL_SIZE, BOARD_SIZE * CELL_SIZE), LINE_WIDTH)
# 绘制星位
for i in [3, 11]:
for j in [3, 11]:
pygame.draw.circle(screen, BLACK, (i * CELL_SIZE, j * CELL_SIZE), 5, 0)
# 定义函数:绘制棋子
def draw_piece(row, col, player):
pygame.draw.circle(screen, BLACK if player == 1 else WHITE, (col * CELL_SIZE, row * CELL_SIZE), CELL_SIZE // 2 - 5, 0)
# 定义函数:判断胜负
def check_win(row, col, player):
# 判断横向是否连成五子
count = 1
for c in range(col - 1, -1, -1):
if board[row][c] == player:
count += 1
else:
break
for c in range(col + 1, BOARD_SIZE):
if board[row][c] == player:
count += 1
else:
break
if count >= 5:
return True
# 判断纵向是否连成五子
count = 1
for r in range(row - 1, -1, -1):
if board[r][col] == player:
count += 1
else:
break
for r in range(row + 1, BOARD_SIZE):
if board[r][col] == player:
count += 1
else:
break
if count >= 5:
return True
# 判断左上到右下是否连成五子
count = 1
r, c = row - 1, col - 1
while r >= 0 and c >= 0:
if board[r][c] == player:
count += 1
else:
break
r -= 1
c -= 1
r, c = row + 1, col + 1
while r < BOARD_SIZE and c < BOARD_SIZE:
if board[r][c] == player:
count += 1
else:
break
r += 1
c += 1
if count >= 5:
return True
# 判断左下到右上是否连成五子
count = 1
r, c = row + 1, col - 1
while r < BOARD_SIZE and c >= 0:
if board[r][c] == player:
count += 1
else:
break
r += 1
c -= 1
r, c = row - 1, col + 1
while r >= 0 and c < BOARD_SIZE:
if board[r][c] == player:
count += 1
else:
break
r -= 1
c += 1
if count >= 5:
return True
# 未连成五子,返回False
return False
# 定义变量:当前落子方
current_player = 1
# 游戏循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# 获取鼠标点击位置
x, y = event.pos
row, col = y // CELL_SIZE, x // 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):
message = "黑方胜利" if current_player == 1 else "白方胜利"
text = font.render(message, True, BLACK)
screen.blit(text, (10, 10))
pygame.display.update()
running = False
# 切换落子方
current_player = 2 if current_player == 1 else 1
# 绘制棋盘
draw_board()
# 更新屏幕
pygame.display.update()
# 退出游戏
pygame.quit()
```
这个示例代码实现的是一个简单的双人五子棋游戏,您可以在此基础上进行修改和完善,例如实现人机对战、添加音效等等。
阅读全文