You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pygame开发国际象棋程序运行后持续黑屏的问题求助

国际象棋棋盘实现黑屏问题修复

问题分析

你的代码存在多处逻辑错误和结构问题,导致程序运行后黑屏,主要问题包括:

  • 类定义外部存在独立的while循环,直接阻断后续逻辑执行
  • ChessBoard类中多个方法未正确初始化依赖(如self.done、self.clock、self.screen)
  • 重复定义draw方法,逻辑冲突
  • 多个方法调用了未实现的函数(如get_square_color、get_image_name)
  • 棋子图片加载和引用逻辑错误
  • 未正确实例化棋盘类并启动主循环

修正后的完整代码

import pygame
import sys

# 配置参数
SQUARE_SIZE = 75  # 调整为适配600x600窗口(75*8=600)
BOARD_SIZE = SQUARE_SIZE * 8
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
LIGHT_BROWN = (255, 206, 158)
DARK_BROWN = (191, 128, 64)

pygame.init()
WINDOW_SIZE = (BOARD_SIZE, BOARD_SIZE)  # 窗口大小匹配棋盘尺寸
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("国际象棋棋盘")
clock = pygame.time.Clock()

# 初始棋子位置(修正空棋盘表示,统一用空字符串)
START_POSITION = [
    ["br", "bn", "bb", "bq", "bk", "bb", "bn", "br"],
    ["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
    ["", "", "", "", "", "", "", ""],
    ["", "", "", "", "", "", "", ""],
    ["", "", "", "", "", "", "", ""],
    ["", "", "", "", "", "", "", ""],
    ["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"],
    ["wr", "wn", "wb", "wq", "wk", "wb", "wn", "wr"]
]

class ChessPiece:
    def __init__(self, color, piece_type, image):
        self.color = color
        self.piece_type = piece_type
        self.image = image

    def __repr__(self):
        return f'{self.color}{self.piece_type}'

class ChessBoard:
    def __init__(self, screen):
        self.screen = screen
        self.board = START_POSITION
        self.move_history = []
        self.captured_pieces = {'w': [], 'b': []}
        self.white_to_move = True
        self.images = {}
        self.done = False
        self.load_images()

    def load_images(self):
        # 确保pieces文件夹存在,图片命名为wq.png、bk.png等
        try:
            for color in ['w', 'b']:
                for piece in ['p', 'r', 'n', 'b', 'q', 'k']:
                    img_path = f"pieces/{color}{piece}.png"
                    img = pygame.image.load(img_path)
                    # 缩放图片适配方块大小
                    self.images[color + piece] = pygame.transform.scale(img, (SQUARE_SIZE, SQUARE_SIZE))
        except pygame.error as e:
            print(f"加载图片失败: {e}")
            sys.exit()

    def get_piece(self, row, col):
        piece_code = self.board[row][col]
        if not piece_code:
            return None
        color = piece_code[0]
        piece_type = piece_code[1]
        return ChessPiece(color, piece_type, self.images[piece_code])

    def draw_board(self):
        # 绘制棋盘方块
        for row in range(8):
            for col in range(8):
                color = LIGHT_BROWN if (row + col) % 2 == 0 else DARK_BROWN
                pygame.draw.rect(self.screen, color, 
                                pygame.Rect(col * SQUARE_SIZE, row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
        # 绘制棋子
        for row in range(8):
            for col in range(8):
                piece_code = self.board[row][col]
                if piece_code:
                    img = self.images[piece_code]
                    self.screen.blit(img, pygame.Rect(col * SQUARE_SIZE, row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))

    def run(self):
        while not self.done:
            clock.tick(60)
            # 事件处理
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True

            # 绘制画面
            self.draw_board()
            pygame.display.flip()

        pygame.quit()
        sys.exit()

# 实例化棋盘并启动程序
if __name__ == "__main__":
    chess_board = ChessBoard(screen)
    chess_board.run()

关键修改说明

  • 结构梳理:移除类外部的无效循环,通过if __name__ == "__main__"启动程序
  • 参数适配:调整方块大小为75,让8x8棋盘刚好适配600x600窗口
  • 依赖初始化:在ChessBoard的__init__中初始化self.screen、self.done等必要属性
  • 图片处理:添加图片缩放逻辑,确保棋子适配方块大小,增加加载错误捕获
  • 简化逻辑:移除未实现的冗余方法(如吃子显示、走棋记录),先保证基础棋盘显示正常
  • 修复棋盘表示:将空棋盘位置统一改为空字符串,避免逻辑判断混乱

运行前准备

  • 创建pieces文件夹,放入下载的棋子图片,命名格式为wq.png(白后)、bk.png(黑王)等
  • 确保Python环境已安装pygame库(可通过pip install pygame安装)

内容的提问来源于stack exchange,提问作者ManuelSN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 02:19:58