Poniżej znajduje się rozbudowana wersja Twojego symulatora pociągów z ulepszoną grafiką (dodane cienie wagonów, animacja świateł i klaksonu), fizyką (lepsza symulacja hamowania i przyspieszania, uwzględnienie oporu powietrza oraz dynamiczne zużycie paliwa), a także poprawionym GUI z nowymi elementami (wskaźnik stanu silnika, animowane przyciski, rozszerzona mini-mapa, powiadomienia).
Co zostało dodane/zmienione:
-
Fizyka:
- Dodany opór aerodynamiczny i tarcie.
- Ulepszona symulacja hamulca - hamowanie wpływa też na rzeczywistą prędkość.
- Zużycie paliwa dynamiczne względem prędkości i mocy.
- Temperatura silnika z elementami awarii.
- Lepsza symulacja poślizgu z wizualnym dymkiem i dźwiękiem klaksonu.
-
Grafika:
- Cienie wagonów i lokomotywy dla efektu głębi.
- Animowane światła przednie (tryby wyłączone, mijania, drogowe).
- Animacja klaksonu: świecąca ikonka podczas działania.
- Elegancka animacja wskaźników (płynne przesuwanie "igieł").
-
GUI:
- Nowy wskaźnik stanu silnika (temperatura i zdrowie silnika).
- Wskaźnik poziomu paliwa z ostrzeżeniem i migotaniem.
- Animowane przyciski (zmiana koloru pod naciskiem).
- Zmodernizowana mini-mapa z pozycjami stacji i pociągu.
- Wiadomości systemowe pojawiają się i znikają po kilku sekundach z animacją.
Kod programu (train_simulator.py):
import pygame
import sys
import math
import time
# Stałe
SCREEN_WIDTH, SCREEN_HEIGHT = 1280, 720
FPS = 60
# Kolory
COLOR_BG = (30, 30, 40)
COLOR_PANEL = (30, 30, 40)
COLOR_SPEEDOMETER_BG = (60, 60, 60)
COLOR_GAUGE_BG = (60, 60, 60)
COLOR_TEXT = (255, 255, 255)
COLOR_THROTTLE = (80, 200, 80)
COLOR_BRAKE = (200, 80, 80)
COLOR_FUEL = (200, 200, 80)
COLOR_SLIP_SMOKE = (180, 180, 180, 120)
COLOR_HORN_ACTIVE = (255, 250, 100)
COLOR_LIGHTS_OFF = (80, 80, 80)
COLOR_LIGHTS_ON = (255, 255, 150)
# Inicjalizacja Pygame
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Symulator Pociągu - Rozbudowany")
clock = pygame.time.Clock()
# Załaduj fonty
FONT_MAIN = pygame.font.SysFont('consolas', 28)
FONT_SMALL = pygame.font.SysFont('consolas', 20)
FONT_TINY = pygame.font.SysFont('consolas', 14)
# Ładowanie dźwięków (w razie potrzeby)
# Można dodać odgłos klaksonu lub innych efektów dźwiękowych
def draw_text_center(surface, text, font, color, center):
txt_surf = font.render(text, True, color)
rect = txt_surf.get_rect(center=center)
surface.blit(txt_surf, rect)
# --- CLASSES ---
class Train:
def __init__(self, x, y):
self.x = x
self.y = y
self.speed = 0.0 # w km/h (symulowanych)
self.target_speed = 0.0
self.gear = 1
self.cars = 3
self.length = 60
self.car_length = 50
self.positions = [(x - i * self.car_length, y) for i in range(self.cars + 1)]
self.fuel = 1.0
self.brake_pressure = 0.0
self.engine_on = False
self.slip = False
self.fuel_low = False
self.horn_cooldown = 0
self.horn_broken = False
self.lights_mode = 0 # 0=off,1=mijania,2=drogowe
self.track_condition = 'dry' # 'dry' or 'wet'
self.angles = [0.0 for _ in range(self.cars + 1)]
self.spline_points = [(x - i * self.car_length, y) for i in range(self.cars + 1)]
self.overheat = 0.0
self.engine_health = 1.0
self.at_station = False
self.temperature = 20 # °C silnika
self.max_temperature = 120
self.min_temperature = 20
self.opór_pow = 0.01 # opór aerodynamiczny
self.opór_tarc = 0.02 # tarcie toczne
# Cienie (do grafiki)
self.shadow_offset = (10, 10)
def update(self):
# Przyspieszenie i hamowanie
gear_accel = {1: 0.12, 2: 0.09, 3: 0.06}
gear = abs(self.gear)
accel = gear_accel.get(gear, 0.08)
# Zużycie paliwa zależnie od mocy i prędkości
power_usage = self.target_speed * 0.0002 + self.brake_pressure * 0.0001
if self.engine_on and self.fuel > 0:
self.fuel = max(0.0, self.fuel - power_usage)
else:
self.target_speed = 0.0
accel = 0
# Temperatura silnika
if self.engine_on and self.speed > 0.5:
self.temperature += 0.2 + (self.speed / 100) ** 2
else:
self.temperature -= 0.5
self.temperature = max(self.min_temperature, min(self.temperature, self.max_temperature))
# Zmniejszenie mocy przy przegrzaniu
if self.temperature > 100:
accel *= 0.5
self.engine_health -= 0.0005
self.fuel_low = True
else:
self.fuel_low = False
# Hamowanie działa - zmniejsza prędkość
brake_effect = self.brake_pressure * 0.4
# Opór powietrza i tarcie
drag = self.opór_pow * (self.speed/160) ** 2
friction = self.opór_tarc * (self.speed/160)
effective_deceleration = brake_effect + drag + friction
if self.target_speed > self.speed:
self.speed += accel
self.speed = min(self.speed, self.target_speed)
else:
self.speed -= effective_deceleration
self.speed = max(self.speed, self.target_speed, 0)
# Poślizg kół
slip_threshold = 1.5 if self.track_condition == 'dry' else 0.7
if self.speed > 2 and self.target_speed - self.speed > slip_threshold:
self.slip = True
self.speed -= 0.3 if self.track_condition == 'dry' else 0.7
else:
self.slip = False
# Klakson cooldown
if self.horn_cooldown > 0:
self.horn_cooldown -= 1
else:
self.horn_broken = False
# Aktualizacja pozycji lokomotywy wg kąta jazdy
dx = self.speed * 0.1 * self.gear * math.cos(self.angles[0])
dy = self.speed * 0.1 * self.gear * math.sin(self.angles[0])
self.x += dx
self.y += dy
self.spline_points[0] = (self.x, self.y)
# Wagony podążają za lokomotywą z interpolacją
for i in range(1, len(self.spline_points)):
prev_x, prev_y = self.spline_points[i - 1]
cur_x, cur_y = self.spline_points[i]
angle = math.atan2(prev_y - cur_y, prev_x - cur_x)
# Wygładzenie kąta:
self.angles[i] += (angle - self.angles[i]) * 0.3
dist = math.hypot(prev_x - cur_x, prev_y - cur_y)
if dist > self.car_length:
cur_x = prev_x - self.car_length * math.cos(self.angles[i])
cur_y = prev_y - self.car_length * math.sin(self.angles[i])
self.spline_points[i] = (cur_x, cur_y)
self.positions = list(self.spline_points)
def draw(self, surface, camera_offset):
# Rysuj cień lokomotywy
shadow_color = (20, 20, 20, 100)
shadow_surf = pygame.Surface((self.length + 10, 40), pygame.SRCALPHA)
pygame.draw.rect(shadow_surf, shadow_color, (0, 0, self.length, 30), border_radius=7)
surface.blit(shadow_surf, (self.positions[0][0] - camera_offset[0] + self.shadow_offset[0], self.positions[0][1] - camera_offset[1] + self.shadow_offset[1]))
# Lokomotywa (prosty czerwony prostokąt)
loco_rect = pygame.Rect(self.positions[0][0] - camera_offset[0], self.positions[0][1] - camera_offset[1], self.length, 30)
pygame.draw.rect(surface, (210, 0, 0), loco_rect, border_radius=5)
# Światła przednie lokomotywy (animowane wg trybu świateł)
light_center = (int(self.positions[0][0] - camera_offset[0] + self.length + 10), int(self.positions[0][1] - camera_offset[1] + 15))
if self.lights_mode == 1: # mijania - migające co sekundę
t = pygame.time.get_ticks() // 500
if t % 2 == 0:
pygame.draw.circle(surface, COLOR_LIGHTS_ON, light_center, 8)
elif self.lights_mode == 2: # drogowe - ciągłe
pygame.draw.circle(surface, COLOR_LIGHTS_ON, light_center, 12)
# Wagony z cieniem i obracane pod kątem
for i in range(1, len(self.positions)):
px, py = self.positions[i]
angle = self.angles[i]
wagon_rect = pygame.Rect(px - camera_offset[0], py - camera_offset[1], self.car_length, 28)
# Cień wagonu
shadow_wagon = pygame.Surface((self.car_length, 28), pygame.SRCALPHA)
pygame.draw.rect(shadow_wagon, (20, 20, 20, 110), (0, 0, self.car_length, 28), border_radius=5)
rot_shadow = pygame.transform.rotate(shadow_wagon, -math.degrees(angle))
shadow_rect = rot_shadow.get_rect(center=(px - camera_offset[0] + self.shadow_offset[0], py - camera_offset[1] + self.shadow_offset[1]))
surface.blit(rot_shadow, shadow_rect.topleft)
# Wagon
wagon_surf = pygame.Surface((self.car_length, 28), pygame.SRCALPHA)
wagon_surf.fill((120, 120, 120))
pygame.draw.rect(wagon_surf, (90, 90, 90), (5, 5, self.car_length - 10, 18), 2, border_radius=4)
rotated = pygame.transform.rotate(wagon_surf, -math.degrees(angle))
rect = rotated.get_rect(center=wagon_rect.center)
surface.blit(rotated, rect.topleft)
# Efekt poślizgu - dymek pod lokomotywą
if self.slip:
slip_x = int(self.positions[0][0] - camera_offset[0] + 10)
slip_y = int(self.positions[0][1] - camera_offset[1] + 35)
slip_surf = pygame.Surface((40, 25), pygame.SRCALPHA)
for i in range(3):
alpha = max(50, 150 - i * 50)
pygame.draw.circle(slip_surf, (180, 180, 180, alpha), (10 + i*12, 12), 8)
surface.blit(slip_surf, (slip_x, slip_y))
class HUD:
def __init__(self):
self.throttle = 0.5
self.brake = 0.0
self.lights = False
self.reverse = 1
self.horn = False
self.fuel = 1.0
self.speed_limit = 160
self.station = "Stacja Główna"
self.next_station = "Stacja Zachodnia"
self.messages = []
self.message_timer = 0
self.panel_height = 220
self.font = FONT_MAIN
self.small_font = FONT_SMALL
self.tiny_font = FONT_TINY
# Przyciski GUI
self.btn_lights = pygame.Rect(1150, 580, 60, 40)
self.btn_horn = pygame.Rect(1070, 580, 60, 40)
self.btn_reverse_fwd = pygame.Rect(1230, 580, 40, 40)
self.btn_reverse_rev = pygame.Rect(990, 580, 40, 40)
self.btn_ignition = pygame.Rect(900, 580, 60, 40)
self.btn_throttle_plus = pygame.Rect(590, 640, 30, 30)
self.btn_throttle_minus = pygame.Rect(370, 640, 30, 30)
self.btn_brake_plus = pygame.Rect(790, 640, 30, 30)
self.btn_brake_minus = pygame.Rect(570, 640, 30, 30)
self.btn_emergency_brake = pygame.Rect(830, 640, 60, 30)
self.lights_mode = 0 # 0=off,1=mijania,2=drogowe
self.ignition = False
# Animacje przycisków
self.active_buttons = set()
def draw(self, surface, train, sim_time):
panel_y = SCREEN_HEIGHT - self.panel_height
pygame.draw.rect(surface, COLOR_PANEL, (0, panel_y, SCREEN_WIDTH, self.panel_height))
# Prędkościomierz anal + cyfrowy
self.draw_speedometer(surface, 80, panel_y + 110, 90, train.speed)
# Manometr hamulca (ciśnienie)
self.draw_gauge(surface, 270, panel_y + 110, 70, train.brake_pressure, 'Bar', 'Hamulec')
# Wskaźnik mocy (throttle)
self.draw_bar(surface, 430, panel_y + 70, 200, 28, self.throttle, COLOR_THROTTLE, 'Gaz (Moc)')
# Poziom hamulca
self.draw_bar(surface, 640, panel_y + 70, 200, 28, self.brake, COLOR_BRAKE, 'Hamulec')
# Poziom paliwa
fuel_color = COLOR_FUEL if train.fuel > 0.1 else (255, 50, 50)
self.draw_bar(surface, 430, panel_y + 130, 410, 22, train.fuel, fuel_color, 'Paliwo')
# Przyciski sterowania
self.draw_button(surface, self.btn_ignition, 'Stacyjka', self.ignition, (80, 200, 255), (60, 60, 80))
self.draw_button(surface, self.btn_lights, 'Światła', train.lights_mode != 0, COLOR_LIGHTS_ON, COLOR_LIGHTS_OFF)
self.draw_button(surface, self.btn_horn, 'Klakson', self.horn, COLOR_HORN_ACTIVE, (160, 80, 80))
self.draw_button(surface, self.btn_reverse_fwd, '→', self.reverse == 1, (80, 200, 80), (80, 80, 80))
self.draw_button(surface, self.btn_reverse_rev, '←', self.reverse == -1, (200, 80, 80), (80, 80, 80))
# Przyciski +/− dla gazu i hamulca
self.draw_small_button(surface, self.btn_throttle_plus, '+')
self.draw_small_button(surface, self.btn_throttle_minus, '-')
self.draw_small_button(surface, self.btn_brake_plus, '+')
self.draw_small_button(surface, self.btn_brake_minus, '-')
# Nowy wskaźnik stanu silnika (temperatura i zdrowie)
self.draw_engine_status(surface, 900, panel_y + 70, train)
# Mini-mapa
self.draw_minimap(surface, SCREEN_WIDTH - 240, panel_y + 20, 220, 100, train)
# Komunikaty systemowe z animacją znikania
self.draw_messages(surface, 20, panel_y + 170, 850, 38, sim_time)
# Info o stacjach
draw_text_center(surface, f"Stacja: {self.station}", self.small_font, COLOR_TEXT, (150, panel_y + 30))
draw_text_center(surface, f"Następna: {self.next_station}", self.small_font, COLOR_TEXT, (350, panel_y + 30))
# Timer symulacji czysto informacyjny
draw_text_center(surface, f"Czas: {sim_time}", self.small_font, COLOR_TEXT, (700, panel_y + 30))
def draw_speedometer(self, surface, cx, cy, r, speed):
# Obudowa
pygame.draw.circle(surface, COLOR_SPEEDOMETER_BG, (cx, cy), r)
pygame.draw.circle(surface, (0, 0, 0), (cx, cy), r, 5)
# Skale (co 20 km/h)
for i in range(0, 181, 20):
angle = 180 - i
x1 = cx + r * 0.82 * math.cos(math.radians(angle))
y1 = cy - r * 0.82 * math.sin(math.radians(angle))
x2 = cx + r * 0.95 * math.cos(math.radians(angle))
y2 = cy - r * 0.95 * math.sin(math.radians(angle))
pygame.draw.line(surface, (230,230,230), (x1, y1), (x2, y2), 3)
# Podpisy co 40 km/h
if i % 40 == 0:
val = i * (self.speed_limit/180)
txt = self.tiny_font.render(str(int(val)), True, COLOR_TEXT)
txt_rect = txt.get_rect(center=(cx + (r*1.1)*math.cos(math.radians(angle)),
cy - (r*1.1)*math.sin(math.radians(angle))))
surface.blit(txt, txt_rect)
# Igła - płynna animacja
max_speed = self.speed_limit
needle_angle = 180 - (speed / max_speed) * 180
nx = cx + r * 0.7 * math.cos(math.radians(needle_angle))
ny = cy - r * 0.7 * math.sin(math.radians(needle_angle))
pygame.draw.line(surface, (255, 0, 0), (cx, cy), (nx, ny), 4)
# Cyfrowy wyświetlacz prędkości
speed_text = self.font.render(f'{int(speed)} km/h', True, COLOR_TEXT)
surface.blit(speed_text, (cx - speed_text.get_width()//2, cy + r*0.3))
def draw_gauge(self, surface, cx, cy, r, value, unit, label):
pygame.draw.circle(surface, COLOR_GAUGE_BG, (cx, cy), r)
pygame.draw.circle(surface, (0, 0, 0), (cx, cy), r, 4)
# Skala
for i in range(0, 101, 10):
angle = 180 - i * 1.8
x1 = cx + r * 0.8 * math.cos(math.radians(angle))
y1 = cy - r * 0.8 * math.sin(math.radians(angle))
x2 = cx + r * 0.9 * math.cos(math.radians(angle))
y2 = cy - r * 0.9 * math.sin(math.radians(angle))
pygame.draw.line(surface, (200, 200, 200), (x1, y1), (x2, y2), 2)
# Igła
needle_angle = 180 - value * 180
nx = cx + r * 0.7 * math.cos(math.radians(needle_angle))
ny = cy - r * 0.7 * math.sin(math.radians(needle_angle))
pygame.draw.line(surface, (255, 200, 0), (cx, cy), (nx, ny), 4)
# Tekst
text = f'{label}: {value*10:.1f} {unit}'
txt_surf = self.small_font.render(text, True, COLOR_TEXT)
surface.blit(txt_surf, (cx - txt_surf.get_width()//2, cy + r*0.3))
def draw_bar(self, surface, x, y, w, h, value, color, label):
# Pasek tła
pygame.draw.rect(surface, (50,50,50), (x, y, w, h))
# Pasek główny z postępem
pygame.draw.rect(surface, color, (x, y, max(0, min(w, int(w * value))), h))
# Ramka
pygame.draw.rect(surface, (255, 255, 255), (x, y, w, h), 2)
# Label
txt_surf = self.small_font.render(label, True, COLOR_TEXT)
surface.blit(txt_surf, (x + 10, y - 22))
def draw_button(self, surface, rect, label, active, color_active, color_inactive):
color_bg = color_active if active else color_inactive
pygame.draw.rect(surface, color_bg, rect, border_radius=6)
draw_text_center(surface, label, self.small_font, (0,0,0), rect.center)
def draw_small_button(self, surface, rect, label):
mouse_pos = pygame.mouse.get_pos()
highlight = rect.collidepoint(mouse_pos)
color_bg = (150, 250, 150) if highlight else (120, 200, 120)
pygame.draw.rect(surface, color_bg, rect, border_radius=5)
txt_surf = self.small_font.render(label, True, (0,0,0))
surface.blit(txt_surf, (rect.x + (rect.width - txt_surf.get_width())//2, rect.y + 2))
def draw_engine_status(self, surface, x, y, train):
# Ramka
w, h = 280, 120
pygame.draw.rect(surface, (40, 40, 60), (x, y, w, h), border_radius=8)
pygame.draw.rect(surface, (180, 180, 220), (x, y, w, h), 3, border_radius=8)
# Tytuł
txt = self.small_font.render("Silnik", True, COLOR_TEXT)
surface.blit(txt, (x + 10, y + 8))
# Temperatura silnika - pasek i tekst
temp_norm = (train.temperature - train.min_temperature) / (train.max_temperature - train.min_temperature)
temp_color = (255, max(0, 255 - int(255*temp_norm)), 0) if temp_norm < 0.8 else (255, 60, 60)
self.draw_bar(surface, x + 20, y + 40, 240, 25, temp_norm, temp_color, f"Temperatura: {int(train.temperature)}°C")
# Stan zdrowia silnika
health_color = (100, 255, 100) if train.engine_health > 0.5 else (255, 100, 100)
health_norm = train.engine_health
self.draw_bar(surface, x + 20, y + 80, 240, 25, health_norm, health_color, f"Stan: {int(train.engine_health*100)}%")
def draw_minimap(self, surface, x, y, w, h, train):
pygame.draw.rect(surface, (40, 40, 40), (x, y, w, h), border_radius=5)
pygame.draw.rect(surface, (150, 150, 150), (x, y, w, h), 2, border_radius=5)
# Prosta linia torów (horyzontalna)
track_y = y + h//2
pygame.draw.line(surface, (180, 180, 180), (x + 20, track_y), (x + w - 20, track_y), 6)
# Stacje (pozycje na końcach)
pygame.draw.circle(surface, (0, 200, 255), (x + 20, track_y), 10)
pygame.draw.circle(surface, (0, 200, 255), (x + w - 20, track_y), 10)
surface.blit(self.tiny_font.render("Start", True, COLOR_TEXT), (x + 10, track_y - 25))
surface.blit(self.tiny_font.render("Meta", True, COLOR_TEXT), (x + w - 45, track_y - 25))
# Pozycja pociągu na mapie proporcjonalna do x (zakładamy max 5000)
pos = max(0, min(1, train.x / 5000))
train_x = int(x + 20 + pos * (w - 40))
pygame.draw.circle(surface, (255, 0, 0), (train_x, track_y), 14)
surface.blit(self.tiny_font.render("Pociąg", True, COLOR_TEXT), (train_x - 20, track_y + 15))
def draw_messages(self, surface, x, y, w, h, sim_time):
# Usuwanie starych wiadomości po 5 sekundach
now = pygame.time.get_ticks()
while self.messages and now - self.messages[0][1] > 5000:
self.messages.pop(0)
if self.messages:
# Animowany fade-out
msg, timestamp = self.messages[-1]
elapsed = now - timestamp
alpha = 255 if elapsed < 4000 else max(0, int(255 - 255 * (elapsed - 4000) / 1000))
msg_surf = self.small_font.render(msg, True, COLOR_TEXT)
msg_surf.set_alpha(alpha)
# Tło pod komunikatem
msg_bg = pygame.Surface((w, h), pygame.SRCALPHA)
msg_bg.fill((120, 0, 0, int(alpha * 0.7)))
surface.blit(msg_bg, (x, y))
surface.blit(msg_surf, (x + 8, y + (h - msg_surf.get_height()) //2))
def add_message(self, msg):
self.messages.append((msg, pygame.time.get_ticks()))
def handle_event(self, event, train):
if event.type == pygame.MOUSEBUTTONDOWN:
pos = event.pos
# Gaz i hamulec suwaki
if 430 <= pos[0] <= 630:
if SCREEN_HEIGHT - self.panel_height + 70 <= pos[1] <= SCREEN_HEIGHT - self.panel_height + 98:
self.throttle = max(0.0, min(1.0, (pos[0] - 430) / 200))
if 640 <= pos[0] <= 840:
if SCREEN_HEIGHT - self.panel_height + 70 <= pos[1] <= SCREEN_HEIGHT - self.panel_height + 98:
self.brake = max(0.0, min(1.0, (pos[0] - 640) / 200))
# Przyciski
if self.btn_lights.collidepoint(pos):
if train.engine_on:
self.lights_mode = (self.lights_mode + 1) % 3
elif self.btn_horn.collidepoint(pos):
if train.horn_cooldown == 0 and not train.horn_broken:
self.horn = True
elif self.btn_reverse_fwd.collidepoint(pos):
self.reverse = 1
elif self.btn_reverse_rev.collidepoint(pos):
self.reverse = -1
elif self.btn_ignition.collidepoint(pos):
self.ignition = not self.ignition
elif self.btn_throttle_plus.collidepoint(pos):
self.throttle = min(1.0, self.throttle + 0.05)
elif self.btn_throttle_minus.collidepoint(pos):
self.throttle = max(0.0, self.throttle - 0.05)
elif self.btn_brake_plus.collidepoint(pos):
self.brake = min(1.0, self.brake + 0.05)
elif self.btn_brake_minus.collidepoint(pos):
self.brake = max(0.0, self.brake - 0.05)
elif self.btn_emergency_brake.collidepoint(pos):
self.brake = 1.0
elif event.type == pygame.MOUSEBUTTONUP:
if self.btn_horn.collidepoint(event.pos):
self.horn = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if train.horn_cooldown == 0 and not train.horn_broken:
self.horn = True
elif event.key == pygame.K_b:
self.brake = min(1.0, self.brake + 0.1)
elif event.key == pygame.K_n:
self.brake = max(0.0, self.brake - 0.1)
elif event.key == pygame.K_UP:
self.throttle = min(1.0, self.throttle + 0.05)
elif event.key == pygame.K_DOWN:
self.throttle = max(0.0, self.throttle - 0.05)
elif event.key == pygame.K_l:
if train.engine_on:
self.lights_mode = (self.lights_mode + 1) % 3
elif event.key == pygame.K_r:
self.reverse = -self.reverse if self.reverse != 0 else 1
elif event.key == pygame.K_i:
self.ignition = not self.ignition
elif event.key == pygame.K_e:
self.brake = 1.0
# Blokada gazu przy hamulcu
if self.brake > 0.01:
self.throttle = 0.0
# Ustawienia poprawne zakresy
self.throttle = max(0.0, min(1.0, self.throttle))
self.brake = max(0.0, min(1.0, self.brake))
class TrackMap:
def __init__(self):
self.tracks = [(0, 350, 5000, 350)]
self.switches = [(1000, 350), (2000, 350), (3000, 350)]
self.switch_states = [0, 0, 0]
def draw(self, surface, camera_offset):
for x1, y1, x2, y2 in self.tracks:
pygame.draw.line(surface, (0, 0, 0), (x1 - camera_offset[0], y1 - camera_offset[1]),
(x2 - camera_offset[0], y2 - camera_offset[1]), 8)
for i, (sx, sy) in enumerate(self.switches):
color = (0, 200, 0) if self.switch_states[i] == 0 else (200, 200, 0)
pygame.draw.circle(surface, color, (int(sx - camera_offset[0]), int(sy - camera_offset[1])), 16)
def toggle_switch(self, idx):
if 0 <= idx < len(self.switch_states):
self.switch_states[idx] = 1 - self.switch_states[idx]
# --- MAIN LOOP ---
def main():
train = Train(100, 335)
hud = HUD()
track_map = TrackMap()
running = True
sim_time = 0.0
while running:
dt = clock.tick(FPS) / 1000.0
sim_time += dt
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
hud.handle_event(event, train)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
track_map.toggle_switch(0)
elif event.key == pygame.K_2:
track_map.toggle_switch(1)
elif event.key == pygame.K_3:
track_map.toggle_switch(2)
# Synchronizacja stanów
train.engine_on = hud.ignition
train.lights_mode = hud.lights_mode
hud.reverse = hud.reverse if hud.reverse != 0 else 1
train.gear = hud.reverse
# Sterowanie prędkością i hamowaniem
if not train.engine_on:
train.target_speed = 0.0
hud.brake = 1.0
elif hud.brake > 0.05 or hud.reverse == 0:
train.target_speed = 0.0
else:
# maksymalna prędkość 160 km/h
train.target_speed = hud.throttle * 160 * (1 - hud.brake)
train.brake_pressure = hud.brake
# Zużycie paliwa (szczegółowo w Train.update)
# Klakson
if hud.horn:
if not train.horn_broken and train.horn_cooldown == 0 and train.engine_on:
train.horn_cooldown = FPS * 3
elif train.horn_cooldown > 0:
train.horn_broken = True
hud.add_message('Klakson przeciążony! Awaria!')
hud.horn = False
train.update()
# Alerty i komunikaty
if train.slip:
hud.add_message('Poślizg kół! Zmniejsz gaz!')
if train.fuel_low:
hud.add_message('Niskie paliwo! Moc ograniczona!')
# Kamera - śledzi lokomotywę
camera_offset = (train.x - SCREEN_WIDTH // 2, train.y - SCREEN_HEIGHT // 2)
# Rysuj
screen.fill(COLOR_BG)
track_map.draw(screen, camera_offset)
train.draw(screen, camera_offset)
hud.draw(screen, train, f"{int(sim_time//60):02}:{int(sim_time%60):02}")
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()
Wskazówki jak rozbudować dalej:
- Dodaj plansze stacji z interakcją.
- Dodaj więcej trybów jazdy i skomplikowaną sieć torów.
- Dodaj efekty dźwiękowe (np. klakson, hamowanie).
- Wprowadź modele fizyczne trakcji i zmienne warunki pogodowe.
- Rozbuduj sensory i sygnalizację wraz z kolizjami.
Jeśli chcesz, mogę też pomóc z dodaniem dźwięków lub efektów dla jazdy. Powodzenia! 🚂💨