77 lines
2.5 KiB
Python
77 lines
2.5 KiB
Python
import pygame
|
|
from pygame.math import Vector2
|
|
|
|
from scripts.constants import *
|
|
|
|
|
|
class Player:
|
|
def __init__(self, pos: pygame.Vector2, width, height, image: pygame.Surface=None):
|
|
self.pos: Vector2 = pos
|
|
self.width: float = width
|
|
self.height: float = height
|
|
self.speed = 150
|
|
self.image = image
|
|
self.mask = pygame.mask.from_surface(self.image)
|
|
self.rect = image.get_frect()
|
|
|
|
|
|
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:
|
|
offset = (int(self.rect.x) - int(wall.rect.x), int(self.rect.y) - int(wall.rect.y))
|
|
|
|
wall_rect = wall.get_rect()
|
|
if self.mask.overlap(wall.mask, offset):
|
|
if movement.x > 0:
|
|
self.rect.right = wall_rect.left
|
|
elif movement.x < 0:
|
|
self.rect.left = wall_rect.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:
|
|
offset = (int(self.rect.x) - wall.rect.x, int(self.rect.y) - wall.rect.y)
|
|
|
|
wall_rect = wall.get_rect()
|
|
if self.mask.overlap(wall.mask, offset):
|
|
if movement.y > 0:
|
|
self.rect.bottom = wall_rect.top
|
|
elif movement.y < 0:
|
|
self.rect.top = wall_rect.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.mask.to_surface(),
|
|
(self.pos[0]-TILE_SIZE/2, self.pos[1]-TILE_SIZE/2-10, self.image.get_width(), self.image.get_height()),
|
|
)
|