我如何使我的随机颜色的正方形上升,然后又以上升的方式下降—在pygame中留下黑屏

问题描述 投票:1回答:1

到目前为止,这是我的代码。我不确定如何使它上升一次,然后以相同的方式使其下降一次,并使用户黑屏。我尝试使用代码执行此操作,但是最终将其翻转并从大到小。我想要的顺序从小到大,然后又从大到小-如果可以的话。

import pygame
import random

pygame.init()
red = (255,0,0)
black = (0,0,0)
screen_size = (700, 700)
screen = pygame.display.set_mode(screen_size)

for x in range(700, 0, -1):
    rand_colour = ((random.randint(0,255), random.randint(0,255), random.randint(0,255)))
    pygame.draw.rect(screen, rand_colour, (0, 0, x+1, x+1))
    pygame.draw.rect(screen, black, (0, 0, x, x))
    pygame.display.flip()
    pygame.event.get()

for x in range(700):
    pygame.draw.rect(screen,((random.randint(0,255),random.randint(0,255),random.randint(0,255))),(1*x,1*x,700,700))

for xy in range(700):
    pygame.draw.rect(screen,black,(700,700,-xy,-xy))
    pygame.display.flip()
    pygame.event.get()
    pygame.time.wait(1)    


pygame.quit()


python pygame
1个回答
0
投票

确定,因此游戏循环不是一个for循环,而是一个while循环,一直运行到用户希望退出(通常通过右上角的X)。 for循环后,您会在程序中注意到该窗口关闭,这就是解决方法。

让我们开始进行设置,这与您的程序相同

import pygame

pygame.init()

size = (500,500)
screen = pygame.display.set_mode(size)

red = (255,0,0)
black = (0,0,0)

running = True #this is true while the game is running

下一步是循环

while running: #loop while the game is running

    for event in pygame.event.get(): #get all events (eg. clicks, key presses, key ups, ETC)
        if event.type == pygame.QUIT: #if the user clicked the X button
            running = False #stop running the program

pygame.quit() #after the loop is finished, quit pygame

这将创建一个空白窗口,并在按下X按钮时将其关闭。

下一步是在屏幕上绘制

while running:
    screen.fill(black) #clear the screen

    pygame.draw.rect(screen,red,(100,100,100,100)) #draw a red rectangle at (100,100) that is 100x100

    pygame.display.update() #update the screen, exact same as using flip()

现在我们在屏幕上有一个红色矩形,让我们调整它的大小,我们将像在for循环中那样为该大小创建变量

size = 100
dsize = -1
...
while running:
    ...
    pygame.draw.rect(screen,red,(100,100,size,size)) #draw a red rectangle at (100,100) that is 100x100

    size += dsize  #change the size
    if size < 10 or size > 100: #if size is outside safe sizes
        dsize *= -1  #reverse the direction

它似乎有点快,但是不能小于1,所以可以使用pygame的时钟来限制fps

clock = pygame.time.Clock()
...
while running:
    ...
    clock.tick(60) #limit the fps to 60
    print(clock.get_fps()) #this is not necessary, but if you change 60 to 0, you can see how fast it was going 
© www.soinside.com 2019 - 2024. All rights reserved.