Skip to main content
 首页 » 编程设计

python之pygame不会绘制矩形

2025年02月15日7lovecherry

我正在使用 python 2.7 制作一个简单的游戏,每当我尝试绘制一个矩形时,我都会得到:

Traceback (most recent call last): File "C:/Users/HP/Desktop/experiment.py", line 335, in (WIDTH ,HEIGHT)]) TypeError: invalid color argument

相关代码如下

BLACK = (0, 0, 0) 
grid = [] 
for row in range(10): 
    #add empty array 
    grid.append([]) 
    for column in range(11): 
        grid[row].append(BLACK) 
WIDTH = 30 
HEIGHT = 30 
MARGIN = 5 
#starting pygame 
pygame.init() 
 
#Setting window dimensions 
WINDOW_SIZE = [425,320] 
screen = pygame.display.set_mode(WINDOW_SIZE) 
stopped = False 
while not stopped: 
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            stopped = True 
#draw grid 
    for row in range(10): 
        for column in range(11): 
            Color = grid[row][column] 
            pygame.draw.rect(screen,Color, 
                             [((MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN), 
                              (WIDTH ,HEIGHT)]) 
    clock.tick(60) 
 
    pygame.display.flip() 
 
 
pygame.quit() 

如有任何帮助,我们将不胜感激!!提前致谢!

编辑:如果需要,这里是 pastebin 中的整个脚本 https://pastebin.com/jCXT0M4a

请原谅它的质量

请您参考如下方法:

在 for 循环中打印网格和 Color,您会看到网格的某些行包含元组列表,而不仅仅是元组。 refresh 函数导致问题,尤其是这些行:

row1 = [right_side[0],front[0],left_side[0],back[0]] 
row2 = [right_side[1],front[1],left_side[1],back[1]] 
row3 = [right_side[2],front[2],left_side[2],back[2]] 

在我看来,第 1-3 行应该是元组列表,但是您创建了元组列表的列表:

[[(0, 255, 0), (0, 255, 0), (0, 255, 0)], [(255, 0, 0), (255, 0, 0), (255, 0, 0)], [(255, 255, 0), (255, 255, 0), (255, 255, 0)], [(0, 0, 255), (0, 0, 255), (0, 0, 255)]] 

在 Python 3.5 及更高版本中,您可以使用最新的附加解包功能,这些功能允许您使用星号 * 运算符将列表解包为其他列表。

row1 = [*right_side[0], *front[0], *left_side[0], *back[0]] 

在其他版本中,您可以使用 these techniques 之一.