这是我的完整代码:
import pygame
pygame.init()
i = 0
x = 0
# Define the colors we will use in RGB format
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
# Set the height and width of the screen
size = [600, 300]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Test")
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
while not done:
clock.tick(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
screen.fill(WHITE)
for x in range(x, x+100, 10):
pygame.draw.rect(screen, BLACK, [x, 0, 10, 10], 1)
pygame.display.flip()
pygame.quit()
绘制了10个正方形,但它们在窗口中向右滚动,我不知道为什么。有什么办法可以阻止我吗?
谢谢。
我现在意识到这与矩形循环无关,但是无论如何我已经将其更改为建议的内容。
现在,您已经添加了更多代码,我看到了问题的出处,就像我怀疑的那样-您正在以不正确的方式进行静态转换,即您在中使用了x
(在主循环之外定义的)for x in range(x, x+100, 10):
。
如果print(x)
在for
-loop内添加一条语句,您将能够看到它x
变得越来越大……这非常适合向场景中添加动态效果,但是我的猜测是(基于您的问题)您想要在场景中添加10个静态矩形。
为此,您需要在x
每次while
循环的新迭代开始时重置您的代码:
while not done:
clock.tick(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
screen.fill(WHITE)
# Every single iteration of the while loop will first reset the x to its initial value
# You can make x be any value you want your set of rectangles to start from
x = 0
# Now start adding up to x's initial value
for x in range(x, x+100, 10):
pygame.draw.rect(screen, BLACK, [x, 0, 10, 10], 1)
pygame.display.flip()
您也可以省略的定义x
为外部变量for
循环,如果你不会使用它来改变x坐标在您的第一个矩形将启动并更换range(x, x+100, 10)
有range(CONST, CONST+100, 10)
哪里CONST
是给定值,如0,100,1000等。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句