Pygame - car racing - python

 # Car Racing based on keypress


import sys,pygame


pygame.init()

screen = pygame.display.set_mode((500, 500))

pygame.display.set_caption("Car Racing")

  

# Car starting co-ordinates and size

x = 200

y = 200


width = 20

height = 20

  

# Moving speed

step = 5


# Loading image

car = pygame.image.load("car.png")

car = pygame.transform.scale(car, (35, 65))

carrect = car.get_rect()


# Changing direction 

car_rotated_Left = pygame.transform.rotate(car, 90)

car_rotated_Right = pygame.transform.rotate(car, 270)

car_rotated_Up = pygame.transform.rotate(car, 0)

car_rotated_Down = pygame.transform.rotate(car, 180)


# infinite loop 

while 1:

pygame.time.delay(10)

angle = 0

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()


# Get the keys pressed 

keys = pygame.key.get_pressed()

      

    # Left arrow key - decrement in x axis

if keys[pygame.K_LEFT]and x>0:

x-=step

car=car_rotated_Left

    # Right arrow key - increment in x axis

if keys[pygame.K_RIGHT] and x<500-width:

x += step

car=car_rotated_Right

         

    # Up arrow key - decrement in y axis

if keys[pygame.K_UP] and y>0:

y -= step

car=car_rotated_Up

          

    # Down arrow key - increment in y axis

if keys[pygame.K_DOWN] and y<500-height:

y += step

car=car_rotated_Down


    # Set screen background and Place moving object on screen 

screen.fill((255, 255, 255))

screen.blit(car, (x, y))

pygame.display.flip()

      

    # Display movement

pygame.display.update() 

  

pygame.quit()


car.png 



Output Window





No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu