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
|
# Copyright (C) 2009, 2010 Roman Zimbelmann <romanz@lavabit.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Directions provide convenience methods for movement operations.
Direction objects are handled just like dicts but provide
methods like up() and down() which give you the correct value
for the vertical direction, even if only the "up" or "down" key
has been defined.
Example application:
d = Direction(down=5)
print(d.up()) # prints -5
print(bool(d.horizontal())) # False, since no horizontal direction is defined
"""
class Direction(dict):
__doc__ = __doc__ # for nicer pydoc
def __init__(self, dictionary=None, **keywords):
if dictionary is not None:
dict.__init__(self, dictionary)
else:
dict.__init__(self, keywords)
if 'to' in self:
self['down'] = self['to']
self['absolute'] = True
def copy(self):
return Direction(**self)
def _get_bool(self, first, second, fallback=None):
try: return self[first]
except:
try: return not self[second]
except: return fallback
def _get_direction(self, first, second, fallback=0):
try: return self[first]
except:
try: return -self[second]
except: return fallback
def up(self):
return -Direction.down(self)
def down(self):
return Direction._get_direction(self, 'down', 'up')
def right(self):
return Direction._get_direction(self, 'right', 'left')
def absolute(self):
return Direction._get_bool(self, 'absolute', 'relative')
def left(self):
return -Direction.right(self)
def relative(self):
return not Direction.absolute(self)
def vertical(self):
return set(self) & set(['up', 'down'])
def horizontal(self):
return set(self) & set(['left', 'right'])
def multiply(self, n):
for key in ('up', 'right', 'down', 'left'):
try:
self[key] *= n
except:
pass
def set(self, n):
for key in ('up', 'right', 'down', 'left'):
if key in self:
self[key] = n
|