Adding Player, movement, and drawing/updating functionality

This commit is contained in:
franky212
2024-10-28 16:00:40 -06:00
parent 90d55e89b7
commit 0412b21bb0
5 changed files with 84 additions and 5 deletions

0
asteroid.py Normal file
View File

22
circleshape.py Normal file
View File

@@ -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

View File

@@ -1,6 +1,10 @@
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 720
PLAYER_RADIUS = 20
PLAYER_TURN_SPEED = 300
PLAYER_SPEED = 200
ASTEROID_MIN_RADIUS = 20
ASTEROID_KINDS = 3
ASTEROID_SPAWN_RATE = 0.8 # seconds

24
main.py
View File

@@ -2,20 +2,34 @@
# the open-source pygame library
# throughout this file
import pygame
from constants import *
from constants import SCREEN_HEIGHT, SCREEN_WIDTH
from player import Player
def main():
pygame.init()
print("Starting asteroids!")
print(f"Screen width: {SCREEN_WIDTH}")
print(f"Screen height: {SCREEN_HEIGHT}")
clock = pygame.time.Clock()
dt = 0
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
player = Player(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
updatable = []
drawable = []
updatable.append(player)
drawable.append(player)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
pygame.Surface.fill(screen, (0, 0, 0))
screen.fill("black")
# limit the framerate to 60 FPS
dt = clock.tick(60) / 1000
for object in drawable:
object.draw(screen)
for object in updatable:
object.update(dt)
pygame.display.flip()
if __name__ == "__main__":

39
player.py Normal file
View File

@@ -0,0 +1,39 @@
import pygame
from circleshape import CircleShape
from constants import PLAYER_RADIUS, PLAYER_TURN_SPEED, PLAYER_SPEED
class Player(CircleShape):
def __init__(self, x, y):
super().__init__(x, y, PLAYER_RADIUS)
self.rotation = 0
def rotate(self, dt):
self.rotation += PLAYER_TURN_SPEED * dt
def move(self, dt):
forward = pygame.Vector2(0, 1).rotate(self.rotation)
self.position += forward * PLAYER_SPEED * dt
def update(self, dt):
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
self.rotate(dt)
if keys[pygame.K_d]:
self.rotate(-dt)
if keys[pygame.K_w]:
self.move(dt)
if keys[pygame.K_s]:
self.move(-dt)
# 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)