用python实现五子棋
时间: 2023-07-12 14:17:05 浏览: 48
好的,下面是一个简单的五子棋实现,使用 Python 语言和 Pygame 库。
```python
import pygame
# 初始化 Pygame
pygame.init()
# 定义游戏窗口大小
WINDOW_SIZE = (600, 600)
# 定义棋盘格子大小和总格子数
CELL_SIZE = 40
GRID_SIZE = 15
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
# 创建游戏窗口
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("五子棋")
# 绘制棋盘
def draw_board():
for i in range(GRID_SIZE):
x = CELL_SIZE // 2 + i * CELL_SIZE
pygame.draw.line(screen, BLACK, (x, CELL_SIZE // 2), (x, WINDOW_SIZE[1] - CELL_SIZE // 2))
pygame.draw.line(screen, BLACK, (CELL_SIZE // 2, x), (WINDOW_SIZE[0] - CELL_SIZE // 2, x))
# 绘制棋子
def draw_piece(row, col, color):
x = CELL_SIZE // 2 + col * CELL_SIZE
y = CELL_SIZE // 2 + row * CELL_SIZE
pygame.draw.circle(screen, color, (x, y), CELL_SIZE // 2 - 2)
# 判断胜利条件
def check_win(board, row, col):
# 横向
count = 0
for j in range(GRID_SIZE):
if board[row][j] == board[row][col]:
count += 1
if count == 5:
return True
else:
count = 0
# 纵向
count = 0
for i in range(GRID_SIZE):
if board[i][col] == board[row][col]:
count += 1
if count == 5:
return True
else:
count = 0
# 左上到右下
count = 0
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == board[row][col]:
count += 1
if count == 5:
return True
else:
break
for i, j in zip(range(row + 1, GRID_SIZE), range(col + 1, GRID_SIZE)):
if board[i][j] == board[row][col]:
count += 1
if count == 5:
return True
else:
break
# 左下到右上
count = 0
for i, j in zip(range(row, GRID_SIZE), range(col, -1, -1)):
if board[i][j] == board[row][col]:
count += 1
if count == 5:
return True
else:
break
for i, j in zip(range(row - 1, -1, -1), range(col + 1, GRID_SIZE)):
if board[i][j] == board[row][col]:
count += 1
if count == 5:
return True
else:
break
return False
# 初始化棋盘
board = [[0 for j in range(GRID_SIZE)] for i in range(GRID_SIZE)]
turn = 1 # 1 表示黑方,2 表示白方
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if turn == 1:
color = BLACK
else:
color = WHITE
pos = pygame.mouse.get_pos()
row = pos[1] // CELL_SIZE
col = pos[0] // CELL_SIZE
if board[row][col] == 0:
draw_piece(row, col, color)
board[row][col] = turn
if check_win(board, row, col):
if turn == 1:
print("黑方胜利!")
else:
print("白方胜利!")
pygame.quit()
quit()
turn = 3 - turn # 切换下一方
# 绘制棋盘和棋子
screen.fill(WHITE)
draw_board()
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
if board[i][j] == 1:
draw_piece(i, j, BLACK)
elif board[i][j] == 2:
draw_piece(i, j, WHITE)
# 刷新屏幕
pygame.display.update()
```
该实现仅供参考,可能存在不足之处。如果您希望实现更完整和复杂的五子棋游戏,可以在此基础上进行扩展和改进。