用Python语言写一个五子棋游戏
时间: 2024-03-06 21:20:36 浏览: 67
好的,以下是一个简单的五子棋游戏实现,使用Python语言和Pygame库:
```python
import pygame
# 初始化Pygame
pygame.init()
# 创建游戏屏幕
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("五子棋")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREY = (200, 200, 200)
# 定义棋盘格子大小和行列数
CELL_SIZE = 40
ROW_COUNT = 15
COLUMN_COUNT = 15
# 创建棋盘
board = [[0] * COLUMN_COUNT for _ in range(ROW_COUNT)]
# 定义当前玩家
current_player = 1
# 定义游戏结束标志
game_over = False
# 绘制棋盘
def draw_board():
for row in range(ROW_COUNT):
for column in range(COLUMN_COUNT):
pygame.draw.rect(screen, BLACK, (column * CELL_SIZE, row * CELL_SIZE, CELL_SIZE, CELL_SIZE), 1)
if board[row][column] == 1:
pygame.draw.circle(screen, BLACK, (column * CELL_SIZE + CELL_SIZE // 2, row * CELL_SIZE + CELL_SIZE // 2), CELL_SIZE // 2 - 2)
elif board[row][column] == 2:
pygame.draw.circle(screen, WHITE, (column * CELL_SIZE + CELL_SIZE // 2, row * CELL_SIZE + CELL_SIZE // 2), CELL_SIZE // 2 - 2)
# 判断游戏是否结束
def check_game_over():
global game_over
for row in range(ROW_COUNT):
for column in range(COLUMN_COUNT):
if board[row][column] == 0:
continue
if column <= COLUMN_COUNT - 5 and board[row][column] == board[row][column+1] == board[row][column+2] == board[row][column+3] == board[row][column+4]:
game_over = True
if row <= ROW_COUNT - 5 and board[row][column] == board[row+1][column] == board[row+2][column] == board[row+3][column] == board[row+4][column]:
game_over = True
if row <= ROW_COUNT - 5 and column <= COLUMN_COUNT - 5 and board[row][column] == board[row+1][column+1] == board[row+2][column+2] == board[row+3][column+3] == board[row+4][column+4]:
game_over = True
if row >= 4 and column <= COLUMN_COUNT - 5 and board[row][column] == board[row-1][column+1] == board[row-2][column+2] == board[row-3][column+3] == board[row-4][column+4]:
game_over = True
# 主循环
while True:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
x, y = pygame.mouse.get_pos()
row = y // CELL_SIZE
column = x // CELL_SIZE
if board[row][column] == 0:
board[row][column] = current_player
current_player = 3 - current_player
check_game_over()
# 绘制屏幕
screen.fill(GREY)
draw_board()
pygame.display.flip()
```
启动程序后,可以在游戏屏幕中点击棋盘格子,下棋子。每次点击后,程序会自动判断是否有玩家获胜,如果有,则结束游戏。
阅读全文