-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
244 lines (214 loc) · 9.06 KB
/
models.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/python3
import colorama
import random
import time
import utils
colorama.init()
class Meta(type):
def __repr__(cls):
return cls.__name__
class Move(object):
__metaclass__ = Meta
def __init__(self, title: str, side: int, audio: str, time: int, *moves, **kwargs):
"""Creates a Move. Arguments are: title,
side (-1 for left, 0 for None, 1 for Right)
audio (for espeak), and time (in seconds)"""
self.title = title
self.side = side
self.audio = audio
self.time = max(time, 0)
self.last = None
self.nextMove = set(moves)
for k, v in kwargs.items():
setattr(self, k, v)
if "lateMove" not in kwargs:
self.lateMove = set()
if "extended_time" not in kwargs:
self.extended_time = []
@property
def times(self):
return [self.time] + self.extended_time
@times.setter
def times(self, args):
args = sorted(args)
self.time = max(args[0], 0)
self.extended_time = [max(0, i) for i in args[1:]]
def updateKwargs(self, **kwargs) -> None:
for k, v in kwargs.items():
setattr(self, k, v)
def addMove(self, *moves) -> None:
self.nextMove.update(moves)
def removeMove(self, *moves) -> None:
self.nextMove.difference_update(moves)
self.lateMove.difference_update(moves)
def addLateMove(self, *moves) -> None:
self.lateMove.update(moves)
self.lateMove.difference_update(self.nextMove)
def notLast(self, prev=None) -> "Move":
"""Returns a move, trying to avoid
both self.last and the N moves
previously called."""
if self.last and len(self.nextMove) > 1:
movesCopy = self.nextMove.copy()
try:
movesCopy.remove(self.side)
if len(movesCopy) == 1: return s.pop()
movesCopy.remove(self.last)
if len(movesCopy) == 1: return s.pop()
except KeyError:
pass
if prev is not None:
movesCopy = movesCopy.difference(prev)
if movesCopy:
return random.choice(tuple(movesCopy))
if prev is not None:
movesCopy = self.nextMove.intersection(prev)
if movesCopy:
return random.choice(tuple(movesCopy))
if self.nextMove:
return random.choice(tuple(self.nextMove))
if self.lateMove:
c = random.choice(tuple(self.lateMove))
self.promoteLate(c)
return c
raise ValueError("No possible move found")
def promoteLate(self, *args, n=1) -> None:
"""Promotes a late move up to the normal move pool, if possible.
If no move given, promotes a random move"""
if args:
self.nextMove.update(self.lateMove.intersection(args))
self.lateMove.difference_update(args)
elif self.lateMove:
moves = random.sample(tuple(self.lateMove), min(n,len(self.lateMove)))
self.lateMove.difference_update(moves)
self.addMove(*moves)
def repCount(self) -> None:
if getattr(self, 'countReps', None):
utils.speak("How many reps?")
return input("How many reps? ")
def __call__(self, imbalance=[], prev=None, verbose=1, **kwargs) -> "Move":
"""Tells me which pose I'm supposed to do and how I'm supposed to do it.
Also figures out next pose and deals with adding late moves"""
print("\n" + colorama.Style.BRIGHT + self.title + colorama.Style.NORMAL)
# Deal with imbalances
if self.side:
if self in imbalance: imbalance.remove(self)
else: imbalance.append(self.otherside)
if verbose >= 2:
print(colorama.Fore.BLUE + utils.wrapper.fill('Prev: ' + '; '.join(map(str, prev))))
print(colorama.Fore.MAGENTA + utils.wrapper.fill('Imbalances (%d): %s' % (len(imbalance), '; '.join(map(str,imbalance))))\
+ colorama.Fore.RESET)
if prev is not None: prev.append(self)
# What is my next move?
if 'nextMove' in kwargs:
# Assume the caller knows what they're doing right now.
# Should possibly assert that nextMove is a plausible nextMove
nextMove = kwargs['nextMove']
self.promoteLate(nextMove)
else:
for i in imbalance:
if i in self.nextMove:
nextMove = i
break
else:
nextMove = self.notLast(prev)
if nextMove is not None:
print('Next Move: ' + nextMove.title)
self.last = nextMove
if verbose >= 1:
print(colorama.Fore.CYAN + utils.wrapper.fill('My options were: ' + '; '.join(str(i) for i in self.nextMove)))
print(colorama.Fore.GREEN + utils.wrapper.fill('Latemoves: ' + '; '.join(str(i) for i in self.lateMove)) + colorama.Fore.RESET)
# Tell me what to do
utils.speak(self.audio)
time.sleep(0.3)
for i in ('early', 'harder'):
if i in kwargs and kwargs[i]: utils.speak(getattr(self, i, None))
# How long am I supposed to do it?
if 'time' in kwargs: t = kwargs['time']
elif 'extended' in kwargs and kwargs['extended'] and self.extended_time: t = random.choice(self.extended_time)
else: t = self.time
# Actually count down
if getattr(self, 'bind', None): utils.speak("Bind if you want to")
if t > 5: utils.speak(str(t) + " seconds")
if getattr(self, 'countdown', None): utils.countdown(t, incremental=True)
else: utils.countdown(t)
#record to file, if we were given a file
if 'f' in kwargs and kwargs['f']:
kwargs['f'].write('%s: %d' % (self.title, t))
s = self.repCount()
if s: kwargs['f'].write(' - %s reps' % s)
kwargs['f'].write('\n')
kwargs['f'].flush()
if getattr(self, 'bind', None): utils.speak('Release bind')
self.promoteLate() # Add in options for harder followup moves next time
return nextMove
def __repr__(self):
return 'Move(%s)' % self.title
def __str__(self):
return self.title
def __unicode__(self):
return self.title
def __hash__(self):
return hash(self.title)
def __eq__(self, other):
if not isinstance(other, Move): return False
return self.title == other.title
def __ne__(self, other):
if not isinstance(other, Move): return True
return self.title != other.title
def __lt__(self, other):
if not isinstance(other, Move): raise TypeError("Unorderable types: Move() <= " + str(type(other)))
return self.title < other.title
def __contains__(self, other):
if other in self.nextMove: return True
if other in self.lateMove: return True
return False
def __len__(self):
return len(self.nextMove.union(self.lateMove))
def __iter__(self):
yield from self.nextMove.union(self.lateMove)
@classmethod
def twoSides(cls, title : str , audio : str , time : int , *args, **kwargs):
"""Hey, you have two legs. Convenience method to generate both left and right sides for a move"""
dicR = {"same": "Right", "other": "Left"}
dicL = {"same": "Left", "other": "Right"}
if "%" in audio:
R = cls(title + ", Right", 1, audio % dicR, time, *args, **kwargs)
L = cls(title + ", Left", -1, audio % dicL, time, *args, **kwargs)
else:
R = cls(title + ", Right", 1, audio, time, *args, **kwargs)
L = cls(title + ", Left", -1, audio, time, *args, **kwargs)
R.otherside = L
L.otherside = R
return (R,L)
@classmethod
def doubleAdd(cls, move, *moves, inverted=False, late=False):
"""Convenience method to help link moves that have sides
inverted: if True, causes L to be linked to R and R to be linked to L
late: if True, causes move to be linked as a late move"""
f = cls.addLateMove if late else cls.addMove
if inverted:
f(move[0], *[i[1] for i in moves])
f(move[1], *[i[0] for i in moves])
else:
f(move[0], *[i[0] for i in moves])
f(move[1], *[i[1] for i in moves])
@staticmethod
def doubleAssignLast(move, lastmove, inverted = False):
"""Convience method to 'fake' the last move for side-specific moves"""
if inverted:
move[0].last = lastmove[1]
move[1].last = lastmove[0]
else:
move[0].last = lastmove[0]
move[1].last = lastmove[1]
@classmethod
def moveReverse(cls, *moves, late=False):
"""Convenience method. Link a move to its .otherside, and also in reverse."""
f = cls.addLateMove if late else cls.addMove
for i in moves:
f(i[0],i[1])
f(i[1],i[0])
@staticmethod
def reDifficultyTimes(li, val, difficulty):
return [max(i + val*difficulty,0) for i in li]