positionals.py
1 from . import commands 2 3 4 class Direction: 5 """ 6 Holds positional tuples in relation to cardinal directions 7 """ 8 North = (0, -1) 9 South = (0, 1) 10 East = (1, 0) 11 West = (-1, 0) 12 13 Still = (0, 0) 14 15 @staticmethod 16 def get_all_cardinals(): 17 """ 18 Returns all contained items in each cardinal 19 :return: An array of cardinals 20 """ 21 return [Direction.North, Direction.South, Direction.East, Direction.West] 22 23 @staticmethod 24 def convert(direction): 25 """ 26 Converts from this direction tuple notation to the engine's string notation 27 :param direction: the direction in this notation 28 :return: The character equivalent for the game engine 29 """ 30 if direction == Direction.North: 31 return commands.NORTH 32 if direction == Direction.South: 33 return commands.SOUTH 34 if direction == Direction.East: 35 return commands.EAST 36 if direction == Direction.West: 37 return commands.WEST 38 if direction == Direction.Still: 39 return commands.STAY_STILL 40 else: 41 raise IndexError 42 43 @staticmethod 44 def invert(direction): 45 """ 46 Returns the opposite cardinal direction given a direction 47 :param direction: The input direction 48 :return: The opposite direction 49 """ 50 if direction == Direction.North: 51 return Direction.South 52 if direction == Direction.South: 53 return Direction.North 54 if direction == Direction.East: 55 return Direction.West 56 if direction == Direction.West: 57 return Direction.East 58 if direction == Direction.Still: 59 return Direction.Still 60 else: 61 raise IndexError 62 63 64 class Position: 65 def __init__(self, x, y): 66 self.x = x 67 self.y = y 68 69 def directional_offset(self, direction): 70 """ 71 Returns the position considering a Direction cardinal tuple 72 :param direction: the direction cardinal tuple 73 :return: a new position moved in that direction 74 """ 75 return self + Position(*direction) 76 77 def get_surrounding_cardinals(self): 78 """ 79 :return: Returns a list of all positions around this specific position in each cardinal direction 80 """ 81 return [self.directional_offset(current_direction) for current_direction in Direction.get_all_cardinals()] 82 83 def __add__(self, other): 84 return Position(self.x + other.x, self.y + other.y) 85 86 def __sub__(self, other): 87 return Position(self.x - other.x, self.y - other.y) 88 89 def __iadd__(self, other): 90 self.x += other.x 91 self.y += other.y 92 return self 93 94 def __isub__(self, other): 95 self.x -= other.x 96 self.y -= other.y 97 return self 98 99 def __abs__(self): 100 return Position(abs(self.x), abs(self.y)) 101 102 def __eq__(self, other): 103 return self.x == other.x and self.y == other.y 104 105 def __ne__(self, other): 106 return not self.__eq__(other) 107 108 def __repr__(self): 109 return "{}({}, {})".format(self.__class__.__name__, 110 self.x, 111 self.y)