如何使用Pygame绘制左下角为黑的国际象棋棋盘,现有代码效果异常
存在的问题
- 坐标系适配错误:Pygame默认以左上角为坐标原点,Y轴向下递增。原代码的行遍历逻辑是从上到下计算颜色奇偶,完全没有考虑「左下角为黑色」的起始位置要求,最终生成的棋盘上下颠倒,起始格子位置不符合需求。
- 渲染顺序错误:事件循环中先执行了画面刷新
pygame.display.flip(),再执行棋盘绘制逻辑,会导致首帧显示异常,也可能引发画面闪烁问题。 - 颜色值不符合要求:原代码中定义的
white_color和black_color实际是米黄色和棕色,和需求里的黑白棋盘要求不符。 - 坐标计算存在精度隐患:使用普通除法计算方格边长可能得到浮点数,在绘制矩形时容易出现坐标偏移。
修改方法
只需要调整行的奇偶判断逻辑适配Pygame坐标系,修正渲染顺序、颜色值和计算逻辑即可,修改后的完整代码如下:
import pygame pygame.init() width = height = int(input('Let\'s draw a chessboard =) \nSpecify the window size from 100 to 1500 pixels (it will be in 1: 1 format): \n')) size = (width, height) screen = pygame.display.set_mode(size) rows = cols = int(input('Specify the desired number of squares, I will raise them to the square and build a chessboard: \n')) # 改用整数除法避免浮点数坐标问题 square_size = width // rows pygame.display.set_caption("The chess board") # 修正为纯黑白,需要保留原木质棋盘色可以改回原有数值 white_color = (255, 255, 255) black_color = (0, 0, 0) def draw_squares(screen): screen.fill(white_color) for row in range(rows): # 将从上到下的行索引转换为从下到上的索引,适配左下角为起点的要求 reverse_row = rows - 1 - row for col in range(cols): # 行列索引相加为偶数时绘制黑格,保证左下角(reverse_row=0, col=0)为黑色 if (reverse_row + col) % 2 == 0: pygame.draw.rect(screen, black_color, (col * square_size, row * square_size, square_size, square_size)) while True: # 优化事件处理逻辑,避免窗口无响应 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() # 先绘制再刷新画面,修正渲染顺序 draw_squares(screen) pygame.display.flip()
内容的提问来源于stack exchange,提问作者Anna Khishchenko
相关产品推荐
相关产品推荐

