62 lines
1.9 KiB
Python
62 lines
1.9 KiB
Python
|
|
import pygame
|
||
|
|
from pygame.math import Vector2
|
||
|
|
|
||
|
|
from scripts.constants import *
|
||
|
|
|
||
|
|
|
||
|
|
class Player:
|
||
|
|
def __init__(self, pos: pygame.Vector2, width, height):
|
||
|
|
self.pos: Vector2 = pos
|
||
|
|
self.width: float = width
|
||
|
|
self.height: float = height
|
||
|
|
self.speed = 150
|
||
|
|
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:
|
||
|
|
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:
|
||
|
|
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.draw.rect(surface, (255, 0, 0), self.rect)
|