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

pygame开发国际象棋:列表存储的Square矩形右键点击变色实现问题

修正方案

1. 先修改board.py的Square类,新增原始颜色存储,避免改红后无法还原

在Square类的pick_color方法中添加原始颜色存储逻辑,方便后续重置高亮时恢复原配色:

def pick_color(self, num_column, num_row):
    if abs(num_column - num_row) % 2 == 0:
        self.color = Square.GREENISH
    else:
        self.color = Square.WHITE
    # 新增:保存方块原始默认配色
    self.original_color = self.color

2. 修正main.py的渲染逻辑,每帧重绘棋盘

你原代码只在初始化棋盘时调用了一次draw_board,后续修改方块color属性后不会自动更新到屏幕上,需要把绘制逻辑放到主循环中逐帧刷新:

def start(self):
    board = Board(0, 0)
    while self.running:
        # 每帧先清屏,避免画面残留
        self.screen.fill(Game.SCREEN_COLOR)
        # 每帧重绘最新状态的棋盘
        board.draw_board(self.screen)
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                self.running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 右键点击用event.button==3判断更准确,避免长按重复触发
                if event.button == 3:
                    checker.check_boundaries(board.squares)
        pygame.display.update()

3. 优化game_logic/click_events.py的点击逻辑

支持右键点击高亮,自动重置之前的高亮方块,同时把颜色改为需求中的红色:

class Checker:
    def __init__(self):
        # 记录当前激活的高亮方块,方便后续重置
        self.active_square = None

    def check_boundaries(self, objects):
        mouse = pygame.mouse.get_pos()
        # 先重置上一个高亮的方块配色
        if self.active_square:
            self.active_square.color = self.active_square.original_color
            self.active_square.active = False
            self.active_square = None
        # 遍历查找当前点击的方块
        for square in objects:
            if square.rect.collidepoint(mouse):
                square.color = (255, 0, 0)
                square.active = True
                self.active_square = square
                # 找到匹配方块后直接终止遍历,优化性能
                break

如果需要支持多个方块同时高亮,删除重置上一个高亮方块的代码段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:39:02