2

目标是在屏幕上制作具有随机绿色阴影的正方形,但 iy 轴不想改变

import pygame
from random import randint

#activate pygame
pygame.init()

#screen (x,y)
screen = pygame.display.set_mode([500, 500])

#bool - if game is running
running = True

tablica = [[randint(1,255) for i in range(10)] for i in range(10)]

print(tablica)

#while game is running
while running:

    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
        running = False

    #fill screen with (r,g,b)
    screen.fill((255,255,255))

    x = 0
    for i, e in enumerate(tablica):
        for j in e:
            pygame.draw.rect(screen,(j,j,0),(x,50*i,50,50))
            x += 50

    #update screen
    pygame.display.flip()

#turn off game
pygame.quit()

但不是在屏幕上绘制 100 个正方形,而是在同一个 x 轴上只画 10 个。提前致谢!

4

1 回答 1

2

x不断增长,并且永远不会放在第一行之后的行首。您必须在外循环中重置 x :

while running:
    # [...]

    # x = 0                                <-- DELETE

    for i, e in enumerate(tablica):
        x = 0                            # <-- INSERT
        for j in e:
            pygame.draw.rect(screen,(j,j,0),(x,50*i,50,50))
            x += 50

但是,您根本不需要该变量x

while running:
    # [...]

    for i, e in enumerate(tablica):
        for k, j in enumerate(e):
            pygame.draw.rect(screen,(j,j,0),(k*50,50*i,50,50))
于 2021-12-07T20:31:49.863 回答