Untitled
unknown
plain_text
a month ago
2.7 kB
6
Indexable
import math
import pygame
from pygame.math import Vector2
# --- Config ---
WIDTH, HEIGHT = 800, 600
FPS = 60
SHIP_THRUST = 0.15
SHIP_ROT_SPEED = 3 # degrees per frame
SHIP_DRAG = 0.0 # 0 = no drag (space)
# --- Init ---
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Simple Space Flight Simulator")
clock = pygame.time.Clock()
# --- Ship setup ---
class Ship:
def __init__(self, pos):
self.pos = Vector2(pos)
self.vel = Vector2(0, 0)
self.angle = 0 # degrees, 0 = pointing right
# Simple triangular ship shape (local coordinates)
self.points = [
Vector2(20, 0), # nose
Vector2(-15, 10),
Vector2(-15, -10),
]
def update(self, keys):
# Rotation
if keys[pygame.K_LEFT]:
self.angle += SHIP_ROT_SPEED
if keys[pygame.K_RIGHT]:
self.angle -= SHIP_ROT_SPEED
# Thrust (forward in direction of angle)
if keys[pygame.K_UP]:
rad = math.radians(self.angle)
thrust_vec = Vector2(math.cos(rad), -math.sin(rad)) * SHIP_THRUST
self.vel += thrust_vec
# Optional drag
self.vel *= (1.0 - SHIP_DRAG)
# Update position
self.pos += self.vel
# Wrap around screen edges
if self.pos.x > WIDTH:
self.pos.x = 0
elif self.pos.x < 0:
self.pos.x = WIDTH
if self.pos.y > HEIGHT:
self.pos.y = 0
elif self.pos.y < 0:
self.pos.y = HEIGHT
def get_transformed_points(self):
# Rotate and translate ship points
rad = math.radians(self.angle)
cos_a = math.cos(rad)
sin_a = math.sin(rad)
transformed = []
for p in self.points:
x = p.x * cos_a - p.y * sin_a
y = p.x * sin_a + p.y * cos_a
transformed.append((x + self.pos.x, y + self.pos.y))
return transformed
def draw(self, surface):
pygame.draw.polygon(surface, (255, 255, 255), self.get_transformed_points(), 2)
ship = Ship((WIDTH // 2, HEIGHT // 2))
# --- Main loop ---
running = True
while running:
dt = clock.tick(FPS) / 1000.0 # not used here but useful for scaling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
ship.update(keys)
# Draw
screen.fill((0, 0, 20)) # dark space background
ship.draw(screen)
# Simple stars
for x in range(0, WIDTH, 80):
for y in range(0, HEIGHT, 80):
pygame.draw.circle(screen, (255, 255, 255), (x + 10, y + 10), 1)
pygame.display.flip()
pygame.quit()
Editor is loading...
Leave a Comment