所以我正在编写一个pygame程序,其中矩形从屏幕顶部不断下降,玩家可以移动它们的矩形来捕捉它们。问题是,当我运行程序时,矩形不会自行落下。它们只会在您开始移动角色或进入某种形式的输入时掉落。当输入结束时,它们会停止下降。为什么会这样?我觉得它可能与我的FPS设置有关,但我之前没有发生过这个问题就完成了类似的程序。谁能告诉我发生了什么?
提前致谢
`import pygame, sys,random,time
from pygame.locals import*
pygame.init()
mainClock=pygame.time.Clock()
WINDOWWIDTH=400
WINDOWHEIGHT=400
windowSurface=pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT ),0,32)
pygame.display.set_caption('Input with Falling Food')
BLACK=(0,0,0)
GREEN=(0,255,0)
WHITE=(255,255,255)
MOVESPEED=20
FOODSIZEMAX=30
FOODSIZEMIN=10
FOODMOVESPEED=30
foodCounter=0
NEWFOOD=5
player=pygame.Rect(300,100,50,50)
foods=[]
for i in range(10):
FOODSIZE=random.randint(FOODSIZEMIN,FOODSIZEMAX)
foods.append(pygame.Rect(random.randint(0,WINDOWWIDTH-FOODSIZE),0,FOODSIZE,FOODSIZE))
moveLeft=False
moveRight=False
moveUp=False
moveDown=False
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_LEFT or event.key==ord('a'):
moveRight=False
moveLeft=True
if event.key==K_RIGHT or event.key==ord('d'):
moveLeft=False
moveRight=True
if event.key==K_UP or event.key==ord('w'):
moveDown=False
moveUp=True
if event.key==K_DOWN or event.key==ord('s'):
moveUp=False
moveDown=True
if event.type==KEYUP:
if event.key==K_ESCAPE:
pygame.quit()
sys.exit()
if event.key==K_LEFT or event.key==ord('a'):
moveLeft=False
if event.key==K_RIGHT or event.key==ord('d'):
moveRight=False
if event.key==K_UP or event.key==ord('w'):
moveUp=False
if event.key==K_DOWN or event.key==ord('s'):
moveDown=False
if event.key==ord('x'):
player.top=random.randint(0,WINDOWHEIGHT-player.height)
player.left=random.randint(0,WINDOWWIDTH-player.width)
if event.type==MOUSEBUTTONUP:
foods.append(pygame.Rect(event.pos[0],event.pos[1],FOODSIZE,FOODSIZE))
foodCounter+=1
if foodCounter>=NEWFOOD:
foodCounter=0
FOODSIZE=random.randint(FOODSIZEMIN,FOODSIZEMAX)
foods.append(pygame.Rect(random.randint(0,WINDOWWIDTH-FOODSIZE),0,FOODSIZE,FOODSIZE))
windowSurface.fill(BLACK)
if moveDown and player.bottom<WINDOWHEIGHT:
player.top+=MOVESPEED
if moveUp and player.top>0:
player.top-=MOVESPEED
if moveLeft and player.left>0:
player.left-=MOVESPEED
if moveRight and player.right<WINDOWWIDTH:
player.right+=MOVESPEED
pygame.draw.rect(windowSurface,WHITE,player)
for i in range(len(foods)):
foods[i].top+=FOODMOVESPEED
for food in foods[:]:
if player.colliderect(food):
foods.remove(food)
for food in foods[:]:
if food.top>=WINDOWHEIGHT:
foods.remove(food)
for i in range(len(foods)):
pygame.draw.rect(windowSurface,GREEN,foods[i])
pygame.display.update()
#mainClock.tick(40)
#time.sleep(0.02)
答案 0 :(得分:0)
您需要将主循环代码从for event in pygame.event.get():
循环中删除。
也就是说,每次时钟滴答时你想要运行的所有内容(不仅仅是当游戏收到输入事件时)都应该在那个循环之外,就在主while
循环中。
至少,为了让食物移动:
for i in range(len(foods)):
foods[i].top+=FOODMOVESPEED
需要被带走。