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

Pygame棋盘开发:生成坐标元组列表并用于绘制方块

解决Pygame棋盘项目中坐标列表返回的问题

嘿,作为刚接触Python和Pygame的新手,能手动画出方块已经迈出超棒的第一步啦!咱们一步步搞定让coordinator()返回坐标元组列表的问题,这样就能在ChessBoard类里直接调用使用啦~

第一步:修改coordinator.py,让函数返回坐标列表

你现在的coordinator()应该是直接打印坐标,咱们把它改成把坐标收集到列表里再返回。举个适配8x8棋盘的具体例子:

# coordinator.py
def coordinator():
    white_squares = []
    # 定义每个方块的尺寸,根据你的项目需求调整数值
    square_size = 50
    # 遍历棋盘的行与列
    for row in range(8):
        for col in range(8):
            # 白方块判定条件:行号+列号为偶数(可根据你的视觉需求调整)
            if (row + col) % 2 == 0:
                # 计算方块左上角坐标:x对应列*尺寸,y对应行*尺寸
                x = col * square_size
                y = row * square_size
                white_squares.append((x, y))
    # 返回收集好的坐标元组列表
    return white_squares

如果之后要生成黑方块,你可以单独写一个get_black_squares()函数,或者让同一个函数返回白、黑两个坐标列表,比如:

def get_chess_coords():
    white_squares = []
    black_squares = []
    square_size = 50
    for row in range(8):
        for col in range(8):
            x = col * square_size
            y = row * square_size
            if (row + col) % 2 == 0:
                white_squares.append((x, y))
            else:
                black_squares.append((x, y))
    return white_squares, black_squares

第二步:在ChessBoard类中调用并使用坐标列表

现在在你的display.py里,就可以导入这个函数,把坐标列表存为类的属性,绘制时直接遍历即可:

# display.py
import pygame
from coordinator import coordinator  # 若用双列表版本则导入get_chess_coords

class ChessBoard:
    def __init__(self, screen):
        self.screen = screen
        self.square_size = 50
        # 获取白方块坐标列表
        self.white_squares = coordinator()
        # 如果用双列表版本:
        # self.white_squares, self.black_squares = get_chess_coords()
    
    def draw_board(self):
        # 绘制白方块
        for x, y in self.white_squares:
            pygame.draw.rect(self.screen, (255, 255, 255), (x, y, self.square_size, self.square_size))
        # 后续绘制黑方块的话:
        # for x, y in self.black_squares:
        #     pygame.draw.rect(self.screen, (0, 0, 0), (x, y, self.square_size, self.square_size))

几个需要注意的小细节

  • 坐标顺序:确保x对应列、y对应行,不然方块可能会画歪哦
  • 尺寸统一:保持coordinator.py和display.py里的square_size数值一致,避免坐标和绘制的方块不匹配
  • 测试验证:可以在ChessBoard初始化后打印self.white_squares,确认是不是你想要的坐标元组列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:12:59