如何每三秒钟添加一个对象?

时间:2018-11-10 15:07:00

标签: python pygame

在当前版本的代码中,在主循环的每次迭代中添加下降的对象。我试图每三秒钟添加掉落的物体。我试图用time.sleep()来做,但是没有用,因为我失去了移动的能力。 当它不起作用时,我尝试在一些地方添加addObject()函数,但是很快我发现什么都不会改变。我怎样才能做到这一点?。这是我的代码:

import pygame,random,sys
from pygame.locals import *
pygame.init()
blue = (0,0,255)
white = (255,255,255)
red = (255,0,0)
Clock = pygame.time.Clock()
width = 300
height = 500
player = pygame.Rect(0,480,20,20)
windowSurface = pygame.display.set_mode((300,500),0 ,32)
moveLeft = False
moveRight = False
moveSpeed = 6
fallingObjects = []
fallingObjectsPositionX = []
fallingObjectsPositionY = []
x = 0   
def addObject(x):
    for i in range(x):
        if len(fallingObjects) < 10:
            fallingObjectsPositionX.append(random.randint(0,width - 20))
            fallingObjectsPositionY.append(0)
            fallingObjects.append((pygame.Rect(fallingObjectsPositionX[len(fallingObjectsPositionX) - 1],fallingObjectsPositionY[len(fallingObjectsPositionY) - 1],20,20))) 
addObject(1)
while x == 0:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT:
                moveLeft = False
                moveRight = True
        if event.type == KEYUP:
            if event.key == K_LEFT:
                moveLeft = False
            if event.key == K_RIGHT:
                moveRight = False
    windowSurface.fill(white)
    if moveLeft and player.left > 0:
        player.left -= moveSpeed
    if moveRight and player.right < width:
        player.right += moveSpeed
    pygame.draw.rect(windowSurface,blue,player)
    for i in fallingObjects[:]:
        if player.colliderect(i):
            x = 1
    for i in range(len(fallingObjects)):
        fallingObjectsPositionY[i] += 5
        fallingObjects[i] = pygame.Rect(fallingObjectsPositionX[i],fallingObjectsPositionY[i],20,20)
        pygame.draw.rect(windowSurface,red,fallingObjects[i])
    for i in range(len(fallingObjects)):
        if fallingObjectsPositionY[i] >= height:
            del fallingObjects[i]
            del fallingObjectsPositionX[i]
            del fallingObjectsPositionY[i]
            for i in range(5):
                addObject(1)
        if IndexError:
            break
    pygame.display.update()
    Clock.tick(40)

0 个答案:

没有答案