70 lines
2.1 KiB
Python
70 lines
2.1 KiB
Python
"""Moon orbital simulation demo.
|
||
|
||
This module defines :class:`Moon` which subclasses :class:`game.Game` and
|
||
uses :func:`compute.rot_2D` and :func:`compute.matmul` to animate a moon
|
||
orbiting the Earth.
|
||
|
||
The original repository contained a fully functional example, but the
|
||
``moon.py`` file was overwritten by another module during a previous
|
||
edit. The following implementation restores the expected behaviour.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import pygame
|
||
|
||
from compute import rot_2D, matmul
|
||
from game import Game
|
||
|
||
|
||
EARTH_RADIUS = 30
|
||
MOON_RADIUS = 10
|
||
BLACK = (0, 0, 0)
|
||
WHITE = (255, 255, 255)
|
||
BLUE = (0, 0, 255)
|
||
|
||
|
||
class Moon(Game):
|
||
"""Demonstrates a moon orbiting the Earth using matrix rotation."""
|
||
|
||
def __init__(self, title: str = "Moon", fps: int = 60, size: Tuple[int, int] = (640, 400)) -> None:
|
||
super().__init__(title, fps, size)
|
||
# Earth centre – centre of the window
|
||
self.center: Tuple[int, int] = (size[0] // 2, size[1] // 2)
|
||
# Fixed orbit offset from the centre
|
||
self.offset: Tuple[float, float] = (100.0, 0.0)
|
||
# Angular speed (radians per frame)
|
||
self.delta_theta: float = 0.01
|
||
self.theta: float = 0.0
|
||
self.rot_moon: list[list[float]] = rot_2D(self.theta)
|
||
|
||
def update_game(self) -> bool:
|
||
# Advance the angle and recompute the rotation matrix
|
||
self.theta += self.delta_theta
|
||
self.rot_moon = rot_2D(self.theta)
|
||
# Rotate the fixed offset vector
|
||
point = [[self.offset[0]], [self.offset[1]]]
|
||
result = matmul(self.rot_moon, point)
|
||
# Translate back to screen coordinates
|
||
self.position_moon = (
|
||
self.center[0] + result[0][0],
|
||
self.center[1] + result[1][0],
|
||
)
|
||
return True
|
||
|
||
def draw_game(self) -> None:
|
||
self.screen.fill(BLACK)
|
||
pygame.draw.circle(self.screen, BLUE, self.center, EARTH_RADIUS)
|
||
pygame.draw.circle(
|
||
self.screen,
|
||
WHITE,
|
||
(int(self.position_moon[0]), int(self.position_moon[1])),
|
||
MOON_RADIUS,
|
||
)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
moon = Moon()
|
||
moon.run()
|
||
|