import random import geometry as geo def doubles(lista): """returns all elements in the list that appear at least twice""" def intersection(lista, listb): """ returns a list of elements common to both lists. Used to find collisions between robots and heaps. """ result = [] for element in lista: if element in listb: result.append(element) return result class Location: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y def __str__(self): return "({} {})".format(self.x, self.y) def generate_random_locality(geometry): return Location(random.randint(0, geometry.width-1), random.randint(0, geometry.height-1)) def update_location(self, direction, geometry): if direction.code == 'N': self.y = min(geometry.height-1, self.y+1) elif direction.code == 'E': self.x = min(geometry.width-1, self.x+1) elif direction.code == 'S': self.y = max(0, self.y-1) elif direction.code == 'W': self.x = max(0, self.x-1) elif direction.code == 'NE': self.y = min(geometry.height-1, self.y+1) self.x = min(geometry.width-1, self.x+1) elif direction.code == 'NW': self.y = min(geometry.height-1, self.y+1) self.x = max(0, self.x-1) elif direction.code == 'SE': self.y = max(0, self.y-1) self.x = min(geometry.width-1, self.x+1) elif direction.code == 'SW': self.y = max(0, self.y-1) self.x = max(0, self.x-1) elif direction.code == '0': pass else: raise ValueError def get(self): return self.x, self.y class Direction: codes = {'N', 'W', 'E', 'S', 'NW', 'NE', 'SW', 'SE', '0'} def __init__(self, code): if code in Direction.codes: self.code = code else: raise ValueError def __str__(self): return "Direction {}".format(self.code) def move_towards(mover, aim): """determines a robot location mover towards an avatar location aim robots now move diagonally """ if mover.x < aim.x and mover.yaim.y: return Direction('SE') elif mover.x==aim.x and mover.yaim.y: return Direction('S') elif mover.x>aim.x and mover.yaim.x and mover.y==aim.y: return Direction('W') elif mover.x>aim.x and mover.y>aim.y: return Direction('SW') class Avatar: def __init__(self, location): self.location = location def __str__(self): return "Avatar at {}".format(self.location) def move(self, direction, geometry): self.location.update_location(direction, geometry) class Robot: def __init__(self, location): self.location = location def __str__(self): return "Robot at {}".format(self.location) def move(self, avatar, geometry): direction = Direction.move_towards(self.location, avatar.location) self.location.update_location(direction, geometry) class Heap: def __init__(self, location): self.location = location def __str__(self): return "Heap {}".format(self.location) class Model: def __init__(self, geometry, nrrobots): self.geometry = geometry self.heaps = [] self.avatar = Avatar(Location.generate_random_locality(geometry)) self.robots = [] while len(self.robots)