Pygame开发:调整代码后棋子(counter)无法在棋盘移动的问题
棋盘游戏棋子无法移动问题修复
问题原因
- 棋子未重绘:棋子绘制代码放在主循环外仅执行一次,后续位置更新后没有重新绘制,视觉上看不到移动效果。
- 语法拼写错误:代码存在多处笔误,比如
quare_size(应为square_size)、ow(应为row)、nd(应为and),导致绘制失败或逻辑异常。 - 初始位置不合理:
counter_pos初始值[-0.35, -0.52]让棋子处于棋盘外,即使移动也无法被看到。 - 主循环未更新显示:事件处理后未调用
pygame.display.update(),位置变更无法同步到屏幕。 - 棋盘绘制逻辑重复:两个
if/elif条件完全重复,同一方格被绘制两次,浪费资源。
修复后的完整代码
import pygame, sys import random from pygame.locals import * pygame.init() screen = pygame.display.set_mode((800, 800)) pygame.display.set_caption("board") grey = (224,224, 224) green = (204, 255, 204) blue = (204, 255, 255) purple = (204, 204, 255) white = (255, 255, 255) rows = 10 cols = 14 colors = [grey, green, blue, purple] def display_board(screen_width, screen_height, square_size, margin): # 创建棋盘Surface,一次性绘制固定颜色的棋盘 board_surface = pygame.Surface((screen_width, screen_height)) for row in range(rows): for col in range(cols): # 合并重复的边界判断条件 if row == 0 or row == rows-1 or col == 0 or col == cols-1: color = random.choice(colors) # 修正拼写错误:quare_size → square_size pygame.draw.rect(board_surface, color, (col * square_size + margin + 2 * col, row * square_size + margin + 2 * row, square_size, square_size)) # 初始化棋子到棋盘内的合理位置 counter_pos = [0, 0] direction = 'right' # 将绘制好的棋盘一次性显示到屏幕 screen.blit(board_surface, (0, 0)) # 初始绘制棋子 pygame.draw.rect(screen, white, (counter_pos[1] * square_size + margin + 2 * counter_pos[1], counter_pos[0] * square_size + margin + 2 * counter_pos[0], square_size, square_size)) pygame.display.update() # 主循环 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN: # 更新棋子位置 if direction == 'right': counter_pos[1] += 1 if counter_pos[1] >= cols - 1: direction = 'down' elif direction == 'down': counter_pos[0] += 1 if counter_pos[0] >= rows - 1: direction = 'left' elif direction == 'left': counter_pos[1] -= 1 if counter_pos[1] <= 0: direction = 'up' elif direction == 'up': counter_pos[0] -= 1 # 修正缩进错误 if counter_pos[0] <= 0: direction = 'right' # 每次移动后,先重绘棋盘覆盖旧棋子,再绘制新位置的棋子 screen.blit(board_surface, (0, 0)) pygame.draw.rect(screen, white, (counter_pos[1] * square_size + margin + 2 * counter_pos[1], counter_pos[0] * square_size + margin + 2 * counter_pos[0], square_size, square_size)) pygame.display.update() pygame.quit() sys.exit() display_board(800, 600, 50, 20)
关键修改说明
- 使用
board_surface预绘制棋盘,确保颜色固定且无需重复生成随机值 - 将棋子绘制逻辑移入主循环,每次位置更新后重新绘制
- 修正所有拼写与缩进错误
- 调整棋子初始位置到棋盘可见区域
- 每次移动后先通过blit棋盘覆盖旧棋子,再绘制新位置,避免残影
内容的提问来源于stack exchange,提问作者user20231298
相关产品推荐
相关产品推荐

