Certainly! Below is a complete Pygame program that features a player-controlled car and a ball, both with basic physics and collision detection. The car can be moved using the arrow keys, and both the car and the ball will respond to collisions with each other.
Prerequisites:
-
Pygame Installation
Ensure you have Pygame installed. You can install it using pip:
pip install pygame
-
Assets
items/car.png: Image representing the car.
items/ball.png: Image representing the ball.
Make sure these images are placed in an items folder relative to where you run the script.
Code Explanation
-
Classes:
-
GameObject: A base class for all game objects, handling image loading, position, velocity, and basic physics updates.
-
Car: Inherits from GameObject. Handles player input for movement (acceleration, deceleration, rotation).
-
Ball: Inherits from GameObject. Applies gravity and handles bouncing when hitting the ground.
-
Physics:
-
Car Physics: The car can accelerate forward/backward and rotate left/right. It has friction that slows it down over time when not accelerating.
-
Ball Physics: The ball is affected by gravity and will bounce upon hitting the ground or the car.
-
Collision Detection:
- The program checks for collisions between the car and the ball using Pygame's
Rect collision detection. Upon collision, it adjusts their velocities to simulate a basic bounce effect.
-
Game Loop:
- Handles events, updates game objects, checks collisions, and renders everything on the screen at 60 FPS.
Complete Code
import pygame
import sys
import math
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Car and Ball Physics Simulation")
# Clock for controlling frame rate
CLOCK = pygame.time.Clock()
FPS = 60
# Colors
WHITE = (255, 255, 255)
GROUND_COLOR = (50, 50, 50)
# Load images
try:
CAR_IMAGE = pygame.image.load('items/car.png').convert_alpha()
BALL_IMAGE = pygame.image.load('items/ball.png').convert_alpha()
except pygame.error as e:
print(f"Error loading images: {e}")
sys.exit()
# Constants
GRAVITY = 0.5
FRICTION = 0.98
GROUND_LEVEL = HEIGHT - 50 # Y position of the ground
# Helper function to rotate an image while keeping its center
def rotate_image(image, angle):
rotated_image = pygame.transform.rotate(image, angle)
rotated_rect = rotated_image.get_rect(center=image.get_rect().center)
return rotated_image, rotated_rect
class GameObject:
def __init__(self, image, x, y):
self.original_image = image
self.image = image
self.rect = self.image.get_rect(center=(x, y))
self.pos = pygame.math.Vector2(x, y)
self.vel = pygame.math.Vector2(0, 0)
self.acc = pygame.math.Vector2(0, 0)
self.angle = 0 # For rotation
def update(self):
# Update velocity and position
self.vel += self.acc
self.vel *= FRICTION
self.pos += self.vel
self.rect.center = self.pos
# Reset acceleration
self.acc = pygame.math.Vector2(0, 0)
def draw(self, surface):
surface.blit(self.image, self.rect.topleft)
class Car(GameObject):
def __init__(self, image, x, y):
super().__init__(image, x, y)
self.speed = 0
self.rotation_speed = 5 # Degrees per frame
def handle_keys(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
# Accelerate forward
self.acc += pygame.math.Vector2(math.cos(math.radians(self.angle)), math.sin(math.radians(self.angle))) * 0.2
if keys[pygame.K_DOWN]:
# Accelerate backward
self.acc -= pygame.math.Vector2(math.cos(math.radians(self.angle)), math.sin(math.radians(self.angle))) * 0.2
if keys[pygame.K_LEFT]:
# Rotate left
self.angle += self.rotation_speed
self.image, self.rect = rotate_image(self.original_image, -self.angle)
self.rect.center = self.pos
if keys[pygame.K_RIGHT]:
# Rotate right
self.angle -= self.rotation_speed
self.image, self.rect = rotate_image(self.original_image, -self.angle)
self.rect.center = self.pos
def update(self):
self.handle_keys()
super().update()
# Keep car within screen bounds
if self.pos.x < 0:
self.pos.x = 0
self.vel.x = 0
elif self.pos.x > WIDTH:
self.pos.x = WIDTH
self.vel.x = 0
if self.pos.y < 0:
self.pos.y = 0
self.vel.y = 0
elif self.pos.y > GROUND_LEVEL:
self.pos.y = GROUND_LEVEL
self.vel.y = 0
class Ball(GameObject):
def __init__(self, image, x, y):
super().__init__(image, x, y)
def update(self):
# Apply gravity
self.acc += pygame.math.Vector2(0, GRAVITY)
super().update()
# Check collision with ground
if self.pos.y >= GROUND_LEVEL - self.rect.height / 2:
self.pos.y = GROUND_LEVEL - self.rect.height / 2
self.vel.y *= -0.7 # Reverse velocity with damping
# Check collision with walls
if self.pos.x <= self.rect.width / 2:
self.pos.x = self.rect.width / 2
self.vel.x *= -0.7
elif self.pos.x >= WIDTH - self.rect.width / 2:
self.pos.x = WIDTH - self.rect.width / 2
self.vel.x *= -0.7
class Game:
def __init__(self):
self.car = Car(CAR_IMAGE, WIDTH / 2, GROUND_LEVEL)
self.ball = Ball(BALL_IMAGE, WIDTH / 2 + 100, GROUND_LEVEL - 100)
def check_collision(self):
if self.car.rect.colliderect(self.ball.rect):
# Simple collision response: reverse velocities
overlap_rect = self.car.rect.clip(self.ball.rect)
if overlap_rect.width < overlap_rect.height:
if self.car.rect.centerx < self.ball.rect.centerx:
self.ball.pos.x = self.car.rect.left - self.ball.rect.width / 2
else:
self.ball.pos.x = self.car.rect.right + self.ball.rect.width / 2
self.ball.vel.x *= -0.7
else:
if self.car.rect.centery < self.ball.rect.centery:
self.ball.pos.y = self.car.rect.top - self.ball.rect.height / 2
else:
self.ball.pos.y = self.car.rect.bottom + self.ball.rect.height / 2
self.ball.vel.y *= -0.7
def run(self):
running = True
while running:
CLOCK.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update game objects
self.car.update()
self.ball.update()
# Check collisions
self.check_collision()
# Draw everything
SCREEN.fill(WHITE)
# Draw ground
pygame.draw.rect(SCREEN, GROUND_COLOR, (0, GROUND_LEVEL, WIDTH, HEIGHT - GROUND_LEVEL))
# Draw objects
self.car.draw(SCREEN)
self.ball.draw(SCREEN)
# Update the display
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
game = Game()
game.run()
Detailed Breakdown
-
Initialization:
pygame.init()
WIDTH, HEIGHT = 800, 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Car and Ball Physics Simulation")
CLOCK = pygame.time.Clock()
FPS = 60
- Initializes Pygame, sets up the screen, and defines the frame rate.
-
Loading Images:
try:
CAR_IMAGE = pygame.image.load('items/car.png').convert_alpha()
BALL_IMAGE = pygame.image.load('items/ball.png').convert_alpha()
except pygame.error as e:
print(f"Error loading images: {e}")
sys.exit()
- Loads the car and ball images. If the images are not found, the program will print an error and exit.
-
GameObject Class:
class GameObject:
...
- A generic class for movable objects, handling position, velocity, acceleration, and drawing.
-
Car Class:
class Car(GameObject):
...
- Inherits from
GameObject.
- Handles user input for movement and rotation.
- Ensures the car stays within screen bounds.
-
Ball Class:
class Ball(GameObject):
...
- Inherits from
GameObject.
- Applies gravity to the ball.
- Handles bouncing off the ground and walls with damping (reducing velocity upon collision).
-
Collision Detection:
def check_collision(self):
if self.car.rect.colliderect(self.ball.rect):
...
- Checks for rectangle collision between the car and the ball.
- Responds by reversing the ball's velocity and adjusting its position to prevent sticking.
-
Game Loop:
def run(self):
while running:
...
- Handles event processing, updates game objects, checks for collisions, and renders everything each frame.
-
Running the Game:
if __name__ == "__main__":
game = Game()
game.run()
- Creates an instance of the class and starts the game loop.
Additional Notes
-
Physics Simplification:
The physics in this example are simplified for demonstration purposes. For more realistic physics, consider integrating a physics engine like Pymunk or Box2D.
-
Improving Collision Response:
The current collision response is basic. Depending on your game's requirements, you might want to implement more accurate physics, such as calculating the collision normal, applying forces based on mass, etc.
-
Enhancements:
- Add multiple balls or obstacles.
- Implement scoring or objectives.
- Improve graphics and animations.
- Add sound effects for collisions and movements.
-
Error Handling:
Ensure that the image files exist in the specified items directory. You can also add more robust error handling as needed.
Running the Code
-
Ensure you have the required images in the items folder:
your_project/
├── items/
│ ├── car.png
│ └── ball.png
└── your_script.py
-
Run the script:
python your_script.py
Use the arrow keys to control the car:
- Up Arrow: Accelerate forward.
- Down Arrow: Accelerate backward.
- Left Arrow: Rotate left.
- Right Arrow: Rotate right.
The ball will respond to gravity and collisions with the car and the ground.