import pygame
import numpy as np
# 初始化游戏
pygame.init()
# 设置窗口大小
WIDTH, HEIGHT = 640, 640
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("五子棋")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
# 创建棋盘
board = np.zeros((15, 15), dtype=int)
# 定义棋子半径和边距
RADIUS = 20
MARGIN = 40
# 定义当前玩家和游戏状态
player = 1
game_over = False
# 画棋盘
def draw_board():
win.fill(WHITE)
for row in range(15):
for col in range(15):
pygame.draw.circle(win, BLACK, (MARGIN + col * 40, MARGIN + row * 40), RADIUS)
if board[row][col] == 1:
pygame.draw.circle(win, BLUE, (MARGIN + col * 40, MARGIN + row * 40), RADIUS)
# 落子
def place_piece(row, col, player):
board[row][col] = player
# 判断游戏是否结束
def check_game_over(row, col):
# 判断行
if sum(board[row, col:col+5]) == 5 * player or sum(board[row, col-4:col+1]) == 5 * player:
return True
# 判断列
if sum(board[row:row+5, col]) == 5 * player or sum(board[row-4:row+1, col]) == 5 * player:
return True
# 判断正对角线
if sum(board[i, j] for i, j in zip(range(row-4, row+1), range(col-4, col+1))) == 5 * player or sum(board[i, j] for i, j in zip(range(row, row+5), range(col, col+5))) == 5 * player:
return True
# 判断反对角线
if sum(board[i, j] for i, j in zip(range(row-4, row+1), range(col+4, col-1, -1))) == 5 * player or sum(board[i, j] for i, j in zip(range(row, row+5), range(col, col-5, -1))) == 5 * player:
return True
return False
# 游戏循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN and not game_over:
x, y = event.pos
col = (x - MARGIN) // 40
row = (y - MARGIN) // 40
if row >= 0 and row < 15 and col >= 0 and col < 15 and board[row][col] == 0:
place_piece(row, col, player)
if check_game_over(row, col):
game_over = True
print("Player {} wins!".format(player))
player = 2 if player == 1 else 1
draw_board()
pygame.display.update()
pygame.quit()
Python实现五子棋小游戏
最新推荐文章于 2024-11-13 17:26:18 发布