Machine_learning_2023/domain/commands/random_cat_move_command.py

71 lines
2.2 KiB
Python
Raw Normal View History

2023-05-18 23:18:07 +02:00
from random import randint
from typing import Tuple
import pygame
from domain.commands.command import Command
from domain.entities.cat import Cat
from domain.world import World
class RandomCatMoveCommand(Command):
def __init__(self, world: World, cat: Cat) -> None:
super().__init__()
self.world = world
self.cat = cat
def run(self):
move_vector = (0, 0)
now = pygame.time.get_ticks()
# region cat random movement
cat = self.world.cat
if now - cat.last_tick >= cat.cooldown:
if not cat.busy:
while True:
cat.direction = randint(0, 3)
if not (
(cat.direction == 0 and cat.y == 0)
or (cat.direction == 1 and cat.x == self.world.width - 1)
or (cat.direction == 2 and cat.y == self.world.height - 1)
or (cat.direction == 3 and cat.x == 0)
):
break
if cat.direction == 0: # up
if cat.busy:
move_vector = (0, -1)
cat.busy = not cat.busy
if cat.direction == 1: # right
if cat.busy:
move_vector = (1, 0)
cat.busy = not cat.busy
if cat.direction == 2: # down
if cat.busy:
move_vector = (0, 1)
cat.busy = not cat.busy
if cat.direction == 3: # left
if cat.busy:
move_vector = (-1, 0)
cat.busy = not cat.busy
cat.last_tick = pygame.time.get_ticks()
if move_vector == (0, 0):
return
end_x = cat.x + move_vector[0]
end_y = cat.y + move_vector[1]
if (
end_x > self.world.width - 1
or end_y > self.world.height - 1
or end_x < 0
or end_y < 0
):
return
self.world.obstacles[cat.x][cat.y].remove(cat)
cat.x = end_x
cat.y = end_y
self.world.obstacles[end_x][end_y].append(cat)
# endregion cat random movement