Male_zoo_Projekt_SI/agent.py

84 lines
3.4 KiB
Python

import pygame
from state_space_search import is_border, is_obstacle
class Agent:
def __init__(self, istate, image_path, grid_size):
self.istate = istate
self.x, self.y, self.direction = istate
self.grid_size = grid_size
self.image= pygame.image.load(image_path)
self.image = pygame.transform.scale(self.image, (grid_size, grid_size))
self._food = 0
def draw(self, screen, grid_size):
# Obróć obrazek zgodnie z kierunkiem
if self.direction == 'E':
self.image= pygame.image.load('images/agent4.png')
elif self.direction == 'S':
self.image= pygame.image.load('images/agent1.png')
elif self.direction == 'W':
self.image= pygame.image.load('images/agent3.png')
else: # direction == 'N'
self.image= pygame.image.load('images/agent2.png')
self.image = pygame.transform.scale(self.image, (grid_size, grid_size))
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):
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)
def move(self, action, max_x, max_y, obstacles, animals, goal):
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]
self.istate = (self.x, self.y, self.direction)
feed_animal(self, animals, goal)
take_food(self)
def feed_animal(self, animals, goal):
goal_x, goal_y = goal
if self.x == goal_x and self.y == goal_y:
for animal in animals:
if animal.x == goal_x and animal.y == goal_y:
if animal.getting_hungry() < self._food :
self._food -= animal._feed
animal._feed = 0
print(animal.name, "fed with", animal.food)
print("Current food level: ", self._food)
else:
animal._feed -= self._food
self._food = 0
print(animal.name, "fed with", animal.food)
print("Current food level: ", self._food)
def take_food(self):
house_x = 3
house_y = 1
if self.x == house_x and self.y == house_y:
if self._food == 0:
self._food = 25
print("Agent took food and current food level is", self._food)