/
dude.py
697 lines (577 loc) · 24.1 KB
/
dude.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
"""
Contains the Dude class, which is a generic creature, and its children.
All players and monsters should be derived from Dude.
"""
import sys
import copy
import collections
import tcod_display as display
import exc
import rng
import config
import symbol
import level
import fixedobj
import action
import coordinates
import fov
import pf
import cond
import kb
kp = kb.kp
import log
"""
Legal monster tags:
"proper_noun": this monster's name is a proper noun.
"two_square_thrower": this monster has a projectile thrown two squares forward
onto an empty or occupied space.
"bug_monster": this monster should only be generated when a bug has occurred
(i.e. there is no "real" monster available).
"do_not_naturally_generate": this monster should never be naturally generated.
"""
class ais:
"""
A glorified enum of AI states.
"""
(FIGHTING, # The monster sees an enemy.
TRAVELING, # The monster is traveling to a specific square.
WANDERING, # The monster is moving, but not to a specific square.
RESTING, # The monster is not moving.
) = range(4)
class qt:
"""
A glorified enum of types of things which take turns.
"""
(PLAYER,
MONSTER,
EVENT,
) = range(3)
class Dude(fixedobj.FixedObject):
"""
A generic creature; all players and monsters come from Dudes.
The Dude class should not be instantiated as is; it exists only to have
other classes derived from it.
"""
def __init__(self, coords = (0, 0), glyph = symbol.BAD_GLYPH,
speed = 72, max_HP = 2, currentLevel = None, name = "Unnamed",
attack = 1, defense = 0, tags = None, char_level = 1,
passableTerrain = level.PASSABLE_TERRAIN):
fixedobj.FixedObject.__init__(self, coords, glyph, currentLevel)
self.name = name
self.speed = speed
self.passableTerrain = passableTerrain
self.max_HP = max_HP
self.cur_HP = self.max_HP
self.attack = attack
self.defense = defense
self.char_level = char_level
self.tags = tags if tags is not None else []
self.fov = fov.fov()
self.conditions = {} # a dict whose keys are condition names,
# and whose values are the conditions themselves
def __str__(self):
return "%d:%s (S:%d, %d/%d) (%d,%d)" % (self.ID, self.name, self.speed, self.cur_HP, self.max_HP, self.coords[0], self.coords[1])
def act(self):
raise NotImplementedError("Only implemented by Dude's children.")
def getAction(self):
"""
Return an Action that represents what the dude is going to do.
"""
raise NotImplementedError("Only implemented by Dude's children.")
def getName(self, commonNounPreceder = "the"):
"""
Returns the dude's name, preceding it with commonNounPreceder.
commonNounPreceder is ignored if the dude contains the proper_noun tag.
Note that commonNounPreceder and the name itself are separated by a
space. If commonNounPreceder is "a", "an" will be substituted where
appropriate.
"""
if "proper_noun" in self.tags:
return self.name
else:
if commonNounPreceder == "a" and self.name.startswith(("a", "e", "i", "o", "u")):
return "an" + " " + self.name
else:
return str(commonNounPreceder) + " " + self.name
def getCurGlyph(self):
"""
Get the glyph that currently represents the dude.
This may be different from its "base" glyph, which is dude.glyph.
"""
ret_glyph = copy.copy(self.glyph)
for condition in self.conditions.values():
ret_glyph = condition.modifyGlyph(ret_glyph)
return ret_glyph
def getType(self):
"""
Get the type of queueable thing this dude is.
"""
raise NotImplementedError("Only implemented in Dude's children.")
def canMove(self, moveCoords):
"""
Returns True if a move to moveCoords is possible; false otherwise.
"""
return self.currentLevel.canMove(self, moveCoords)
def possibleMoves(self):
"""
Return a list of the possible moves from the current location.
"""
adjacent_coords = coordinates.adjacent_coords(self.coords)
return [x for x in adjacent_coords if self.canMove(x)]
def canPass(self, dungeonGlyph):
return dungeonGlyph in self.passableTerrain
def isDead(self):
"""
Returns True if HP <= 0, or if the dude is dead for some other reason.
"""
return self.cur_HP <= 0
def checkDeath(self):
"""If dead, die."""
if self.isDead():
self.die()
def isPlayer(self):
"""Returns True if this Dude is the player, False otherwise."""
return self.getType() == qt.PLAYER
def setHP(self, newHP):
"""
Set the dude's HP to newHP or to its max_HP, whichever is lower.
"""
if newHP > self.max_HP:
self.cur_HP = self.max_HP
else:
self.cur_HP = newHP
def resetFOV(self):
"""
Reset the dude's field of view, determined by its current level and
its coordinates.
"""
self.fov.recalculate(self.currentLevel, self.coords)
def giveCondition(self, condition):
"""
Apply a new condition to the Dude.
"""
if condition.name in self.conditions:
self.removeCondition(condition.name)
self.conditions[condition.name] = condition
condition.apply(self)
# Many conditions change the dude's glyph.
self.currentLevel.refreshDudeGlyph(self)
def removeCondition(self, condition_name):
"""
Remove a condition from the dude of the name "condition_name".
"""
if condition_name in self.conditions:
self.conditions[condition_name].cancel(self)
del self.conditions[condition_name]
else:
raise KeyError("This condition, %s, is not found on this monster." % condition_name)
def hasCondition(self, condition_name):
"""
Return True if the Dude has a condition of the name "condition_name".
"""
return condition_name in self.conditions
def updateConditions(self):
"""
Update all of the conditions, and remove them if necessary.
"""
conditions_to_be_removed = []
for condition in self.conditions.values():
condition.passTurn()
if condition.isOver():
conditions_to_be_removed.append(condition)
for condition in conditions_to_be_removed:
self.removeCondition(condition.name)
def getConditionAction(self):
"""
Get an action governed by the Dude's condition, not its decisions.
Return an action if the Dude's conditions are making it take an action.
Return "None" if they are not.
"""
possible_actions = []
for condition in self.conditions.values():
new_action = condition.getAction(self)
if new_action is not None:
possible_actions.append(new_action)
if len(possible_actions) > 0:
return rng.choice(possible_actions)
else:
return None
def exists(self):
return not self.isDead()
class Monster(Dude):
"""
A dude not controlled by the player. Typically an antagonist.
"""
def __init__(self, name, coords, glyph, AICode, speed, max_HP, tags, attack, defense,
spec, specfreq, currentLevel = None):
"""
Create a new monster.
name - the name of the monster.
coords - the coordinates at which the monster currently is.
(5, 9), for instance.
glyph - a one-character string representing the monster, like "d".
AICode - a string representing the Monster's AI - "CLOSE", etc.
speed - just set this to 72 for now.
max_HP - the maximum (and starting) HP of the monster.
tags - any special qualities the monster has.
attack - the monster's attack capability; what percentage of the health
of a player of the same level the monster should take away. An
integer.
defense - what percentage of the damage dealt by the player the monster
should take. An integer; <100 shows resilience, while >100 shows
a faculty for taking much damage.
spec - a string representing the monster's special power, activated on
a regular attack.
specfreq - a string representing how many of the monster's regular
melee attacks should be replaced by a special attack.
"""
Dude.__init__(self, coords, glyph, speed, max_HP, currentLevel, name,
attack, defense, tags, 1)
self.AICode = AICode
self.state = ais.RESTING
self.player_last_location = None
self.spec = spec
self.specfreq = specfreq
def getType(self):
return qt.MONSTER
def act(self):
"""
Asks the monster to take a turn.
Returns: True is the monster has taken a turn via this call,
False otherwise.
"""
self.resetFOV()
cond_action = self.getConditionAction()
if cond_action is None:
cur_action = self.getAction()
else:
cur_action = cond_action
for condition in self.conditions.values():
cur_action = condition.modifyAction(cur_action)
action_succeeded = cur_action.do()
if action_succeeded:
self.updateConditions()
return action_succeeded
def getAction(self):
"""
Calculate the action of a monster. AI code goes here!
"""
# special AI routines for weird monsters
if self.AICode == "STATUE":
return self.statue()
if self.AICode == "WAIT":
return action.Wait(self)
if self.state == ais.FIGHTING:
return self.fighting()
elif self.state == ais.TRAVELING:
return self.traveling()
elif self.state == ais.WANDERING:
return self.wandering()
elif self.state == ais.RESTING:
return self.resting()
else:
assert False, "This monster has some strange, unknown AI state!"
return action.Wait(self)
def fighting(self):
"""
Calculate the action of a monster who sees the player.
"""
if self.currentLevel.player not in self.fov:
if self.player_last_location is not None:
# The player has escaped! Find a likely square where he could have gone.
adjacent_coords = coordinates.adjacent_coords(self.player_last_location)
legal_coords = [i for i in adjacent_coords
if coordinates.legal(i, self.currentLevel.dimensions)]
passable_coords = [i for i in legal_coords
if self.currentLevel.isEmpty(i)]
out_of_vision_coords = \
[i for i in passable_coords if i not in self.fov]
if len(out_of_vision_coords) > 0:
# There is a possible escape route! Pursue!
self.direction = coordinates.subtract(
rng.choice(out_of_vision_coords),
self.player_last_location)
self.path = pf.find_shortest_path(self.currentLevel,
self.coords, self.player_last_location, False)
if self.path == []:
# There is no route to the player's escape route. Wait, but stay in
# state FIGHTING so as to take advantage of any route that opens up.
return action.Wait(self)
self.state = ais.TRAVELING
return self.traveling()
else:
# There is no possible escape route; give up and rest.
self.state = ais.RESTING
return self.resting()
else:
assert False
else:
self.player_last_location = self.currentLevel.player.coords
if self.AICode == "CLOSE":
return self.closeToPlayer()
elif self.AICode == "RANGEDAPPROACH":
return self.rangedApproach()
else:
raise exc.InvalidDataWarning(
"The monster %s has an unknown AICode, %s"
% (self.name, self.AICode))
return action.Wait(self)
assert False
def traveling(self):
"""
Calculate the action of a monster moving to a specific location.
Note that a "path" variable must exist for this to make sense.
"""
# self.path[0] should be the monster's current square.
# self.path[1] should be the square the monster wants to move to.
# self.path[-1] should be the monster's ultimate destination.
assert self.path != None, \
"Despite the monster being in state TRAVELING, the path variable is null."
if self.currentLevel.player in self.fov:
self.state = ais.FIGHTING
return self.fighting()
else:
path_is_invalid = False
if len(self.path) == 0:
assert False # This shouldn't happen!
path_is_invalid = True
elif self.coords != self.path[0]:
# Something has moved the monster since its last turn.
path_is_invalid = True
elif len(self.path) == 1:
# Since self.coords == self.path[0], the monster has reached its destination!
self.state = ais.WANDERING
return self.wandering()
elif not self.canMove(self.path[1]):
path_is_invalid = True
if path_is_invalid:
if len(self.path) == 0:
# If the path is completely empty, something has gone wrong.
assert False
# Just give up and return to being stationary.
self.state = ais.RESTING
return self.resting()
else:
destination = self.path[-1]
self.path = pf.find_shortest_path(self.currentLevel, self.coords, destination, True)
if len(self.path) == 0:
# There simply is no path to the destination!
# Set self.path to only contain the destination, so that next turn, this code
# attempts to find another path.
self.path = [destination]
return action.Wait(self)
elif len(self.path) == 1:
# This should not happen!
assert False
return action.Wait(self)
if self.canMove(self.path[1]):
move_direction = coordinates.subtract(self.path[1], self.coords)
self.path.pop(0)
return action.Move(self, move_direction)
else:
assert False, "The supposedly legal path contains an illegal move!"
return action.Wait(self)
def wandering(self):
"""
Calculate the action of a monster without a specific goal in mind.
"""
if self.currentLevel.player in self.fov:
self.state = ais.FIGHTING
return self.fighting()
assert self.direction is not None
ordered_moves = coordinates.adjacent_coords_sorted(self.coords, self.direction)
possible_moves = [x for x in ordered_moves if self.currentLevel.canMove(self, x)]
if len(possible_moves) == 0:
# You're stuck! Give up, just rest there.
self.state = ais.RESTING
return self.resting()
else:
move_coords = possible_moves[0]
self.direction = coordinates.subtract(move_coords, self.coords)
return action.Move(self, coordinates.subtract(move_coords, self.coords))
assert False
def resting(self):
"""
Return the action of a monster who is just sitting there, doing nothing.
"""
if self.currentLevel.player in self.fov:
self.state = ais.FIGHTING
return self.fighting()
else:
return action.Wait(self)
def closeToPlayer(self):
"""
Pathfind to the player, and attack him if possible.
"""
player_location = self.currentLevel.player.coords
# If adjacent to the player, attack him.
if coordinates.adjacent(player_location, self.coords):
if rng.percentChance(self.specfreq):
return action.SpecialMelee(self,
self.currentLevel.player,
self.spec)
else:
return action.Attack(self, self.currentLevel.player,
"%(SOURCE_NAME)s attacks %(TARGET_NAME)s! (%(DAMAGE)d)")
# Otherwise, pathfind toward him.
else:
path = pf.find_shortest_path(self.currentLevel, self.coords, player_location, False)
if path != []:
move_coords = coordinates.subtract(path[1], path[0])
return action.Move(self, move_coords)
else:
return action.Wait(self)
def rangedApproach(self):
if ("prefer_melee" in self.tags and
coordinates.minimumPath(self.coords,
self.currentLevel.player.coords) == 1):
# If the monster prefers melee and is in melee range, don't do a ranged attack.
return self.closeToPlayer()
ranged_attack = self.probableRangedAttack()
if ranged_attack is not None:
return ranged_attack
else:
return self.closeToPlayer()
def probableRangedAttack(self):
"""
Return an action for a ranged attack on a target if such an attack is
possible. Otherwise, return None.
"""
if "two_square_thrower" in self.tags:
if self.currentLevel.player in self.fov \
and coordinates.minimumPath(self.coords, self.currentLevel.player.coords) in range(1, 4):
possible_directions = ((2,0),(2,2),(0,2),(-2,2),(-2,0),(-2,-2),(0,-2),(2,-2))
possible_targets = [coordinates.add(self.coords, i) for i in possible_directions if self.currentLevel.isEmpty(coordinates.add(self.coords, i))]
visible_targets = [coords for coords in possible_targets if coords in self.fov]
close_targets = [coords for coords in visible_targets if (coordinates.minimumPath(coords, self.currentLevel.player.coords) <= 1)]
actual_targets = [coords for coords in close_targets if coords not in self.currentLevel.dudeLayer]
if len(actual_targets) == 0:
return None
final_target = rng.choice(actual_targets)
return action.ThrowGrenade(self, final_target)
else:
return None
elif "straight_shooter" in self.tags:
direction = coordinates.get_cardinal_direction(self.coords,
self.currentLevel.player.coords)
dist = coordinates.minimumPath(self.coords,
self.currentLevel.player.coords)
if self.currentLevel.player in self.fov \
and direction is not None \
and dist < 12:
if self.spec == "ARROW":
return action.FireArrow(self, direction, 12)
elif self.spec == "POUNCE":
return action.Pounce(self, direction, 12)
else:
assert False
return None
else:
return None
else:
return None
def statue(self):
"""
The statue AI pattern is as follows:
If a monster that meets certain conditions is in view, do
a general haste.
If no such monster is in view, teleport adjacent to a damaged monster.
If no such monster exists, then teleport randomly.
"""
for d in self.fov.dudes:
if self.spec == "QUICKEN":
if (not d.isPlayer()) and (d.AICode != "STATUE"):
return action.HasteAll(self, 8, False, False)
else:
assert False
# If the statue is stuck, it can't teleport, so it just stays.
if self.hasCondition("STUCK"):
return action.Wait(self)
# If the statue did not do anything to monsters in view, it must teleport.
for m in self.currentLevel.dudeLayer:
if m.cur_HP < m.max_HP and not m.isPlayer() and (m.AICode != "STATUE"):
# Aha, a target!
destination_candidates = coordinates.adjacent_coords(m.coords)
destination_options = [i for i in destination_candidates
if self.currentLevel.isEmpty(i)
and i not in self.currentLevel.dudeLayer]
if destination_options != []:
return action.Teleport(self, rng.choice(destination_options))
# If there are no monsters to which the statue can teleport, teleport randomly.
for i in range(100):
destination = rng.randomPointInRect((0,0),
(self.currentLevel.dimensions[0] - 1,
self.currentLevel.dimensions[1] - 1))
if self.currentLevel.isEmpty(destination) and \
destination not in self.currentLevel.dudeLayer:
return action.Teleport(self, destination)
return action.Wait(self)
def die(self):
if self.spec != "NONE":
self.currentLevel.player.obtainCard(self)
self.currentLevel.kill(self)
if self.cur_HP > 0:
self.cur_HP = -300
class MonsterFactory(list):
"""
Getting a monster from this factory with [] gives you a duplicate.
"""
def __init__(self, *args, **kwds):
"""
Create a new MonsterFactory, given a list of monsters (or nothing).
"""
list.__init__(self, *args, **kwds)
self.buggy_monster = None
def create(self, key, coords = None, currentLevel = None):
"""
Get a duplicate of the monster identified (by int or string) as key.
"""
monsterPrototype = self.getPrototype(key)
return duplicate(monsterPrototype, coords, currentLevel)
def getPrototype(self, key):
"""
Get the actual monster stored in the factory, not just a duplicate.
"""
try: # is the key a string?
key.upper()
except AttributeError:
return list.__getitem__(self, key)
else:
soughtIndex = -1
for mon in self:
if key == mon.name:
soughtIndex = self.index(mon)
if soughtIndex == -1:
log.log("No monster with name %s found." % key)
return self.buggy_monster
else:
return list.__getitem__(self, soughtIndex)
def setBuggyMonster(self, buggy_monster):
"""
Set the monster created when no valid monster data is available.
"""
self.buggy_monster = buggy_monster
def getBuggyMonster(self):
"""
Get a copy of the monster created when no valid monster data is present.
"""
return duplicate(self.buggy_monster)
def duplicate(prototype, coords = None, currentLevel = None):
"""
Get a duplicate of the monster prototype supplied. If a currentLevel
is supplied as well, then the Monster is initialized on that Level; if
coords are supplied, the Monster begins on those coordinates.
"""
return Monster(prototype.name,
coords,
prototype.glyph,
prototype.AICode,
prototype.speed,
prototype.max_HP,
prototype.tags[:] if prototype.tags is not None else None,
prototype.attack,
prototype.defense,
prototype.spec,
prototype.specfreq,
currentLevel,
)