Python实现五子棋小游戏

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()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值