python - 如何让我的随机颜色方块上升然后以与上升相同的方式下降 - 在pygame中留下黑屏
问题描述
到目前为止,这是我的代码。我不确定如何让它上升一次,然后让它以同样的方式下降一次,让用户黑屏。我尝试使用代码执行此操作,但是最终将其翻转并从大到小。我想要它的顺序是从小到大,然后再从大到小——如果这有意义的话。
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()
解决方案
好的,所以游戏循环不是有几个 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
推荐阅读
- java - java:将字符串转换为希腊字符
- python - Python Flask:单击通过单击另一个按钮呈现的按钮
- javascript - 单击按钮时触发键盘事件
- hibernate - 使用 Hibernate 创建表
- python-3.x - 在networkx中按顺序获取源的祖先
- java - 如何获取在使用 Selenium 路由到另一个 url 之前临时出现的重定向 url?
- angular - 如何从angular4中的表单中删除formGroup?
- asp.net - 如何在 asp.net 中将 Fileupload 绑定到 Image 控件
- android - 如何从本地sqlite糖数据库android中检索数据
- html - 如何以红色和绿色显示 Unicode 字符“记录的黑色圆圈”