【问题标题】:My pygame program doesn't want to change y axis我的 pygame 程序不想改变 y 轴
【发布时间】:2021-12-07 20:27:10
【问题描述】:

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

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 个。 提前致谢!

【问题讨论】:

    标签: python pygame pygame2


    【解决方案1】:

    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))
    

    【讨论】:

    • 感谢优化代码:P
    • 我忘了哈哈
    • @kiciarozek 谢谢。不客气。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多