-
Notifications
You must be signed in to change notification settings - Fork 0
/
position.py
124 lines (97 loc) · 2.73 KB
/
position.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from enum import Enum
class Direction(Enum):
North = 1
South = 2
East = 4
West = 8
NorthEast = 5
NorthWest = 9
SouthEast = 6
SouthWest = 10
class Position:
""" Defines a position object
"""
def __init__(self, row, col):
self.row = row
self.col = col
def __repr__(self):
return "%s(row=%i, col=%i)" % (self.__class__.__name__, self.row, self.col)
def __eq__(self, other):
return self.row == other.row and self.col == other.col
def __lt__(self, other):
return self.row < other.row or (self.row == other.row and self.col < other.col)
def __hash__(self):
return hash((self.row, self.col))
# N, S, W, E properties to get relative positions
@property
def North(self):
"""
:return: A Position north of this one
"""
return Position(self.row - 1, self.col)
@property
def South(self):
"""
:return: A Position south of this one
"""
return Position(self.row + 1, self.col)
@property
def East(self):
"""
:return: A Position east of this one
"""
return Position(self.row, self.col - 1)
@property
def West(self):
"""
:return: A Position west of this one
"""
return Position(self.row, self.col + 1)
@property
def NorthEast(self):
return self.North.East
@property
def SouthEast(self):
return self.South.East
@property
def NorthWest(self):
return self.North.West
@property
def SouthWest(self):
return self.South.West
# Short forms are functions, so they can be lazy ;-)
def N(self):
return self.North
def S(self):
return self.South
def E(self):
return self.East
def W(self):
return self.West
def NE(self):
return self.NorthEast
def NW(self):
return self.NorthWest
def SE(self):
return self.SouthEast
def SW(self):
return self.SouthWest
# Generic function which accept direction as a paremeter
def go(self, direction):
""" Returns a new position going in one of the 8 directions
:param direction: a Direction.{N,S,W,E...} instance
:return: the new Position
"""
assert isinstance(direction, Direction)
return {
Direction.North: self.N,
Direction.South: self.S,
Direction.East: self.E,
Direction.West: self.W,
Direction.NorthEast: self.NE,
Direction.NorthWest: self.NW,
Direction.SouthEast: self.SE,
Direction.SouthWest: self.SW
}[direction]()