school-horror-game/scripts/player.py
2026-11-11 17:54:46 +01:00

72 lines
2.3 KiB
Python

import pygame
from pygame.math import Vector2
from scripts.constants import *
class Player:
def __init__(self, pos: pygame.Vector2, width, height, image=None):
self.pos: Vector2 = pos
self.width: float = width
self.height: float = height
self.speed = 150
self.image = image
self.rect = pygame.Rect(
self.pos[0] - self.width / 2, self.pos[1] - self.height / 2, width, height
)
def update(self, walls, dt):
keys = pygame.key.get_pressed()
direction = pygame.Vector2(
keys[pygame.K_d] - keys[pygame.K_a], keys[pygame.K_s] - keys[pygame.K_w]
)
if direction.length_squared() > 0:
direction = direction.normalize()
movement: pygame.Vector2 = direction * self.speed * dt
self.pos.x += movement.x
if self.pos.x - self.width / 2 < 0:
self.pos.x = self.width / 2
if self.pos.x + self.width / 2 > SCREEN_WIDTH:
self.pos.x = SCREEN_WIDTH - self.width / 2
self.rect.centerx = round(self.pos.x)
for wall in walls:
wall = wall.get_rect()
if self.rect.colliderect(wall):
if movement.x > 0:
self.rect.right = wall.left
elif movement.x < 0:
self.rect.left = wall.right
self.pos.x = self.rect.centerx
self.pos.y += movement.y
if self.pos.y - self.height / 2 < 0:
self.pos.y = self.height / 2
if self.pos.y + self.height / 2 > SCREEN_HEIGHT:
self.pos.y = SCREEN_HEIGHT - self.height / 2
self.rect.centery = round(self.pos.y)
for wall in walls:
wall = wall.get_rect()
if self.rect.colliderect(wall):
if movement.y > 0:
self.rect.bottom = wall.top
elif movement.y < 0:
self.rect.top = wall.bottom
self.pos.y = self.rect.centery
def render(self, surface: pygame.Surface):
if not self.image:
pygame.draw.rect(surface, self.color, self.rect)
else:
surface.blit(
self.image,
(self.pos[0]-TILE_SIZE/2, self.pos[1]-TILE_SIZE/2-10, self.image.get_width(), self.image.get_height()),
)