Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- from pygame.locals import *
- import os, math
- SCREEN_SIZE_X = 800
- SCREEN_SIZE_Y = 600
- SPEED = 2
- TURN_SPEED = 3
- RIGHT = 0
- LEFT = 1
- class Car():
- def __init__(self):
- self.sprite = pygame.image.load(os.path.join('img', 'car.png')).convert()
- self.rect = self.sprite.get_rect()
- self.rect.center = SCREEN_SIZE_X/2, SCREEN_SIZE_Y - self.rect.height * 2
- self.sprite.set_colorkey((255, 255, 255))
- self.angle = 0
- self.original = self.sprite
- def change_direction(self, direction):
- """
- Set the orientation of the car.
- """
- if direction == RIGHT:
- self.angle += TURN_SPEED
- elif direction == LEFT:
- self.angle -= TURN_SPEED
- def update(self):
- """
- Update the position of car regarding the current orientation and the SPEED value.
- """
- speedx = math.sin(self.angle * (math.pi/180)) * SPEED
- speedy = math.cos(self.angle * (math.pi/180)) * SPEED * -1
- #rotate the car
- a_rad = math.asin(speedx/SPEED)
- a_deg = math.degrees(a_rad)
- self.sprite = pygame.transform.rotate(self.original, a_deg * -1)
- self.rect = self.sprite.get_rect(center = self.rect.center)
- #move the car
- self.rect.center = self.rect.center[0] + speedx, self.rect.center[1] + speedy
- def draw(self, screen):
- """
- Draw the car on the screen.
- """
- screen.blit(self.sprite, self.rect.center)
- def main():
- pygame.init()
- screen = pygame.display.set_mode((SCREEN_SIZE_X, SCREEN_SIZE_Y), HWSURFACE|DOUBLEBUF)
- car = Car()
- clock = pygame.time.Clock()
- loop = True
- while loop:
- clock.tick(60)
- for event in pygame.event.get():
- if event.type == QUIT:
- loop = False
- if event.type == KEYDOWN:
- if event.key == K_ESCAPE:
- loop = False
- pygame.event.pump()
- key = pygame.key.get_pressed()
- #set the orientation of the car with the RIGHT and LEFT button
- if key[K_RIGHT]:
- car.change_direction(RIGHT)
- if key[K_LEFT]:
- car.change_direction(LEFT)
- car.update()
- screen.fill((255, 255, 255))
- car.draw(screen)
- pygame.display.flip()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement