SpaceGame Technical Documentation
SpaceGame is a 2D space simulation game featuring planets, stars, ships, and physics-based interactions including gravity and collisions. The game tries to obey the laws of relativity. For a spaceship flying through space the notion of an "absolute speed" shouldn't make any sense. And nowhere in the game should relativity be violated.
The files are:
- camera: does camera stuff
- contains Camera class, does camera stuff
- constants: most constants are where they are needed, but some are in this file
- enemy_ai: does more complicated enemy AI stuff
- contains MarkovAI class
- main: runs game, handles menu and game loop
- physics: has basic classes
- contains main classes, Pos, PosVel, Particle, Body, Disk
- profiler: does profiling stuff, not so important for docs
- projectiles:
- contains Bullet, Rocket, Missile Flare classes
- ship:
- contains ShipConfig, Ship, ShipInput, PlayerShip, EnemyConfig, BulletEnemy, RocketEnemy, MissileEnemy, MarkovEnemy classes
- universe: all the celestial bodies and bullet-planet, planet-planet etc. interactions are handled here
- contains Star, PlanetConfig, Planet, UniverseOptions, Universe classes
Core simulation module containing celestial bodies and physics.
Extends: Disk
- Purpose: Represents a stationary celestial body
- Key Properties:
- Position (x, y)
- Radius
- Color
Dataclass
- Purpose: Configuration settings for planet creation
- Attributes:
relative_pos: Initial position relative to reference pointrelative_vel: Initial velocity vectorradius: Size of the planet
Extends: Disk
- Purpose: Represents a movable planet affected by physics
- Key Properties:
- Position (x, y)
- Velocity vector
- Radius
- Mass (derived from radius)
Dataclass
- Purpose: Configuration for universe generation
- Notable Settings:
- Dimensions
- Physics constants
- Generation parameters
Core simulation class
- Purpose: Manages all game elements and their interactions
- Key Methods:
add_player(player): Adds a player ship to the universeadd_enemy(enemy): Adds an enemy ship to the universeadd_planet(planet): Adds a planet to the universe_nearby_planets(position, radius): Returns planets within specified radiusapply_gravity_to(object): Applies gravitational forces to an objectapply_gravity(): Applies gravity to all objects in the universeapply_bounce(): Handles collision physicscreate_particles_on_disk(disk, count): Creates particle effects on a diskcreate_particle_cloud(position, count): Creates a cloud of particlescollide_bullets(): Handles bullet collision detection and effectshandle_input(input_state): Processes user inputstep(dt): Advances simulation by time stepdraw_background(): Renders the backgrounddraw(): Renders all game objectsdraw_text(text, position): Renders text at positiondraw_grid(): Renders coordinate gridgenerate_planet(config): Creates a planet from configurationfrom_options(options): Factory method to create universe from options
Module for player and enemy ship functionality.
- Purpose: Configuration settings for ship creation
- Notable Attributes:
- Ship size
- Speed characteristics
- Weapon settings
- Visual properties
Extends: Disk
- Purpose: Base class for player and enemy vessels
- Key Properties:
- Position and velocity
- Health and shield status
- Weapon systems
- Key Methods:
thrust(direction, power): Move the shiprotate(angle): Change ship orientationfire_weapon(): Attack actiontake_damage(amount): Handle incoming damageupdate(dt): Update ship state
Module handling viewport and coordinate transformations.
Extends: Pos
- Purpose: Controls the view into the game world
- Key Properties:
_tracking: Object camera follows_zoom: Scale factor for rendering_surface: Pygame surface to draw on_surface_size: Dimensions of rendering area_surface_rect: Rectangle defining render boundaries
- Key Methods:
step(): Update camera position to follow tracked object_rectangle_intersects_surface(rect): Check if an area is visible_world_to_surface(pos): Convert world coordinates to screen coordinatesstart_drawing_new_frame(): Clear screen for new renderdraw_pixel(color, transparency, pos): Draw single pixel with alphadraw_circle(color, center, radius): Draw filled circledraw_polygon(color, points): Draw filled polygondraw_line(color, start, end, thickness): Draw line with widthdraw_hairline(color, start, end): Draw single-pixel width linedraw_text(text, pos, font, color): Render text
_get_enclosing_rect(points): Calculate bounding box for set of points
Entry point for the game with initialization and main loop.
- Purpose: Initialize and run the game
- Key Operations:
- Initialize Pygame systems
- Show menu and get game options
- Create universe with planets and players
- Set up cameras for each player
- Run main game loop processing input, physics, and rendering
- Handle game-over condition
- Clean up and exit
- Purpose: Display and handle the main menu
- Key Operations:
- Render menu title and options
- Handle keyboard navigation
- Toggle option values
- Return updated options when player presses Enter
Module implementing the core physics engine and base classes for physical objects.
- Purpose: Represents an object with a position in 2D space
- Key Properties:
__pos: Vector representing (x, y) position (private)
- Key Methods:
_shift(delta): Move position by a vectorpos_relative_to(other): Calculate position relative to another objectdistance_squared_to(other): Calculate squared distance (optimization)distance_to(other): Calculate distance to another position
Extends: Pos
- Purpose: Represents an object with both position and velocity
- Key Properties:
__vel: Velocity vector (private)
- Key Methods:
step(dt): Update position based on velocity and time step_add_vel(vel): Add to current velocityvel_relative_to(other): Calculate velocity relative to another object_new_origin_and_only_use_this_if_you_really_know_what_you_are_doing(): Static method to create origin point
Extends: PosVel
- Purpose: Visual effects for explosions, thrusters, etc.
- Key Properties:
_base_color: Particle color_lifetime: Remaining display time_max_lifetime: Total display time
- Key Methods:
step_and_survives(dt): Update and check if particle is still activedraw(camera): Render particle with fading transparency
Extends: PosVel
- Purpose: Represents a physical body with mass and forces
- Key Properties:
mass: Object's mass, affects gravitational interactions
- Key Methods:
add_impulse(impulse): Add instantaneous force effectapply_force(force, dt): Apply continuous force over timegravitational_force(other): Calculate gravitational pull from another bodydraw(camera): Abstract method implemented by subclasses
Extends: Body
- Purpose: Represents a circular object with collision properties
- Key Properties:
radius: Size of the disk__radius_squared: Cached square of radius for optimizationcolor: Display color
- Key Methods:
draw(camera): Render disk as circleintersects_disk(other): Detect collision with another diskbounce_disks(other): Handle collision physics between two disksbounce_off_of_disk(other): Specialized collision for static objects
- Pos: Base class for objects with position
- Camera: Manages viewport and rendering
- PosVel: Extends Pos with velocity
- Particle: Extends PosVel for visual effects
- Disk: Extends Body with circular shape and radius
- Bullet: What Ships shoot
- Flare: Slow moving Bullet with specific behavior
- Rocket: Type of Bullet with specific behavior
- Missile: Another type of Bullet with different behavior
- Star: Stationary celestial body
- Planet: Movable celestial body
- Ship: Base class for ships
- PlayerShip: Player-controlled ship
- BulletEnemy: AI-controlled ship
- RocketEnemy: Enemy ship that fires rockets
- MissileEnemy: Enemy ship that fires missiles
- MarkovEnemy: Advanced enemy AI using Markov chains
- Bullet: What Ships shoot
-
handle_inputgets called. This modifiesself.thrust_stateand callsincrement_rot_counters -
increment_rot_countersincrements self.turn_L/R and self.turn_back_L/R. -
stepcallsdo_rotation_for_player -
do_rotation_for_playerchecksself.turn_L/Randself.turn_back_L/Rand activatesself.rotation_stateaccordingly. -
steptwo classes up applies force based onself.rotation_stateandself.thrust_state.
-
One of the
_execute_...methods is called. This returns adesired_directionand athrust_state. -
_matchtransforms thedesired_directioninto arotation_stateusingcalculate_rotation. -
TODO: finish this.
- Universe here gravity, bounces, bullet interactions and more are handled
- Ship creates Bullet objects when firing
- Planet objects exert gravitational forces on Ship and other Planet objects