AI-Project/survival/player.py

79 lines
2.3 KiB
Python
Raw Permalink Normal View History

2021-03-14 22:57:33 +01:00
from random import randint
2021-03-04 14:07:44 +01:00
import pygame
class Player:
2021-03-04 14:07:44 +01:00
def __init__(self):
2021-03-28 18:05:52 +02:00
# self.pos = [1024, 512]
# self.velocity = [0, 0]
# self.image = Image('stevenson.png')
# self.image.set_scale(2)
# self.speed = 30
# self.movement_target = [self.pos[0], self.pos[1]]
# self.timer = 0
pass
2021-03-04 14:07:44 +01:00
def draw(self, camera):
2021-03-28 18:05:52 +02:00
self.image.pos = self.pos
camera.draw(self.image)
2021-03-04 14:07:44 +01:00
def is_moving(self):
return self.pos != self.movement_target
def move_in_random_direction(self):
2021-03-14 22:57:33 +01:00
value = randint(0, 3)
random_movement = {
0: self.move_up,
1: self.move_down,
2: self.move_left,
3: self.move_right
}
random_movement[value]()
def update(self, delta, pressed_keys):
if self.is_moving():
if self.velocity[0] != 0:
self.pos[0] += self.velocity[0] * self.speed * delta / 100
if abs(self.movement_target[0] - self.pos[0]) < 0.1 * self.speed:
self.velocity = [0, 0]
self.pos = self.movement_target
else:
self.pos[1] += self.velocity[1] * self.speed * delta / 100
if abs(self.pos[1] - self.movement_target[1]) < 0.1 * self.speed:
self.velocity = [0, 0]
self.pos = self.movement_target
return
2021-03-14 22:57:33 +01:00
self.timer += delta
if self.timer > 1000:
2021-03-28 18:05:52 +02:00
self.move_in_random_direction()
2021-03-14 22:57:33 +01:00
self.timer = 0
2021-03-04 14:07:44 +01:00
if pressed_keys[pygame.K_LEFT]:
2021-03-14 22:57:33 +01:00
self.move_left()
2021-03-04 14:07:44 +01:00
elif pressed_keys[pygame.K_RIGHT]:
2021-03-14 22:57:33 +01:00
self.move_right()
elif pressed_keys[pygame.K_DOWN]:
2021-03-14 22:57:33 +01:00
self.move_down()
2021-03-04 14:07:44 +01:00
elif pressed_keys[pygame.K_UP]:
2021-03-14 22:57:33 +01:00
self.move_up()
def move_left(self):
self.velocity = [-1, 0]
self.movement_target = [self.pos[0] - 32, self.pos[1]]
def move_right(self):
self.velocity = [1, 0]
self.movement_target = [self.pos[0] + 32, self.pos[1]]
def move_up(self):
self.velocity = [0, -1]
self.movement_target = [self.pos[0], self.pos[1] - 32]
2021-03-04 14:07:44 +01:00
2021-03-14 22:57:33 +01:00
def move_down(self):
self.velocity = [0, 1]
self.movement_target = [self.pos[0], self.pos[1] + 32]