/
Actions.hs
863 lines (810 loc) · 32.4 KB
/
Actions.hs
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
module Actions where
import Control.Monad
import Control.Monad.State hiding (State)
import Data.Function
import Data.List as L
import Data.Map as M
import qualified Data.IntMap as IM
import Data.Maybe
import Data.Set as S
import System.Time
import Action
import Display hiding (display)
import Dungeon
import Geometry
import Grammar
import qualified HighScores as H
import Item
import qualified ItemKind
import ItemState
import qualified Keys as K
import Level
import LevelState
import Message
import Movable
import MovableState
import MovableKind
import MovableAdd
import Perception
import Random
import State
import qualified Config
import qualified Save
import Terrain
import qualified Effect
import EffectAction
import Keys hiding (Up, Down)
-- All the rest of the Action stuff.
displayHistory :: Action ()
displayHistory =
do
hst <- gets shistory
messageOverlayConfirm "" (unlines hst)
abort
dumpConfig :: Action ()
dumpConfig =
do
config <- gets sconfig
let fn = "LambdaHack.config.dump"
liftIO $ Config.dump fn config
abortWith $ "Current configuration dumped to file " ++ fn ++ "."
saveGame :: Action ()
saveGame =
do
b <- messageYesNo "Really save?"
if b
then do
-- Save the game state
st <- get
liftIO $ Save.saveGame st
ln <- gets (lname . slevel)
let total = calculateTotal st
status = H.Camping ln
go <- handleScores False status total
when go $ messageMore "See you soon, stronger and braver!"
end
else abortWith "Game resumed."
quitGame :: Action ()
quitGame =
do
b <- messageYesNo "Really quit?"
if b
then end -- TODO: why no highscore? no display, because the user may be in a hurry, since he quits the game instead of getting himself killed properly? no score recording, not to polute the scores list with games that the player didn't even want to end honourably?
else abortWith "Game resumed."
-- | End targeting mode, accepting the current location or not.
endTargeting :: Bool -> Action ()
endTargeting accept = do
returnLn <- gets (creturnLn . scursor)
target <- gets (mtarget . getPlayerBody)
cloc <- gets (clocation . scursor)
lvlSwitch returnLn -- return to the original level of the player
modify (updateCursor (\ c -> c { ctargeting = False }))
let isEnemy = case target of TEnemy _ -> True ; _ -> False
when (not isEnemy) $
if accept
then updatePlayerBody (\ p -> p { mtarget = TLoc cloc })
else updatePlayerBody (\ p -> p { mtarget = TCursor })
endTargetingMsg
endTargetingMsg :: Action ()
endTargetingMsg = do
pkind <- gets (mkind . getPlayerBody)
target <- gets (mtarget . getPlayerBody)
state <- get
let verb = "target"
targetMsg = case target of
TEnemy a ->
case findActorAnyLevel a state of
Just (_, m) -> objectMovable (mkind m)
Nothing -> "a long gone adversary"
TLoc loc -> "location " ++ show loc
TCursor -> "current cursor position continuously"
messageAdd $ subjectMovableVerb pkind verb ++ " " ++ targetMsg ++ "."
-- | Cancel something, e.g., targeting mode, resetting the cursor
-- to the position of the player. Chosen target is not invalidated.
cancelCurrent :: Action ()
cancelCurrent = do
targeting <- gets (ctargeting . scursor)
if targeting
then endTargeting False
else abortWith "Press Q to quit."
-- | Accept something, e.g., targeting mode, keeping cursor where it was.
-- Or perform the default action, if nothing needs accepting.
acceptCurrent :: Action () -> Action ()
acceptCurrent h = do
targeting <- gets (ctargeting . scursor)
if targeting
then endTargeting True
else h -- nothing to accept right now
moveCursor :: Dir -> Int -> Action ()
moveCursor dir n = do
(sy, sx) <- gets (lsize . slevel)
let upd cursor =
let (ny, nx) = iterate (`shift` dir) (clocation cursor) !! n
cloc = (max 1 $ min ny (sy-1), max 1 $ min nx (sx-1))
in cursor { clocation = cloc }
modify (updateCursor upd)
doLook
move :: Dir -> Action ()
move dir = do
pl <- gets splayer
targeting <- gets (ctargeting . scursor)
if targeting then moveCursor dir 1 else moveOrAttack True True pl dir
run :: Dir -> Action ()
run dir = do
pl <- gets splayer
targeting <- gets (ctargeting . scursor)
if targeting
then moveCursor dir 10
else do
updatePlayerBody (\ p -> p { mdir = Just dir })
-- attacks and opening doors disallowed while running
moveOrAttack False False pl dir
-- | This function implements the actual "logic" of running. It checks if we
-- have to stop running because something interested happened, and it checks
-- if we have to adjust the direction because we're in the corner of a corridor.
continueRun :: Dir -> Action ()
continueRun dir =
do
state <- get
loc <- gets (mloc . getPlayerBody)
per <- currentPerception
msg <- currentMessage
ms <- gets (lmonsters . slevel)
hs <- gets (lheroes . slevel)
lmap <- gets (lmap . slevel)
pl <- gets splayer
let dms = case pl of
AMonster n -> IM.delete n ms -- don't be afraid of yourself
AHero _ -> ms
mslocs = S.fromList (L.map mloc (IM.elems dms))
monstersVisible = not (S.null (mslocs `S.intersection` ptvisible per))
newsReported = not (L.null msg)
t = lmap `at` loc -- tile at current location
itemsHere = not (L.null (titems t))
heroThere = L.elem (loc `shift` dir) (L.map mloc (IM.elems hs))
dirOK = accessible lmap loc (loc `shift` dir)
-- What happens next is mostly depending on the terrain we're currently on.
let exit (Stairs {}) = True
exit (Opening {}) = True
exit (Door {}) = True
exit _ = False
let hop t
| monstersVisible || heroThere
|| newsReported || itemsHere || exit t = abort
hop Corridor =
-- in corridors, explore all corners and stop at all crossings
-- TODO: even in corridors, stop if you run past an exit (rare)
let ns = L.filter (\ x -> distance (neg dir, x) > 1
&& accessible lmap loc (loc `shift` x))
moves
allCloseTo main = L.all (\ d -> distance (main, d) <= 1) ns
in case ns of
[onlyDir] -> run onlyDir -- can be diagonal
_ ->
-- prefer orthogonal to diagonal dirs, for hero's safety
case L.filter (\ x -> not $ diagonal x) ns of
[ortoDir]
| allCloseTo ortoDir -> run ortoDir
_ -> abort
hop _ -- outside corridors, never change direction
| not dirOK = abort
hop _ =
let ns = L.filter (\ x -> x /= dir && distance (neg dir, x) > 1) moves
ls = L.map (loc `shift`) ns
as = L.filter (\ x -> accessible lmap loc x
|| openable 0 lmap x) ls
ts = L.map (tterrain . (lmap `at`)) as
in if L.any exit ts then abort else run dir
hop (tterrain t)
stopRunning :: Action ()
stopRunning = updatePlayerBody (\ p -> p { mdir = Nothing })
ifRunning :: (Dir -> Action a) -> Action a -> Action a
ifRunning t e =
do
mdir <- gets (mdir . getPlayerBody)
maybe e t mdir
-- | Store current message in the history and reset current message.
history :: Action ()
history =
do
msg <- resetMessage
config <- gets sconfig
let historyMax = Config.get config "ui" "historyMax"
unless (L.null msg) $
modify (updateHistory (take historyMax . ((msg ++ " "):)))
-- | Update player memory.
remember :: Action ()
remember =
do
per <- currentPerception
let vis = S.toList (ptvisible per)
let rememberLoc = M.update (\ (t,_) -> Just (t,t))
modify (updateLevel (updateLMap (\ lmap -> foldr rememberLoc lmap vis)))
neverMind :: Bool -> Action a
neverMind b = abortIfWith b "never mind"
-- | Open and close doors
openclose :: Bool -> Action ()
openclose o =
do
message "direction?"
display
e <- session nextCommand
pl <- gets splayer
K.handleDirection e (actorOpenClose pl True o) (neverMind True)
actorOpenClose :: Actor ->
Bool -> -- ^ verbose?
Bool -> -- ^ open?
Dir -> Action ()
actorOpenClose actor v o dir =
do
state <- get
lmap <- gets (lmap . slevel)
pl <- gets splayer
body <- gets (getActor actor)
let txt = if o then "open" else "closed"
let hms = levelHeroList state ++ levelMonsterList state
let loc = mloc body
let isPlayer = actor == pl
let isVerbose = v && isPlayer
let dloc = shift loc dir -- location we act upon
in case lmap `at` dloc of
Tile d@(Door hv o') []
| secret o' && isPlayer -> -- door is secret, cannot be opened or closed by the player
neverMind isVerbose
| maybe o ((|| not o) . (> (niq (mkind body)))) o' ->
-- door is in unsuitable state
abortIfWith isVerbose ("already " ++ txt)
| not (unoccupied hms dloc) ->
-- door is blocked by a movable
abortIfWith isVerbose "blocked"
| otherwise -> -- door can be opened / closed
-- TODO: print message if action performed by monster and perceived
let nt = Tile (Door hv (toOpen o)) []
adj = M.adjust (\ (_, mt) -> (nt, mt)) dloc
in modify (updateLevel (updateLMap adj))
Tile d@(Door hv o') _ -> -- door is jammed by items
abortIfWith isVerbose "jammed"
_ -> -- there is no door here
neverMind isVerbose
advanceTime actor
-- | Attempt a level switch to k levels deeper.
-- TODO: perhaps set up some level name arithmetics in Level.hs
-- and hide there the fact levels are now essentially Ints.
lvlDescend :: Int -> Action ()
lvlDescend k =
do
state <- get
let n = levelNumber (lname (slevel state))
nln = n + k
when (nln < 1 || nln > sizeDungeon (sdungeon state) + 1) $
abortWith "no more levels in this direction"
assertTrue $ liftM (k == 0 ||) (lvlSwitch (LambdaCave nln))
-- | Attempt a level change via up level and down level keys.
-- Will quit the game if the player leaves the dungeon.
lvlChange :: VDir -> Action ()
lvlChange vdir =
do
cursor <- gets scursor
targeting <- gets (ctargeting . scursor)
pbody <- gets getPlayerBody
pl <- gets splayer
map <- gets (lmap . slevel)
let loc = if targeting then clocation cursor else mloc pbody
case map `at` loc of
Tile (Stairs _ vdir' next) is
| vdir == vdir' -> -- stairs are in the right direction
case next of
Nothing ->
-- we are at the "end" of the dungeon
if targeting
then abortWith "cannot escape dungeon in targeting mode"
else do
b <- messageYesNo "Really escape the dungeon?"
if b
then fleeDungeon
else abortWith "Game resumed."
Just (nln, nloc) -> do
if targeting
then do
-- this assertion says no stairs go back to the same level
assertTrue $ lvlSwitch nln
-- do not freely reveal the other end of the stairs
map <- gets (lmap . slevel) -- lvlSwitch modifies map
let upd cursor =
let cloc = if Level.isUnknown (rememberAt map nloc)
then loc
else nloc
in cursor { clocation = cloc, clocLn = nln }
modify (updateCursor upd)
doLook
else do
-- Remove the player from the old level.
modify (deleteActor pl)
-- At this place the invariant that player exists fails.
-- Change to the new level (invariant not essential).
assertTrue $ lvlSwitch nln
-- Restore the invariant: add player to the new level.
modify (insertActor pl pbody)
-- Land the player at the other end of the stairs.
updatePlayerBody (\ p -> p { mloc = nloc })
-- Change the level of the player recorded in cursor.
modify (updateCursor (\ c -> c { creturnLn = nln }))
-- Create a backup of the savegame.
state <- get
liftIO $ Save.saveGame state >> Save.mvBkp (sconfig state)
playerAdvanceTime
_ -> -- no stairs
if targeting
then do
lvlDescend (if vdir == Up then -1 else 1)
ln <- gets (lname . slevel)
let upd cursor = cursor { clocLn = ln }
modify (updateCursor upd)
doLook
else
let txt = if vdir == Up then "up" else "down"
in abortWith ("no stairs " ++ txt)
-- | Hero has left the dungeon.
fleeDungeon :: Action ()
fleeDungeon =
do
state <- get
let total = calculateTotal state
items = L.concatMap mitems (levelHeroList state)
if total == 0
then do
go <- messageMoreConfirm "Coward!"
when go $
messageMore "Next time try to grab some loot before escape!"
end
else do
let winMsg = "Congratulations, you won! Your loot, worth " ++
show total ++ " gold, is:"
displayItems winMsg True items
go <- session getConfirm
when go $ do
go <- handleScores True H.Victor total
when go $ messageMore "Can it be done better, though?"
end
-- | Switches current hero to the next hero on the level, if any, wrapping.
cycleHero :: Action ()
cycleHero =
do
pl <- gets splayer
hs <- gets (lheroes . slevel)
let i = case pl of AHero n -> n ; _ -> -1
(lt, gt) = IM.split i hs
case IM.keys gt ++ IM.keys lt of
[] -> abortWith "Cannot select another hero on this level."
ni : _ -> assertTrue $ selectPlayer (AHero ni)
-- | Search for secret doors
search :: Action ()
search =
do
lmap <- gets (lmap . slevel)
ploc <- gets (mloc . getPlayerBody)
let searchTile (Tile (Door hv (Just n)) x, t') =
(Tile (Door hv (Just (max (n - 1) 0))) x, t')
searchTile t = t
f l m = M.adjust searchTile (shift ploc m) l
slmap = foldl' f lmap moves
modify (updateLevel (updateLMap (const slmap)))
playerAdvanceTime
-- | Start the floor targeting mode or toggle between the two floor modes.
targetFloor :: Action ()
targetFloor = do
target <- gets (mtarget . getPlayerBody)
let tgt = case target of
TLoc l -> TLoc l -- don't forget the old location target too fast
_ -> TCursor
updatePlayerBody (\ p -> p { mtarget = tgt })
setCursor tgt
-- | Start the monster targeting mode. Cycle between monster targets.
-- TODO: also target a monster by moving the cursor, if in target monster mode.
-- TODO: sort monsters by distance to the player.
targetMonster :: Action ()
targetMonster = do
pl <- gets splayer
ms <- gets (lmonsters . slevel)
per <- currentPerception
target <- gets (mtarget . getPlayerBody)
targeting <- gets (ctargeting . scursor)
let i = case target of
TEnemy (AMonster n) | targeting -> n -- try next monster
TEnemy (AMonster n) -> n - 1 -- try to retarget old monster
_ -> -1 -- try to target first monster (e.g., number 0)
dms = case pl of
AMonster n -> IM.delete n ms -- don't target yourself
AHero _ -> ms
(lt, gt) = IM.split i dms
gtlt = IM.assocs gt ++ IM.assocs lt
lf = L.filter (\ (_, m) -> actorSeesLoc pl (mloc m) per pl) gtlt
tgt = case lf of
[] -> target -- no monsters in sight, stick to last target
(ni, _) : _ -> TEnemy (AMonster ni) -- pick the next monster
updatePlayerBody (\ p -> p { mtarget = tgt })
setCursor tgt
-- | Set, activate and display cursor information.
setCursor :: Target -> Action ()
setCursor tgt = do
state <- get
per <- currentPerception
ploc <- gets (mloc . getPlayerBody)
ln <- gets (lname . slevel)
let upd cursor =
let cloc = case targetToLoc (ptvisible per) state of
Nothing -> ploc
Just l -> l
in cursor { ctargeting = True, clocation = cloc, clocLn = ln }
modify (updateCursor upd)
doLook
-- | Perform look around in the current location of the cursor.
-- TODO: depending on tgt, show extra info about tile or monster or both
doLook :: Action ()
doLook =
do
loc <- gets (clocation . scursor)
state <- get
lmap <- gets (lmap . slevel)
per <- currentPerception
target <- gets (mtarget . getPlayerBody)
let canSee = S.member loc (ptvisible per)
monsterMsg =
if canSee
then case L.find (\ m -> mloc m == loc) (levelMonsterList state) of
Just m -> subjectMovable (mkind m) ++ " is here. "
Nothing -> ""
else ""
mode = case target of
TEnemy _ -> "[targeting monster] "
TLoc _ -> "[targeting location] "
TCursor -> "[targeting current] "
-- general info about current loc
lookMsg = mode ++ lookAt True canSee state lmap loc monsterMsg
-- check if there's something lying around at current loc
t = lmap `at` loc
if length (titems t) <= 2
then do
messageAdd lookMsg
else do
displayItems lookMsg False (titems t)
session getConfirm
messageAdd ""
-- | Display inventory
inventory :: Action a
inventory =
do
items <- gets (mitems . getPlayerBody)
if L.null items
then abortWith "You are not carrying anything"
else do
displayItems "This is what you are carrying:" True items
session getConfirm
abortWith ""
-- | Let the player choose any item with a given group name.
-- Note that this does not guarantee an item from the group to be chosen,
-- as the player can override the choice.
getGroupItem :: String -> -- name of the group
String -> -- prompt
[Item] -> -- all objects in question
String -> -- how to refer to the collection of objects,
-- e.g., "in your inventory"
Action (Maybe Item)
getGroupItem groupName prompt is packName =
let choice i = ItemKind.jname (ItemKind.getIK (ikind i)) == groupName
header = capitalize $ suffixS groupName
in getItem prompt choice header is packName
drinkPotion :: Action ()
drinkPotion =
do
state <- get
pbody <- gets getPlayerBody
items <- gets (mitems . getPlayerBody)
pl <- gets splayer
if L.null items
then abortWith "You are not carrying anything."
else do
i <- getGroupItem "potion" "What to drink?" items "in your inventory"
case i of
Just i'@(Item { ikind = ik })
| ItemKind.jname (ItemKind.getIK ik) == "potion" ->
do
-- only one potion is consumed even if several
-- are joined in the inventory
let consumed = i' { icount = 1 }
removeFromInventory consumed
message (subjectVerbIObject state pbody "drink" consumed "")
itemEffectAction i' pl pl
Just _ -> abortWith "you cannot drink that"
Nothing -> neverMind True
playerAdvanceTime
readScroll :: Action ()
readScroll =
do
state <- get
pbody <- gets getPlayerBody
items <- gets (mitems . getPlayerBody)
pl <- gets splayer
if L.null items
then abortWith "You are not carrying anything."
else do
i <- getGroupItem "scroll" "What to read?" items "in your inventory"
case i of
Just i'@(Item { ikind = ik })
| ItemKind.jname (ItemKind.getIK ik) == "scroll" ->
do
-- only one scroll is consumed even if several
-- are joined in the inventory
let consumed = i' { icount = 1 }
removeFromInventory consumed
message (subjectVerbIObject state pbody "read" consumed "")
itemEffectAction i' pl pl
Just _ -> abortWith "you cannot read that"
Nothing -> neverMind True
playerAdvanceTime
fireItem :: Action ()
fireItem = do
state <- get
per <- currentPerception
pitems <- gets (mitems . getPlayerBody)
pl <- gets splayer
target <- gets (mtarget . getPlayerBody)
case findItem (\ i -> ItemKind.jname (ItemKind.getIK (ikind i)) == "dart") pitems of
Just (dart, _) -> do
let fired = dart { icount = 1 }
removeFromInventory fired
case targetToLoc (ptvisible per) state of
Nothing -> abortWith "target invalid"
Just loc ->
if actorReachesLoc pl loc per pl
then case locToActor loc state of
Just ta -> itemEffectAction dart pl ta
Nothing -> modify (updateLevel (scatterItems [fired] loc))
else abortWith "target not reachable"
Nothing -> abortWith "nothing to fire"
playerAdvanceTime
zapItem :: Action ()
zapItem = do
pl <- gets splayer
state <- get
per <- currentPerception
pitems <- gets (mitems . getPlayerBody)
case findItem (\ i -> ItemKind.jname (ItemKind.getIK (ikind i)) == "wand") pitems of
Just (wand, _) -> do
let zapped = wand { icount = 1 }
removeFromInventory zapped
case targetToLoc (ptvisible per) state of
Nothing -> abortWith "target invalid"
Just loc ->
if actorReachesLoc pl loc per pl
then case locToActor loc state of
Just ta -> itemEffectAction wand pl ta
Nothing -> abortWith "no living target to affect"
else abortWith "target not reachable"
Nothing -> abortWith "nothing to zap"
playerAdvanceTime
dropItem :: Action ()
dropItem =
do
state <- get
pbody <- gets getPlayerBody
ploc <- gets (mloc . getPlayerBody)
items <- gets (mitems . getPlayerBody)
if L.null items
then abortWith "You are not carrying anything."
else do
i <- getAnyItem "What to drop?" items "inventory"
case i of
Just i' ->
do
removeFromInventory i'
message (subjectVerbIObject state pbody "drop" i' "")
dropItemsAt [i'] ploc
Nothing -> neverMind True
playerAdvanceTime
-- | Remove given item from the hero's inventory.
removeFromInventory :: Item -> Action ()
removeFromInventory i =
updatePlayerBody (\ p -> p { mitems = removeItemByLetter i (mitems p) })
-- | Remove given item from the given location.
removeFromLoc :: Item -> Loc -> Action ()
removeFromLoc i loc =
modify (updateLevel (updateLMap adj))
where
adj = M.adjust (\ (t, rt) -> (remove t, rt)) loc
remove t = t { titems = removeItemByKind i (titems t) }
actorPickupItem :: Actor -> Action ()
actorPickupItem actor =
do
state <- get
pl <- gets splayer
per <- currentPerception
lmap <- gets (lmap . slevel)
movable <- gets (getActor actor)
let loc = mloc movable
let t = lmap `at` loc -- the map tile in question
let perceived = loc `S.member` ptvisible per
let isPlayer = actor == pl
-- check if something is here to pick up
case titems t of
[] -> abortIfWith isPlayer "nothing here"
(i:rs) -> -- pick up first item; TODO: let player select item; not for monsters
case assignLetter (iletter i) (mletter movable) (mitems movable) of
Just l ->
do
let (ni, nitems) = joinItem (i { iletter = Just l }) (mitems movable)
-- message is dependent on who picks up and if the hero can perceive it
if isPlayer
then message (letterLabel (iletter ni) ++ objectItem state ni)
else when perceived $
message $ subjectCompoundVerbIObject state movable "pick" "up" i ""
removeFromLoc i loc
-- add item to actor's inventory:
updateAnyActor actor $ \ m ->
m { mitems = nitems, mletter = maxLetter l (mletter movable) }
Nothing -> abortIfWith isPlayer "you cannot carry any more"
advanceTime actor
pickupItem :: Action ()
pickupItem = do
pl <- gets splayer
actorPickupItem pl
-- TODO: I think that player handlers should be wrappers around more general actor handlers, but
-- the actor handlers should be performing specific actions, i.e., already specify the item to be
-- picked up. It doesn't make sense to invoke dialogues for arbitrary actors, and most likely the
-- decision for a monster is based on perceiving a particular item to be present, so it's already
-- known. In actor handlers we should make sure that messages are printed to the player only if the
-- hero can perceive the action.
-- | Let the player choose any item from a list of items.
getAnyItem :: String -> -- prompt
[Item] -> -- all objects in question
String -> -- how to refer to the collection of objects, e.g. "in your inventory"
Action (Maybe Item)
getAnyItem prompt is isn = getItem prompt (const True) "Objects" is isn
-- | Let the player choose a single item from a list of items.
getItem :: String -> -- prompt message
(Item -> Bool) -> -- which items to consider suitable
String -> -- how to describe suitable objects
[Item] -> -- all objects in question
String -> -- how to refer to the collection of objects, e.g. "in your inventory"
Action (Maybe Item)
getItem prompt p ptext is0 isn =
let is = L.filter p is0
choice | L.null is = "[*]"
| otherwise = "[" ++ letterRange (concatMap (maybeToList . iletter) is) ++ " or ?* or " ++ showKey Keys.Return ++ "]"
r = do
message (prompt ++ " " ++ choice)
display
let h = session nextCommand >>= h'
h' e = case e of
K.Char '?' -> do
-- filter for supposedly suitable objects
b <- displayItems (ptext ++ " " ++ isn) True is
if b then session (getOptionalConfirm (const r) h')
else r
K.Char '*' -> do
-- show all objects
b <- displayItems ("Objects " ++ isn) True is0
if b then session (getOptionalConfirm (const r) h')
else r
K.Char l -> return (find (\ i -> maybe False (== l) (iletter i)) is0)
K.Return -> return (case is of [] -> Nothing ; i : _ -> Just i)
_ -> return Nothing
h
in r
displayItems :: Message -> Bool -> [Item] -> Action Bool
displayItems msg sorted is = do
state <- get
let inv = unlines $
L.map (\ i ->
letterLabel (iletter i) ++ objectItem state i ++ " ")
((if sorted then sortBy (cmpLetter' `on` iletter) else id) is)
let ovl = inv ++ more
message msg
overlay ovl
-- | This function performs a move (or attack) by any actor,
-- i.e., it can handle monsters, heroes and both.
moveOrAttack :: Bool -> -- allow attacks?
Bool -> -- auto-open doors on move
Actor -> -- who's moving?
Dir ->
Action ()
moveOrAttack allowAttacks autoOpen actor dir
| dir == (0,0) =
-- Moving with no direction is a noop.
-- We include it currently to prevent that
-- monsters attack themselves by accident.
advanceTime actor
| otherwise = do
-- We start by looking at the target position.
state <- get
pl <- gets splayer
lmap <- gets (lmap . slevel)
sm <- gets (getActor actor)
let sloc = mloc sm -- source location
tloc = sloc `shift` dir -- target location
tgt <- gets (locToActor tloc)
case tgt of
Just target ->
if allowAttacks then
-- Attacking does not require full access, adjacency is enough.
actorAttackActor actor target
else if accessible lmap sloc tloc then do
-- Switching positions requires full access.
actorRunActor actor target
when (actor == pl) $ message $ lookAt False True state lmap tloc ""
else abort
Nothing ->
if accessible lmap sloc tloc then do
-- perform the move; TODO: make this a separate function
updateAnyActor actor $ \ m -> m { mloc = tloc }
when (actor == pl) $ message $ lookAt False True state lmap tloc ""
advanceTime actor
else if autoOpen then
-- try to open a door
actorOpenClose actor False True dir
else abort
-- | Resolves the result of an actor moving into another. Usually this
-- involves melee attack, but with two heroes it just changes focus.
-- Movables on blocked locations can be attacked without any restrictions.
-- For instance, a movable on an open door can be attacked diagonally,
-- and a movable capable of moving through walls can be attacked from an
-- adjacent position.
actorAttackActor :: Actor -> Actor -> Action ()
actorAttackActor (AHero _) target@(AHero _) =
-- Select adjacent hero by bumping into him. Takes no time.
selectPlayer target >> return ()
actorAttackActor source target = do
sm <- gets (getActor source)
case strongestWeapon (mitems sm) of
Just weapon ->
itemEffectAction weapon source target
Nothing ->
effectToAction (Effect.Wound 3) source target 0 "" >> return ()
advanceTime source
-- | Resolves the result of an actor running into another.
-- This involves switching positions of the two movables.
actorRunActor :: Actor -> Actor -> Action ()
actorRunActor source target = do
pl <- gets splayer
sloc <- gets (mloc . getActor source) -- source location
tloc <- gets (mloc . getActor target) -- target location
updateAnyActor source $ \ m -> m { mloc = tloc }
updateAnyActor target $ \ m -> m { mloc = sloc }
if source == pl
then stopRunning -- do not switch positions repeatedly
else if isAMonster source
then focusIfAHero target
else return ()
advanceTime source
-- | Generate a monster, possibly.
generateMonster :: Action ()
generateMonster =
do -- TODO: simplify
state <- get
nstate <- liftIO $ rndToIO $ rollMonster state
modify (const nstate)
-- | Advance the move time for the given actor.
advanceTime :: Actor -> Action ()
advanceTime actor =
do
time <- gets stime
updateAnyActor actor $ \ m -> m { mtime = time + (nspeed (mkind m)) }
playerAdvanceTime :: Action ()
playerAdvanceTime = do
pl <- gets splayer
advanceTime pl
-- | Possibly regenerate HP for all movables on the current level.
regenerateLevelHP :: Action ()
regenerateLevelHP =
do
time <- gets stime
let upd m = if time `mod` (nregen (mkind m)) /= 0
then m
else m { mhp = min (nhpMax (mkind m)) (mhp m + 1) }
-- We really want hero selection to be a purely UI distinction,
-- so all heroes need to regenerate, not just the player.
-- Only the heroes on the current level regenerate (others are frozen
-- in time together with their level). This prevents cheating
-- via sending one hero to a safe level and waiting there.
modify (updateLevel (updateHeroes (IM.map upd)))
modify (updateLevel (updateMonsters (IM.map upd)))