This is a basic clone of the classic arcade game "Asteroids," built using Python and the Pygame library. The objective is to navigate a spaceship and destroy incoming asteroids, which split into smaller pieces when hit.
Objective: Destroy all asteroids without getting hit by them.
Controls:
W: Move forward (in the direction the ship is facing)S: Move backwardA: Rotate leftD: Rotate rightSpacebar: Shoot bulletsX: Close the game window (or click the 'X' button)
Gameplay Mechanics:
- Asteroid Destruction: When an asteroid is hit by a bullet:
- Large asteroids split into two medium asteroids.
- Medium asteroids split into two small asteroids.
- Small asteroids are destroyed completely.
- Collision: If your spaceship collides with any asteroid (regardless of size), the game ends immediately.
Building this game provided hands-on experience with fundamental programming concepts and specific Pygame functionalities.
- Object-Oriented Programming (OOP):
- Classes & Objects: Designed
Player,Asteroid,Shot,CircleShape, andAsteroidFieldclasses to represent game entities and their behaviors. - Inheritance: Utilized inheritance extensively (e.g.,
Player,Asteroid,Shotinheriting fromCircleShape, which itself inherits frompygame.sprite.Sprite) to share common attributes and methods (likeposition,radius,update,draw). - Encapsulation: Grouped related data (attributes) and behavior (methods) within classes (e.g., player movement logic within the
Playerclass, asteroid splitting logic within theAsteroidclass).
- Classes & Objects: Designed
- Modules & Imports: Structured the project into multiple files (
main.py,constants.py,circleshape.py,player.py,asteroid.py,asteroidfield.py) and managed dependencies usingimportstatements. - Constants: Used a dedicated
constants.pyfile to store game configuration values, making the code more readable and easier to modify. - Data Structures:
- Lists: Used for managing collections of points (e.g.,
Player.triangle()method) and iterating over sprite groups. pygame.math.Vector2: Crucial for handling 2D positions, velocities, and directional vectors, enabling accurate movement and rotation calculations.
- Lists: Used for managing collections of points (e.g.,
- Control Flow: Applied
if/elsestatements for conditional logic,whileloops for the main game loop, andforloops for iterating through events and game objects. - Functions & Methods: Broke down complex tasks into smaller, manageable functions and class methods.
randomModule: Used extensively for generating random positions, velocities, and angles for asteroids and their split trajectories.
- Initialization & Setup:
pygame.init(): Initializing all Pygame modules.pygame.display.set_mode(): Creating the game window and display surface.pygame.display.flip(): Updating the entire screen to show new frames.
- Game Loop: The core
while running:loop structure that handles game logic, input, updates, and drawing in each frame. - Event Handling:
pygame.event.get(): Processing user inputs and system events (e.g., closing the window).pygame.QUIT: Handling the window close event for graceful exit.pygame.key.get_pressed(): Detecting currently pressed keys for continuous input (movement, shooting).
- Drawing Primitives:
screen.fill(): Clearing the screen with a background color each frame.pygame.draw.polygon(): Drawing the player's triangular ship.pygame.draw.circle(): Drawing asteroids and bullets as circles.
- Sprites & Sprite Groups:
pygame.sprite.Sprite: The base class for visible game objects, facilitating organization.pygame.sprite.Group: Efficiently managing collections of sprites for updates, drawing, and collision detection..add()/.kill(): Automatically adding sprites to groups on creation and removing them from all groups whenkill()is called..containers: A static sprite field used to automatically add new instances to specified groups.
- Time Management &
dt(Delta Time):pygame.time.Clock(): Creating a clock object to control the game's frame rate.clock.tick(FPS): Limiting the frames per second (e.g., 60 FPS) and returning the time elapsed since the last tick (in milliseconds).dt(Delta Time): Converting milliseconds to seconds (/ 1000.0) to make movement and rotation calculations frame-rate independent, ensuring consistent speed across different machines.
- Vector Math for Game Physics:
pygame.math.Vector2.rotate(): Rotating directional vectors for player movement and asteroid splitting.pygame.math.Vector2.distance_to(): Calculating the distance between two points for collision detection.
- Collision Detection: Implemented custom circle-to-circle collision detection logic based on distances and radii.
- Rate Limiting: Implemented a simple cooldown timer for player shooting using
dt.
-
Prerequisites:
- Python 3.x
- Pygame library (
pip install pygame) - (If on Windows Subsystem for Linux 2 / WSL2): An X server like VcXsrv (XLaunch) running on your Windows host.
-
Setup (for WSL2/Linux users):
- Ensure XLaunch is running on Windows with "Multiple windows," "Start no client," and "Disable access control" enabled.
- In your WSL2 terminal, ensure your
DISPLAYenvironment variable is correctly set. A common method is addingexport DISPLAY="$(grep -oP "(?<= nameserver ).+" /etc/resolv.conf):0"to your~/.bashrcfile.
-
Run the Game:
- Navigate to the game's directory in your terminal.
- Execute the
main.pyfile:python3 main.py
- Score System: Track and display the player's score.
- Lives & Game Over Screen: Implement multiple lives and a proper "Game Over" display.
- Level Progression: Increase asteroid density or speed over time.
- Sound Effects & Music: Add audio for shooting, explosions, and background music.
- Power-ups: Introduce temporary boosts for the player.
- Visual Enhancements: More detailed ship graphics, asteroid textures, particle effects for explosions.
- Hyperspace / Teleport: A classic Asteroids feature.
- Wrap-around Screen Edges: Make objects that go off one side appear on the other.