«

一个五子棋游戏的HTML页面,没事的时候来玩玩,AI生成

Fate 发布于 阅读:155


一个五子棋游戏 ,使用Pygame库实现了五子棋游戏,包含画布、玩家轮流下棋、绘制棋子以及判断胜负的功能。背景颜色为浅灰色,棋盘颜色为米色。获胜信息会在屏幕中央显示。请确保在运行此代码之前安装了Pygame库,可以通过以下命令安装

pip install pygame

以下是完整代码


import pygame
import sys

# 初始化Pygame
pygame.init()

# 设置窗口大小
width, height = 400, 400
cell_size = width // 15
grid_size = 15

# 设置颜色
background_color = (240, 240, 240)
board_color = (243, 210, 181)
black_stone_color = (0, 0, 0)
white_stone_color = (255, 255, 255)

# 创建窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("五子棋游戏")

# 设置字体
font = pygame.font.Font(None, 36)

# 初始化棋盘
board = [[None] * grid_size for _ in range(grid_size)]
current_player = 'black'
game_ended = False

def draw_board():
    screen.fill(background_color)
    for i in range(grid_size):
        pygame.draw.line(screen, board_color, (i * cell_size, 0), (i * cell_size, height))
        pygame.draw.line(screen, board_color, (0, i * cell_size), (width, i * cell_size))

def draw_stone(x, y, color):
    pygame.draw.circle(screen, color, ((x + 0.5) * cell_size, (y + 0.5) * cell_size), cell_size // 2 - 5)

def check_win(x, y):
    directions = [(1, 0), (0, 1), (1, 1), (1, -1)]

    for dx, dy in directions:
        count = 1
        for i in range(1, 5):
            nx, ny = x + dx * i, y + dy * i
            if 0 <= nx < grid_size and 0 <= ny < grid_size and board[nx][ny] == current_player:
                count += 1
            else:
                break
        for i in range(1, 5):
            nx, ny = x - dx * i, y - dy * i
            if 0 <= nx < grid_size and 0 <= ny < grid_size and board[nx][ny] == current_player:
                count += 1
            else:
                break
        if count >= 5:
            return True
    return False

def main():
    global current_player, game_ended

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN and not game_ended:
                x, y = event.pos
                col = round(x / cell_size)
                row = round(y / cell_size)

                if board[col][row] is None:
                    board[col][row] = current_player
                    draw_stone(col, row, black_stone_color if current_player == 'black' else white_stone_color)

                    if check_win(col, row):
                        winner_message = f"{current_player} 获胜!"
                        text_surface = font.render(winner_message, True, (0, 0, 0))
                        screen.blit(text_surface, (width // 2 - text_surface.get_width() // 2, height // 2 - text_surface.get_height() // 2))
                        game_ended = True

                    current_player = 'white' if current_player == 'black' else 'black'

        draw_board()
        pygame.display.flip()

if __name__ == "__main__":
    main()

下面看看HTML效果

<!DOCTYPE html>

五子棋游戏
``` ```

推荐阅读: