Sure! Below is a basic implementation of a top-down car parking game using Pygame. The game features:
- Basic Graphics: Simple shapes and colors to represent the car, obstacles, and parking spot.
- Realistic Physics: The car moves with acceleration, deceleration, and rotation to simulate realistic driving.
- Controls: Arrow keys to accelerate/brake (
Up/Down) and steer (Left/Right).
- Levels: Three levels with increasing difficulty and obstacles.
- Parking Mechanism: You need to park perfectly into the designated spot and stay there for 3 seconds with a visible countdown.
To run the game, make sure you have Pygame installed:
pip install pygame
Here's the code:
import pygame
import math
import sys
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Car Parking Game")
# Colors
WHITE = (255, 255, 255)
GRAY = (120, 120, 120)
GREEN = (50, 168, 82)
RED = (220, 20, 60)
BLUE = (30, 144, 255)
BLACK = (0, 0, 0)
# Car settings
CAR_WIDTH, CAR_HEIGHT = 50, 30
# Load car image and scale
CAR_IMAGE = pygame.Surface((CAR_WIDTH, CAR_HEIGHT), pygame.SRCALPHA)
pygame.draw.polygon(
CAR_IMAGE,
RED,
[(0, CAR_HEIGHT), (CAR_WIDTH, CAR_HEIGHT), (CAR_WIDTH, 0), (0, 0)]
)
# Obstacles and parking spot for each level
LEVELS = [
{
"obstacles": [],
"parking_spot": pygame.Rect(700, 500, CAR_WIDTH + 10, CAR_HEIGHT + 10)
},
{
"obstacles": [pygame.Rect(400, 200, 50, 200)],
"parking_spot": pygame.Rect(50, 500, CAR_WIDTH + 10, CAR_HEIGHT + 10)
},
{
"obstacles": [pygame.Rect(300, 100, 200, 50), pygame.Rect(500, 300, 50, 200)],
"parking_spot": pygame.Rect(700, 50, CAR_WIDTH + 10, CAR_HEIGHT + 10)
}
]
# Car class
class Car:
def __init__(self, x, y):
self.x = x
self.y = y
self.angle = 0 # In degrees
self.speed = 0
self.max_speed = 5
self.acceleration = 0.1
self.brake_deceleration = 0.2
self.free_deceleration = 0.05
self.steer_angle = 5
self.length = CAR_WIDTH
self.width = CAR_HEIGHT
self.rect = pygame.Rect(self.x, self.y, self.length, self.width)
def update(self):
# Move forward/backward
rad = math.radians(self.angle)
self.x += -self.speed * math.sin(rad)
self.y += -self.speed * math.cos(rad)
# Update rect for collision detection
self.rect = pygame.Rect(self.x, self.y, self.length, self.width)
# Rotate the rectangle
self.rect.center = (self.x + self.length / 2, self.y + self.width / 2)
def draw(self, win):
rotated_image = pygame.transform.rotate(CAR_IMAGE, self.angle)
new_rect = rotated_image.get_rect(center=CAR_IMAGE.get_rect(topleft=(self.x, self.y)).center)
win.blit(rotated_image, new_rect.topleft)
# Main function
def main():
clock = pygame.time.Clock()
level = 0
run = True
while run and level < len(LEVELS):
car = Car(100, 500)
obstacles = LEVELS[level]["obstacles"]
parking_spot = LEVELS[level]["parking_spot"]
parked = False
parking_timer = 0 # In seconds
font = pygame.font.SysFont(None, 48)
while True:
dt = clock.tick(60) / 1000 # Frame delta time
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Key presses
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
car.angle += car.steer_angle
if keys[pygame.K_RIGHT]:
car.angle -= car.steer_angle
if keys[pygame.K_UP]:
if car.speed < car.max_speed:
car.speed += car.acceleration
elif keys[pygame.K_DOWN]:
if car.speed > -car.max_speed / 2:
car.speed -= car.brake_deceleration
else:
# Deceleration when no key is pressed
if car.speed > 0:
car.speed -= car.free_deceleration
elif car.speed < 0:
car.speed += car.free_deceleration
if abs(car.speed) < car.free_deceleration:
car.speed = 0
car.update()
# Collision detection with obstacles
collision = False
for obstacle in obstacles:
if car.rect.colliderect(obstacle):
collision = True
break
if collision:
# Reset level on collision
break
# Check if parked
if parking_spot.contains(car.rect) and abs(car.speed) < 0.1:
parking_timer += dt
else:
parking_timer = 0
if parking_timer >= 3:
# Level complete
level += 1
break
# Drawing
WIN.fill(GRAY)
# Draw parking spot
pygame.draw.rect(WIN, GREEN, parking_spot)
# Draw obstacles
for obstacle in obstacles:
pygame.draw.rect(WIN, BLUE, obstacle)
# Draw car
car.draw(WIN)
# Draw parking timer
if parking_timer > 0:
countdown_text = font.render(f"{int(3 - parking_timer) + 1}", True, BLACK)
WIN.blit(countdown_text, (WIDTH // 2 - countdown_text.get_width() // 2, 10))
# Update the display
pygame.display.flip()
# Game over or completed all levels
WIN.fill(WHITE)
font = pygame.font.SysFont(None, 72)
if level == len(LEVELS):
text = font.render("You Win!", True, GREEN)
else:
text = font.render("Game Over", True, RED)
WIN.blit(text, (WIDTH // 2 - text.get_width() // 2, HEIGHT // 2))
pygame.display.flip()
pygame.time.wait(3000)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Explanation:
- Car Movement: The car moves forward or backward based on acceleration and speed. Steering adjusts the angle, affecting the direction.
- Physics: We simulate acceleration, maximum speed, braking, and free deceleration when no key is pressed.
- Collision Detection: The car's rectangle is used to check for collisions with obstacles.
- Levels: Each level has predefined obstacles and a parking spot location.
- Parking Mechanism: If the car is within the parking spot and nearly stationary, a timer starts. You must stay parked for 3 seconds to complete the level.
- Controls:
- Up Arrow: Accelerate forward.
- Down Arrow: Brake/reverse.
- Left/Right Arrows: Steer left/right.
Additional Features:
- Visible Countdown: When you're parked, a countdown displays the remaining time to complete parking.
- Game Over Screen: If you collide with an obstacle, the level restarts. After completing all levels, a "You Win!" message is displayed.
Note: This is a basic implementation. You can enhance it by adding more levels, improving graphics with images, adding sounds, and refining physics for more realism.
To Run the Game:
- Save the code in a file named
car_parking_game.py.
- Ensure you have Pygame installed:
pip install pygame.
- Run the game:
python car_parking_game.py.
Enjoy the game, and feel free to customize it further!