-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkid.py
391 lines (353 loc) · 11.6 KB
/
kid.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
from place import *
class KidDeath(Exception):
pass
class Kid:
def superimposeOnTileImage(self, block: list):
block[-2]=[0,0,4,4,0,0]
block[-3]=[0,0,4,4,0,0]
block[-4]=[0,0,4,4,0,0]
block[-5]=[0,0,4,4,0,0]
block[-4][1 if self.direction==LEFT else 4]=4
hasSword=False
def getNextPlaceOrDie(self,place: Place,direction):
newPlace=place.getNextPlace(direction)
if not newPlace:
self.die()
return newPlace
def __init__(self,levelNumber):
self.alive=True
self.healthPoints=3
self.possibleHealthPoints=3
self.loadLevel(levelNumber)
def printHealth(self):
if self.alive:
print("Health points: %d of %d"%(self.healthPoints,self.possibleHealthPoints))
else:
print("Dead")
def increasePossibleHealthPoints(self,points):
self.possibleHealthPoints+=points
self.healthPoints=self.possibleHealthPoints
self.printHealth()
def changeHealthPoints(self,points):
points=min(points,self.possibleHealthPoints-self.healthPoints)
self.healthPoints+=points
if points>0:
print("Gained %d health points"%points)
elif points<0:
print("Lost %d health points"%abs(points))
if self.healthPoints<=0:
self.die()
self.printHealth()
def pickUpItem(self):
t=self.place.tile
if isinstance(t,Tile_item):
t.take()
print("took "+t.name)
t.affectKid(self)
else:
print("Nothing to take")
def printPlace(self,place=None,includeAbove=True):
if not place:
place=self.place
msg=""
if place.guard:
msg+="guard, "
if place.tile.isEmpty:
bottom,floorCount=place.tile.findBottom()
edge, distance = place.tile.findClosestEdge(self.direction)
dropWidthLabel = ""
if edge.tile.isFloor:
if distance == 1:
dropWidthLabel = "narrow"
elif distance == 2:
dropWidthLabel = "wide"
bottomLabel = bottom.description if bottom else "abis"
dropMessage = f"{dropWidthLabel} {floorCount} story drop to {bottomLabel} below".strip()
msg+=dropMessage
else:
msg+=place.description
if includeAbove:
above=place.getNextPlace(UP)
if above:
if not above.tile.isEmpty:
edge=None
roofName=above.tile.roofName
if above.hasClearDirection(oppositeDirections[self.direction]):
edge="starts"
elif above.hasClearDirection(self.direction):
edge="ends"
if edge and isinstance(above.tile,Tile_floor):
roofName=Tile_floor.name
msg+=", %s above"%roofName
if edge:
msg+=" %s"%edge
if type(above.tile) is not Tile_floor and not isinstance(above.tile,Tile_wall):
msg+=" with %s"%above.description
print(msg)
def printAhead(self):
ahead=self.place.getNextPlace(self.direction)
if ahead:
print("Ahead: ", end=' ')
self.printPlace(place=ahead)
if ahead.tile.isEmpty:
furtherAhead, distance = ahead.tile.findClosestEdge(self.direction)
if distance < 3 and furtherAhead.tile.isFloor:
print("Further ahead: ", end=' ')
self.printPlace(place=furtherAhead, includeAbove=False)
def printDirection(self):
print("Facing %s"%directionLabels[self.direction])
def exit(self):
if isinstance(self.place.tile,Tile_exit):
if self.place.tile.isOpen:
print("Walking through Exit")
raise LevelExit
else:
print("Exit is closed")
else:
print("Not at exit")
def die(self):
self.alive=False
print("Dead")
raise KidDeath
def touchPlace(self,vMomentum,hMomentum,continuing=False,grab=None):
if self.place.tile.isEmpty:
self.doPossibleFall(grab=grab)
return
if vMomentum>0:
print("Landed on ", end=' ')
self.printPlace()
self.doPossibleHarm(vMomentum,hMomentum)
self.place.tile.touch()
if self.place.tile.isEmpty and not continuing:
return self.doPossibleFall(grab=grab is not False)
if not continuing:
self.printAhead()
def doPossibleHarm(self,vMomentum,hMomentum):
if self.place.guard:
print("(Hit by guard)")
self.die()
if self.place.tile.willKillActer(vMomentum,hMomentum):
self.die()
elif self.place.tile.willHarmActer(vMomentum,hMomentum):
self.changeHealthPoints(-1)
def doPossibleGrab(self):
newPlace=self.place.getNextPlace(self.direction)
if not newPlace or not newPlace.tile.isFloor:
return False
self.place=newPlace
print("grabbed onto ledge on %s and climbed up"%directionLabels[self.direction])
self.touchPlace(0,1,grab=False)
return True
def doPossibleFall(self,grab=False):
floorCount=0
place = self.place
while place and place.tile.isEmpty:
if grab and floorCount<2 and self.doPossibleGrab():
return True
place=place.getNextPlace(DOWN)
floorCount+=1
if floorCount>0:
print(f"(Fell down {floorCount} stories)")
if not place:
self.die()
self.place = place
self.touchPlace(floorCount,0)
return floorCount>0
def step(self,grab=None):
newPlace=self.getNextPlaceOrDie(self.place,self.direction)
if newPlace.tile.isWall:
print("Can't go that way - ahead: ", end=' ')
self.printPlace(place=newPlace,includeAbove=False)
return
self.place=newPlace
self.touchPlace(0,1,grab=grab)
def _walkRun(self,maxPlaces,stopAtName,run=False):
minPlaces=2 if run else 1
placeCount=0
floorCount=0
msg="Running" if run else "Walking"
if maxPlaces is not None:
msg+=" %s %d places"%(directionLabels[self.direction],maxPlaces)
else:
msg+=" %s"%directionLabels[self.direction]
maxPlaces=LROOMS*PLACES
if stopAtName:
msg+=" until at %s"%stopAtName
print(msg+":")
continuing=True
hMomentum=2
while continuing or placeCount<minPlaces:
newPlace=self.getNextPlaceOrDie(self.place,self.direction)
if newPlace.tile.isWall:
print("Can't go that way - ahead: ", end=' ')
self.printPlace(place=newPlace,includeAbove=False)
break
self.place=newPlace
placeCount+=1
print("%s: "%placeCount, end=' ')
continuing=placeCount<maxPlaces
if continuing:
if stopAtName:
if stopAtName=="edge" and self.place.hasClearDirection(self.direction):
continuing=False
elif self.place.isNameMatch(stopAtName):
continuing=False
if continuing and placeCount>=1:
nextPlace=self.place.getNextPlace(self.direction)
if nextPlace and nextPlace.tile.isWall:
continuing=False
elif not run and (not nextPlace or nextPlace.tile.isEmpty):
continuing=False
oldHealthPoints=self.healthPoints
oldFloor=self.place.floorNum
self.touchPlace(0,hMomentum,continuing=continuing)
if self.healthPoints!=oldHealthPoints or self.place.floorNum!=oldFloor:
break
def walk(self,maxPlaces=None,stopAtName=None):
self._walkRun(maxPlaces,stopAtName)
def run(self,maxPlaces=None,stopAtName=None):
self._walkRun(maxPlaces,stopAtName,run=True)
def killGuard(self):
nextPlace=self.place.getNextPlace(self.direction)
if not nextPlace or not nextPlace.guard:
print("No guard to kill")
elif not self.hasSword:
print("Nothing to kill guard with")
else:
nextPlace.guard.kill()
def climbDown(self):
backDirection=oppositeDirections[self.direction]
newPlace=self.place.getNextPlace(backDirection)
if not newPlace or not newPlace.tile.isEmpty:
print("No drop behind")
return False
self.place=self.getNextPlaceOrDie(newPlace,DOWN)
print("Climbing down backwards on %s"%directionLabels[backDirection])
if self.place.tile.isEmpty:
newPlace=self.place.getNextPlace(self.direction)
if newPlace and not newPlace.tile.isWall:
self.place=newPlace
print("Swung in underneath")
self.touchPlace(1,0)
return True
def climbUp(self):
if isinstance(self.place.tile,Tile_exit):
if self.place.tile.isOpen:
print("Walking through Exit")
raise LevelExit
else:
print("Exit is closed")
above=self.place.getNextPlace(UP)
if not above:
print("Nothing to climb up to")
return False
elif above.tile.isEmpty:
aheadAbove=above.getNextPlace(self.direction)
if aheadAbove.tile.isFloor:
if not aheadAbove.tile.isWall:
self.place=aheadAbove
print("climbed up to ledge on %s"%directionLabels[self.direction])
self.touchPlace(0,0)
return True
print("Blocked by %s"%aheadAbove.description)
return False
print("Nothing to climb up to")
return False
elif isinstance(above.tile,Tile_looseBoard):
print("Bumped loose board")
above.tile.touch()
self.changeHealthPoints(-1)
return False
elif not above.tile.isWall and above.hasClearDirection(oppositeDirections[self.direction]):
behind=self.place.getNextPlace(oppositeDirections[self.direction])
if not behind or behind.tile.isWall:
print("bumped roof")
aheadAbove=above.getNextPlace(self.direction)
if aheadAbove and isinstance(aheadAbove.tile,Tile_looseBoard):
print("Bumped loose board in roof ahead")
aheadAbove.tile.touch()
return False
self.place=above
print("Climbed up to ledge directly above")
self.touchPlace(0,0)
return True
print("bumped roof")
aheadAbove=above.getNextPlace(self.direction)
if aheadAbove and isinstance(aheadAbove.tile,Tile_looseBoard):
print("Bumped loose board in roof ahead")
aheadAbove.tile.touch()
return False
def turn(self):
self._faceDirection(oppositeDirections[self.direction])
def turnLeft(self):
return self._faceDirection(LEFT)
def turnRight(self):
return self._faceDirection(RIGHT)
def _faceDirection(self,direction):
if self.direction!=direction:
self.direction=direction
self.printDirection()
self.printAhead()
return True
return False
def leap(self,large=False,grab=False):
print("leaping %s"%directionLabels[self.direction])
places=2 if large else 1
placeCount=0
while placeCount<places:
newPlace=self.getNextPlaceOrDie(self.place,self.direction)
if newPlace.guard:
print("(Hit by guard)")
self.die()
if newPlace.tile.isWall:
print("Hit "+newPlace.description)
if placeCount>0:
self.touchPlace(1,1,grab=grab)
return False
self.place=newPlace
print(self.place.tile.passVerb+" "+self.place.tile.name)
placeCount+=1
newPlace=self.getNextPlaceOrDie(self.place,self.direction)
if newPlace.tile.isWall:
print("Hit "+newPlace.description)
else:
self.place=newPlace
self.touchPlace(1,1,grab=grab)
return True
@classmethod
def loadFromRestorePoint(cls,saveState):
import pickle as pickle
kid=pickle.loads(saveState)
if not isinstance(kid,cls):
raise ValueError("file was not a Kid")
return kid
@classmethod
def loadFromFile(cls,path):
with open(path,'rb') as f:
s=f.read()
return cls.loadFromRestorePoint(s)
def _createRestorePoint(self):
import pickle as pickle
return pickle.dumps(self)
def saveToFile(self,path):
with open(path,"wb") as f:
s=self._createRestorePoint()
f.write(s)
def loadLevel(self,levelNumber):
level=Level(levelNumber)
roomNum = level.start_position[0]-1
room = Room(level, roomNum)
floorNum = level.start_position[1]/PLACES
placeNum = level.start_position[1]%PLACES
self.place=Place(room,floorNum,placeNum)
self.hasSword=True if self.place.level.levelNumber>1 else False
self.direction=RIGHT if level.start_position[2] else LEFT
self.lastRestorePoint=self._createRestorePoint()
def loadNextLevel(self):
self.loadLevel(self.place.level.levelNumber+1)
def printWhere(self):
levelNum = self.place.level.levelNumber
roomNum = self.place.room.roomNum + 1
floorNum = self.place.floorNum + 1
placeNum = self.place.placeNum + 1
print(f"Level {levelNum}, room {roomNum}, floor {floorNum}, place {placeNum}")