samedi 20 juillet 2019

How to make the blue rectangle not dissapear and move towards the red one?

I am trying to make a game and the blue rectangles are the incoming traffic, while the red one is the player. I generate the blue ones randomly but they don't remain on the "road" and dissapear after they appear. How to stop them from dissapearing?

The player should avoid incoming traffic (blue rectangles) but they dissapear immediatly after they are spawned.How do i stop that from happening?

import pygame
import random
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("F1")


x = 235
y = 0
width = 30
height = 50
speed = 0

a = 235
b = 0


class incoming(object):
    def __init__(self,a,b,width,height):
        self.a = a
        self.b = b
        self.width = width
        self.height = height


    def draw(self,win):
        pygame.draw.rect(win,(0,0,255),(a,b,width,height))


pygame.time.set_timer(pygame.USEREVENT+2, random.randrange(1500,3000))

run = True
while run:
    win.fill((0,255,0))

    road = pygame.draw.rect(win,[0,0,0],[175,y,120,-1000000])

    car = pygame.draw.rect(win,[255,0,0],[x,380,width,height])

    a = random.randrange(175,266,30)

    obstacles = []

    while speed < 10:
        speed = speed+0.1
        break

    y=y+speed

    b = 0
    if a < 210:
        b = b + speed + 2
    else:
        b = b + speed - 2


    dispSpeed = speed*32+speed*4/9
    myFont = pygame.font.SysFont("Times New Roman", 18)

    scris = myFont.render("Speed:", 1, [0,0,255])
    speedaf = myFont.render(str(int(dispSpeed)), 1, [0,0,255])

    win.blit(scris, (30,40))
    win.blit(speedaf, (30, 60))


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False


        if event.type == pygame.USEREVENT+2:
            obstacles.append(incoming(a,b,width,height))

    for obstacle in obstacles:            
        obstacle.draw(win)

    pygame.display.update()


    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        x=x-width

    if keys[pygame.K_DOWN]:
        while speed>0.2:
            speed = speed-0.25
            break

    if keys[pygame.K_RIGHT]:
        x=x+width

pygame.quit()

I expected the blue rectangles to move toward the red one after they are spawned at the top of the window, but they dissapear right after they are spawned.




Aucun commentaire:

Enregistrer un commentaire