-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcar.py
More file actions
82 lines (59 loc) · 2.49 KB
/
Copy pathcar.py
File metadata and controls
82 lines (59 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import pygame
import os
import numpy as np
import math
CAR1 = pygame.image.load(os.path.join(os.getcwd(), "./images/car.png"))
CRASH = pygame.image.load(os.path.join(os.getcwd(), "./images/crash.png"))
# permet de réduire l'image unifomement plus tard
w1 = CAR1.get_width()
h1 = CAR1.get_height()
class Car(pygame.sprite.Sprite): #Utilisation de la classe "Sprite" du module "sprite". Car defined by extending Sprite
def __init__(self, x, y, car_image):
pygame.sprite.Sprite.__init__(self)
###### Car's image and mask ######
self.image = pygame.transform.scale(car_image, (w1 * 0.05, h1 * 0.05))
self.crash = pygame.transform.scale(CRASH, (w1 * 0.1, h1 * 0.1))
self.rect = self.image.get_rect(center=(x, y))
# Creating the mask of the car. Useful for collision detection
self.mask = pygame.mask.from_surface(self.image)
###### Car's properties ######
# Car's position vector
self.position = [x, y]
# Car's velocity
self.velocity = 0
# Car's angle
self.angle = 0
####### Car's methods - Car Physics #######
def move(self):
self.position[0] += self.velocity * math.cos(math.radians(self.angle))
self.position[1] -= self.velocity * math.sin(math.radians(self.angle))
def turn_left(self):
# If the car is moving forward, the angle increases by 5 degrees
if self.velocity >= 0:
self.angle += 2
# If the car is moving backward, the angle decreases by 5 degrees
else:
self.angle -= 2
def turn_right(self):
# Same here, but in the opposite direction
if self.velocity >= 0:
self.angle -= 2
else:
self.angle += 2
def accelerate(self):
self.velocity += 0.1
def decelerate(self):
self.velocity -= 0.1
def brake(self):
if self.velocity >= 0.2:
self.velocity -= 0.2
elif self.velocity <= -0.2:
self.velocity += 0.2
else:
self.velocity = 0
####### Car's methods - Updating the car's position and mask #######
def update(self):
self.move()
self.rect = self.image.get_rect(center=(self.position[0], self.position[1]))
self.mask = pygame.mask.from_surface(self.image)
#print("Position vector: ", self.position)