From 6b3eda2ad197d2bd9d434f820f682f13e71c8fbb Mon Sep 17 00:00:00 2001 From: yuzu-eva Date: Fri, 20 Sep 2024 17:21:09 +0200 Subject: render shapes and add rotation --- circleshape.py | 22 ++++++++++++++++++++++ constants.py | 3 +++ main.py | 8 ++++++++ player.py | 31 +++++++++++++++++++++++++++++++ 4 files changed, 64 insertions(+) create mode 100644 circleshape.py create mode 100644 player.py diff --git a/circleshape.py b/circleshape.py new file mode 100644 index 0000000..eb08882 --- /dev/null +++ b/circleshape.py @@ -0,0 +1,22 @@ +import pygame + +# Base class for game objects +class CircleShape(pygame.sprite.Sprite): + def __init__(self, x, y, radius): + # we will be using this later + if hasattr(self, "containers"): + super().__init__(self.containers) + else: + super().__init__() + + self.position = pygame.Vector2(x, y) + self.velocity = pygame.Vector2(0, 0) + self.radius = radius + + def draw(self, screen): + # sub-classes must override + pass + + def update(self, dt): + # sub-classes must override + pass diff --git a/constants.py b/constants.py index 6f9d7d2..4b98fc6 100644 --- a/constants.py +++ b/constants.py @@ -5,3 +5,6 @@ ASTEROID_MIN_RADIUS = 20 ASTEROID_KINDS = 3 ASTEROID_SPAWN_RATE = 0.8 # seconds ASTEROID_MAX_RADIUS = ASTEROID_MIN_RADIUS * ASTEROID_KINDS + +PLAYER_RADIUS = 20 +PLAYER_TURN_SPEED = 300 diff --git a/main.py b/main.py index e91ba28..bd59cfc 100644 --- a/main.py +++ b/main.py @@ -1,15 +1,23 @@ import pygame from constants import * +from circleshape import * +from player import * def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) + clock = pygame.time.Clock() + dt = 0 + player = Player(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: return screen.fill("black") + player.update(dt) + player.draw(screen) pygame.display.flip() + dt = clock.tick(60) / 1000 if __name__ == "__main__": main() diff --git a/player.py b/player.py new file mode 100644 index 0000000..d629c09 --- /dev/null +++ b/player.py @@ -0,0 +1,31 @@ +import pygame +from constants import * +from circleshape import * + +class Player(CircleShape): + def __init__(self, x, y): + super().__init__(x, y, PLAYER_RADIUS) + self.rotation = 0 + + # in the player class + def triangle(self): + forward = pygame.Vector2(0, 1).rotate(self.rotation) + right = pygame.Vector2(0, 1).rotate(self.rotation + 90) * self.radius / 1.5 + a = self.position + forward * self.radius + b = self.position - forward * self.radius - right + c = self.position - forward * self.radius + right + return [a, b, c] + + def draw(self, screen): + pygame.draw.polygon(screen, "white", self.triangle(), 2) + + def rotate(self, dt): + self.rotation += PLAYER_TURN_SPEED * dt + + def update(self, dt): + keys = pygame.key.get_pressed() + if keys[pygame.K_LEFT]: + self.rotate(-dt) + if keys[pygame.K_RIGHT]: + self.rotate(dt) + -- cgit v1.2.3