Male_zoo_Projekt_SI/agent.py

67 lines
2.7 KiB
Python
Raw Normal View History

2024-03-22 16:59:39 +01:00
import pygame
from state_space_search import is_border, is_obstacle
2024-03-23 13:55:16 +01:00
2024-03-22 16:59:39 +01:00
class Agent:
def __init__(self, istate, image_path, grid_size):
self.istate = istate
self.x, self.y, self.direction = istate
2024-03-22 16:59:39 +01:00
self.grid_size = grid_size
self.image_original = pygame.image.load(image_path)
self.image_original = pygame.transform.scale(self.image_original, (grid_size, grid_size))
self.image = self.image_original
2024-03-22 16:59:39 +01:00
def draw(self, screen):
# Obróć obrazek zgodnie z kierunkiem
if self.direction == 'E':
self.image = pygame.transform.rotate(self.image_original, -90)
elif self.direction == 'S':
self.image = pygame.transform.rotate(self.image_original, 180)
elif self.direction == 'W':
self.image = pygame.transform.rotate(self.image_original, 90)
else: # direction == 'N'
self.image = self.image_original
2024-03-22 16:59:39 +01:00
screen.blit(self.image, (self.x * self.grid_size, self.y * self.grid_size))
def handle_event(self, event, max_x, max_y, animals, obstacles):
2024-03-22 16:59:39 +01:00
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.move('Go Forward', max_x, max_y, obstacles, animals)
elif event.key == pygame.K_LEFT:
self.move('Turn Left', max_x, max_y, obstacles, animals)
elif event.key == pygame.K_RIGHT:
self.move('Turn Right', max_x, max_y, obstacles, animals)
2024-03-22 16:59:39 +01:00
feed_animal(self, animals)
def move(self, action, max_x, max_y, obstacles, animals):
if action == 'Go Forward':
new_x, new_y = self.x, self.y
if self.direction == 'N':
new_y -= 1
elif self.direction == 'E':
new_x += 1
elif self.direction == 'S':
new_y += 1
elif self.direction == 'W':
new_x -= 1
# Sprawdź, czy nowe położenie mieści się w granicach kraty i nie jest przeszkodą
if is_border(new_x, new_y, max_x, max_y) and not(is_obstacle(new_x, new_y, obstacles)):
self.x, self.y = new_x, new_y
elif action == 'Turn Left':
self.direction = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}[self.direction]
elif action == 'Turn Right':
self.direction = {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}[self.direction]
feed_animal(self, animals)
def feed_animal(self, animals):
for animal in animals:
if self.x == animal.x and self.y == animal.y:
if animal.feed() == 'True':
animal._feed = 0
print(animal.name, "fed with", animal.food)