In the current version of the code, falling objects are added at each iteration of the main loop. I was trying to add falling objects every three seconds. I was trying to do it with time.sleep() but it didn't worked because I lost the ability to move. When it did not work I tried to add the addObject () function in a few places, but soon I found out that nothing would change. How can I do this?. This is my code:
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)