-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhtpataic20.html
1495 lines (1489 loc) · 61.2 KB
/
htpataic20.html
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>20. Combat</title>
<link rel="stylesheet" href="htpataic.css" type="text/css" />
</head>
<body>
<table class="contents"><tr><td>
<h4>Contents</h4>
<div><a href="htpataic01.html">1. Introduction</a></div>
<div><a href="htpataic02.html">2. The main loop</a></div>
<div><a href="htpataic03.html">3. Locations</a></div>
<div><a href="htpataic04.html">4. Objects</a></div>
<div><a href="htpataic05.html">5. Inventory</a></div>
<div><a href="htpataic06.html">6. Passages</a></div>
<div><a href="htpataic07.html">7. Distance</a></div>
<div><a href="htpataic08.html">8. North, east, south, west</a></div>
<div><a href="htpataic09.html">9. Code generation</a></div>
<div><a href="htpataic10.html">10. More attributes</a></div>
<div><a href="htpataic11.html">11. Conditions</a></div>
<div><a href="htpataic12.html">12. Open and close</a></div>
<div><a href="htpataic13.html">13. The parser</a></div>
<div><a href="htpataic14.html">14. Multiple nouns</a></div>
<div><a href="htpataic15.html">15. Light and dark</a></div>
<div><a href="htpataic16.html">16. Savegame</a></div>
<div><a href="htpataic17.html">17. Test automation</a></div>
<div><a href="htpataic18.html">18. Abbreviations</a></div>
<div><a href="htpataic19.html">19. Conversations</a></div>
<div><b>20. Combat</b></div>
<div><a href="htpataic21.html">21. Multi-player</a></div>
<div><a href="htpataic22.html">22. Client-server</a></div>
<div><a href="htpataic23.html">23. Database</a></div>
<div><a href="htpataic24.html">24. Speech</a></div>
<div><a href="htpataic25.html">25. JavaScript</a></div>
</td></tr></table>
<h1>How to program a text adventure in C</h1>
<p>
by Ruud Helderman
<<a href="mailto:r.helderman@hccnet.nl">r.helderman@hccnet.nl</a>>
</p>
<p>
Licensed under
<a href="https://github.com/helderman/htpataic/blob/master/LICENSE">MIT License</a>
</p>
<h2>20. Combat</h2>
<p class="intro">
Since the early classics were influenced by
<a href="https://en.wikipedia.org/wiki/Fantasy">fantasy</a>,
it is not surprising that many text-based games adopted elements from
<a href="https://en.wikipedia.org/wiki/Role-playing_game">RPG games</a>
like
<a href="https://en.wikipedia.org/wiki/Dungeons_%26_Dragons">Dungeons & Dragons</a>.
</p>
<p>
Multi-player games thrive on role play and combat; you see that in every
<a href="https://en.wikipedia.org/wiki/MUD">MUD</a>.
Single-player games on the other hand, typically focus on puzzle solving.
The boundaries are not always that sharp.
In the early days, before the rise of
<a href="https://en.wikipedia.org/wiki/Internet">the internet</a>,
there were plenty of single-player games that featured combat,
though often in a simplified form.
</p>
<p>
It is easy enough to implement a ‘kill’ command that will dispose of any actors standing in your way.
</p>
<table><tr>
<td class="snippet">guard->health--; /* do this often enough and he's dead */
</td>
</tr></table>
<p>
But of course there is a lot more to it.
Some weapons may be more effective than others.
Some opponents may be tougher than others.
Both the player and non-player characters stand a better chance in combat
when being healthy, skilled and well-equiped.
A lot can be learned from
<a href="https://en.wikipedia.org/wiki/Tabletop_role-playing_game">tabletop role-playing games</a>,
where
<a href="https://en.wikipedia.org/wiki/Statistic_(role-playing_games)">statistics</a>
determine the chances of survival.
Each stat can be implemented as an attribute in our ‘object’ structure;
this was discussed in chapter 10.
A combat-related command should use these stats
in a ‘damage formula’
that determines the impact of the command on the actors involved.
</p>
<table><tr>
<td class="snippet">guard->health -= calculate_damage(player, guard);
</td>
</tr></table>
<h3>Random</h3>
<p>
Traditionally, some uncertainty is built into a damage formula.
Tabletop games have
<a href="https://en.wikipedia.org/wiki/Dice">dice</a>,
computer games have a
<a href="https://en.wikipedia.org/wiki/Random_number_generation">random number generator</a>.
Please note that ‘randomness’ may cause trouble with the
‘roll-forward’ savegame technique proposed in chapter 16.
Roll-forward demands repeatability.
When saving a game, you expect the exact same game state when restoring.
But different random numbers might completely change
the outcome of battles that took place prior to saving.
</p>
<p>
Fortunately, computers typically use
<a href="https://en.wikipedia.org/wiki/Pseudorandom_number_generator">pseudorandom number generators</a>.
Reproducibility is one of their big advantages.
Just make sure to seed the PRNG with the same fixed number at the start of every game.
If you prefer to have a uniquely random game experience for every new game session
(though I doubt that will be relevant for a text adventure,
where a player is typically dedicated to a single ongoing session),
then at least make sure the seed is stored as part of the savegame.
</p>
<p>
This applies not only to combat, but to everything that is random,
for example objects positioned randomly on the map,
or NPCs moving randomly between locations.
</p>
<h3>Real-time vs turn based</h3>
<p>
When implementing combat in a text adventure,
you will have to choose between
<a href="https://en.wikipedia.org/wiki/Turns,_rounds_and_time-keeping_systems_in_games#Real-time">real-time</a>
and
<a href="https://en.wikipedia.org/wiki/Turns,_rounds_and_time-keeping_systems_in_games#Turn-based">turn-based</a>.
In multi-player games, turn-based only makes sense when playing offline (as in
<a href="https://en.wikipedia.org/wiki/Play-by-mail_game">play-by-mail</a>).
Online players do not want to be kept waiting for other players to respond,
which is why a
<a href="https://en.wikipedia.org/wiki/MUD">MUD</a>
is typically played in real time.
This brings a few coding challenges; in particular
<a href="https://en.wikipedia.org/wiki/Synchronization_(computer_science)">synchronization</a>.
It’s also important to implement some kind of
<a href="https://en.wikipedia.org/wiki/Glossary_of_video_game_terms#cooldown">cooldown</a>,
to prevent things like combat to turn into a
<a href="https://en.wikipedia.org/wiki/Speed_typing_contest">speed typing contest</a>.
</p>
<p>
Single-player games are typically turn-based.
Computers respond faster than humans,
so a human player will not be frustrated by the time it takes
for a non-player character to respond to the player’s actions.
Turn-based has the advantage of not rushing players,
giving them all the time in the world to think about their next move,
while at the same time offering instant feedback
at every attempt from the player to progress through the game.
</p>
<p>
Turn-based does not mean there is no notion of time;
it’s just not <i>real time</i>.
Every command from the user is a ‘turn’ in the game.
During that turn, some ‘game time’ passes,
which gives other (non-player) characters an equal opportunity to take action.
For example, after the player has taken a swing at an orc,
it’s the orc’s turn to retaliate.
</p>
<p>
In its simplest form, every command represents an equal time slice.
But it is also possible to make certain commands ‘consume’ more time than others,
giving the rest of the world more time to do their ‘thing’ in response.
For example, the player may be given the opportunity
to travel from one town to another with a single ‘go’ command,
but that may cost the player so much game time,
that night will fall halfway through,
bringing out nasty night crawlers.
‘Long’ commands may also consume more resources, like
food, water, physical strength, and fuel for a lamp.
</p>
<p>
At the very least, I would recommend to let ‘supportive’ commands,
for example ‘help’, ‘save’, ‘load’, consume zero game time.
These commands are not part of the storyline;
it would be unfair to penalize the player for using them.
The same thing goes for typos and other input that is rejected by the parser;
this is supposed to be an adventure, not a
<a href="https://en.wikipedia.org/wiki/Spelling_bee">spelling bee</a>.
</p>
<table><tr>
<td class="snippet">The orc looks very angry.
--> hit orc
You hit the orc on the head.
The orc is dazed, and for a moment, is defenseless.
--> stabbb orc
I don't know how to 'stabbb'.
The orc recovers and strikes back.
You are dead.
--> <span class="red">*** rage quit ***</span>
</td>
</tr></table>
<p>
Please note that in battle, a return action
is not necessarily implied by the player’s last command.
Once enraged, the orc is likely to keep responding with violence,
regardless of what the player’s subsequent commands will be.
</p>
<table><tr>
<td class="snippet">--> hit orc
You hit the orc; orc loses 10 HP.
Orc strikes back; you lose 10 HP.
--> give flowers to orc
Orc accepts your gift and makes a flower basket out of it.
--> <span class="red">mood swings???</span>
</td>
</tr></table>
<p>
Therefore, it is best to implement all actions from ‘the rest of the world’
not as part of any user command, but as a separate step in the main loop.
Remember the main loop from chapter 2?
We will just make an additional function call there.
</p>
<table class="demo">
<tr><th>Sample output</th></tr>
<tr><td>
Welcome to Little Cave Adventure.<br />
You are in an open field.<br />
You see:<br />
a silver coin<br />
a burly guard<br />
a cave entrance to the east<br />
dense forest all around<br />
a lamp<br />
a wooden club<br />
a dagger<br />
<br />
--> get club<br />
You pick up a wooden club.<br />
<br />
--> get dagger<br />
You pick up a dagger.<br />
<br />
--> get lamp<br />
You pick up a lamp.<br />
<br />
--> attack<br />
You hit a burly guard with a dagger.<br />
You are hit by a burly guard with bare hands.<br />
<br />
--> attack with club<br />
You hit a burly guard with a wooden club.<br />
<br />
--> drop dagger<br />
You drop a dagger.<br />
You see a burly guard pick up a dagger.<br />
<br />
--> attack guard<br />
You hit a burly guard with a wooden club.<br />
You are hit by a burly guard with a dagger.<br />
<br />
--> attack with dagger<br />
You are not holding any dagger.<br />
<br />
--> attack with lamp<br />
You try to hit a burly guard with a lamp, but you miss.<br />
<br />
--> wait<br />
Some time passes...<br />
You are hit by a burly guard with a dagger.<br />
<br />
--> quit<br />
<br />
Bye!<br />
</td></tr>
</table>
<table class="code"><tr>
<th>main.c</th>
</tr><tr>
<td>
<ol>
<li class="old">#include <stdbool.h></li>
<li class="old">#include <stdio.h></li>
<li class="old">#include <string.h></li>
<li class="old">#include "expand.h"</li>
<li class="old">#include "parsexec.h"</li>
<li class="new">#include "turn.h"</li>
<li class="old"></li>
<li class="old">static char input[100] = "look around";</li>
<li class="old"></li>
<li class="old">static bool getFromFP(FILE *fp)</li>
<li class="old">{</li>
<li class="old"> bool ok = fgets(input, sizeof input, fp) != NULL;</li>
<li class="old"> if (ok) input[strcspn(input, "\n")] = '\0';</li>
<li class="old"> return ok;</li>
<li class="old">}</li>
<li class="old"></li>
<li class="old">static bool getInput(const char *filename)</li>
<li class="old">{</li>
<li class="old"> static FILE *fp = NULL;</li>
<li class="old"> bool ok;</li>
<li class="old"> if (fp == NULL)</li>
<li class="old"> {</li>
<li class="old"> if (filename != NULL) fp = fopen(filename, "rt");</li>
<li class="old"> if (fp == NULL) fp = stdin;</li>
<li class="old"> }</li>
<li class="old"> else if (fp == stdin && filename != NULL)</li>
<li class="old"> {</li>
<li class="old"> FILE *out = fopen(filename, "at");</li>
<li class="old"> if (out != NULL)</li>
<li class="old"> {</li>
<li class="old"> fprintf(out, "%s\n", input);</li>
<li class="old"> fclose(out);</li>
<li class="old"> }</li>
<li class="old"> }</li>
<li class="old"> printf("\n--> ");</li>
<li class="old"> ok = getFromFP(fp);</li>
<li class="old"> if (fp != stdin)</li>
<li class="old"> {</li>
<li class="old"> if (ok)</li>
<li class="old"> {</li>
<li class="old"> printf("%s\n", input);</li>
<li class="old"> }</li>
<li class="old"> else</li>
<li class="old"> {</li>
<li class="old"> fclose(fp);</li>
<li class="old"> ok = getFromFP(fp = stdin);</li>
<li class="old"> }</li>
<li class="old"> }</li>
<li class="old"> return ok;</li>
<li class="old">}</li>
<li class="old"></li>
<li class="new">static bool processInput(char *ptr, int size)</li>
<li class="new">{</li>
<li class="new"> return turn(parseAndExecute(expand(ptr, size)));</li>
<li class="new">}</li>
<li class="old"></li>
<li class="old">int main(int argc, char *argv[])</li>
<li class="old">{</li>
<li class="old"> (void)argc;</li>
<li class="old"> printf("Welcome to Little Cave Adventure.\n");</li>
<li class="new"><span class="old"> while </span>(processInput(input,<span class="old"> sizeof </span>input)<span class="old"> && getInput(argv[1]));</span></li>
<li class="old"> printf("\nBye!\n");</li>
<li class="old"> return 0;</li>
<li class="old">}</li>
</ol>
</td>
</tr></table>
<div class="explanation">
<p>
Explanation:
</p>
<ul>
<li>Line 6:
another new module, shown below.
</li>
<li>Line 54:
directly after calling function parseAndExecute,
we will call a new function named ‘turn’.
The return value of parseAndExecute is passed into turn as a parameter.
</li>
</ul>
</div>
<p>
Function ‘turn’ implements
everything that is going on around the player.
In a multi-player game, this would include activity of other human players.
A single-player game only has non-player characters,
but of course there could be many other processes.
A typical example is a lamp that is slowly dying.
Every turn with the lamp being on, it will consume oil or battery power.
Once everything is consumed, the light will dim.
Other examples are forces of nature: a storm, a flood, a volcanic eruption.
</p>
<table class="code"><tr>
<th>turn.h</th>
</tr><tr>
<td>
<ol>
<li class="new">extern bool turn(int time);</li>
</ol>
</td>
</tr><tr>
<th>turn.c</th>
</tr><tr>
<td>
<ol>
<li class="new">#include <stdbool.h></li>
<li class="new">#include <stdio.h></li>
<li class="new">#include "object.h"</li>
<li class="new">#include "misc.h"</li>
<li class="new">#include "location.h"</li>
<li class="new">#include "damage.h"</li>
<li class="new"></li>
<li class="new">static OBJECT *findBestWeaponAround(OBJECT *actor, OBJECT *weapon)</li>
<li class="new">{</li>
<li class="new"> OBJECT *obj;</li>
<li class="new"> for (obj = objs; obj < endOfObjs; obj++)</li>
<li class="new"> {</li>
<li class="new"> if (isHolding(actor->location, obj) && obj->impact < weapon->impact)</li>
<li class="new"> {</li>
<li class="new"> weapon = obj;</li>
<li class="new"> }</li>
<li class="new"> }</li>
<li class="new"> return weapon;</li>
<li class="new">}</li>
<li class="new"></li>
<li class="new">static void actorTakingTurn(OBJECT *actor)</li>
<li class="new">{</li>
<li class="new"> if (isHolding(player->location, actor) && actor->trust < 0)</li>
<li class="new"> {</li>
<li class="new"> OBJECT *weapon = getOptimalWeapon(actor);</li>
<li class="new"> OBJECT *best = findBestWeaponAround(actor, weapon);</li>
<li class="new"> if (weapon == best)</li>
<li class="new"> {</li>
<li class="new"> dealDamage(actor, weapon, player);</li>
<li class="new"> }</li>
<li class="new"> else</li>
<li class="new"> {</li>
<li class="new"> best->location = actor;</li>
<li class="new"> printf("You see %s pick up %s.\n",</li>
<li class="new"> actor->description, best->description);</li>
<li class="new"> }</li>
<li class="new"> }</li>
<li class="new">}</li>
<li class="new"></li>
<li class="new">static void depleteLight(OBJECT *obj, int time)</li>
<li class="new">{</li>
<li class="new"> if ((obj->light -= time) <= 0 &&</li>
<li class="new"> (isHolding(player, obj) || isHolding(player->location, obj)))</li>
<li class="new"> {</li>
<li class="new"> printf("You see %s go out.\n", obj->description);</li>
<li class="new"> }</li>
<li class="new">}</li>
<li class="new"></li>
<li class="new">bool turn(int time)</li>
<li class="new">{</li>
<li class="new"> if (time > 0)</li>
<li class="new"> {</li>
<li class="new"> bool originallyLit = isLit(player->location);</li>
<li class="new"> OBJECT *obj, *originalLocation = player->location;</li>
<li class="new"> for (obj = objs; obj < endOfObjs; obj++)</li>
<li class="new"> {</li>
<li class="new"> if (validObject(obj) && obj->location != NULL)</li>
<li class="new"> {</li>
<li class="new"> if (obj->health > 0) actorTakingTurn(obj);</li>
<li class="new"> if (obj->light > 0) depleteLight(obj, time);</li>
<li class="new"> }</li>
<li class="new"> }</li>
<li class="new"> if (player->health <= 0)</li>
<li class="new"> {</li>
<li class="new"> printf("You rise up to a more peaceful place...\n");</li>
<li class="new"> player->location = heaven;</li>
<li class="new"> player->health = 100;</li>
<li class="new"> for (obj = objs; obj < endOfObjs; obj++)</li>
<li class="new"> {</li>
<li class="new"> if (obj->location == player) obj->location = field;</li>
<li class="new"> }</li>
<li class="new"> }</li>
<li class="new"> if (originallyLit != isLit(player->location) ||</li>
<li class="new"> originalLocation != player->location)</li>
<li class="new"> {</li>
<li class="new"> executeLookAround();</li>
<li class="new"> }</li>
<li class="new"> }</li>
<li class="new"> return time >= 0;</li>
<li class="new">}</li>
</ol>
</td>
</tr></table>
<div class="explanation">
<p>
Explanation:
</p>
<ul>
<li>Line 8-19:
this function gives non-player characters a little bit of
<a href="https://en.wikipedia.org/wiki/Artificial_intelligence">artificial intelligence</a>.
An NPC will pick up a more powerful weapon, if any, before attacking.
This may not be the best tactic
in situations where a swift attack would be beneficial.
To make the NPC more intelligent, improve the function
by making a more complex decision tree involving more attributes.
</li>
<li>Line 23:
non-player characters will only be aggressive
when their ‘trust’ towards the player is negative.
This is a new attribute that is introduced below.
</li>
<li>Line 25:
start off taking the most powerful weapon the NPC is carrying.
</li>
<li>Line 26:
try to find an even more powerful weapon in NPC’s surroundings.
</li>
<li>Line 27:
if <i>findBestWeaponAround</i> is unable to find a better weapon,
then it will simply return the original weapon
(the one passed in as a parameter).
</li>
<li>Line 29:
the NPC is attacking.
</li>
<li>Line 33:
the NPC picks up the new weapon.
This ends NPC’s turn;
NPC will have to wait until the next turn to attack.
</li>
<li>Line 42-46:
each lamp in the game, when lit, will slowly consume its fuel.
Every turn, property <i>light</i> is decreased by an amount
that equals the time passed.
This will happen regardless of where the lamp is.
The player will be notified once all fuel has been consumed,
but this only happens if the lamp is present at player’s location.
Of course, it is also possible to give an early warning, for example
“the lamp flickers” when <i>light</i> drops below 10.
</li>
<li>Line 49, 51, 79:
time, passed in as a parameter, is typically 1 in this game,
meaning a single unit of time has passed.
There are two special values: 0 and -1.
Zero means the player did not take a turn
(for example because no valid command was entered),
so we let the surrounding world skip its turn too.
A negative number (-1) means the user wants to quit the program.
</li>
<li>Line 55-62:
give every object a chance to do its thing.
But <i>only</i> if that object exists,
i.e. its <i>condition</i> function returns true (see chapter 11),
and its location is not NULL (see chapter 12 and 15).
This helps prevent the lamp from burning fuel while it’s off.
</li>
<li>Line 63:
when player’s health hits zero, player dies.
</li>
<li>Line 65-67:
As explained in chapter 2, I like to give the player another chance.
Health is restored, and the player is moved to a ‘respawn point’.
I made a dedicated location for that, named ‘little heaven’.
Your quest does not end there;
I gave heaven a portal that will transport the player back to the field.
This portal is just a straightforward ‘passage’ (see chapter 6).
You can find heaven and portal in <i>object.txt</i>.
</li>
<li>Line 68-71:
Contrary to what the ancient pharaos believed,
you are going to heaven empty-handed.
Here, all your possessions are being moved to the field.
This makes it very easy for the player to reclaim them
after going through the portal.
Of course, we could also move each object back to its original location
(you may want to add an attribute <i>home</i> to <i>OBJECT</i>),
or make it even more challenging by moving them to random locations.
Do be careful with objects that are required to make progress through the game;
moving a key to a location behind the door it unlocks,
could make the quest impossible.
</li>
<li>Line 73-77:
It is possible player’s surroundings change
due to circumstances beyond player’s control.
For example, player may be transported to a different location (line 66),
or it may suddenly become dark (line 45).
That warrants the game automatically giving an updated look around.
</li>
</ul>
</div>
<p>
Functions <i>dealDamage</i> and <i>getOptimalWeapon</i>
are implemented in the following module.
Separating them from <i>turn.c</i> makes sense,
because we will need the same functionality once again
as we implement an ‘attack’ command
by the end of this chapter.
</p>
<table class="code"><tr>
<th>damage.h</th>
</tr><tr>
<td>
<ol>
<li class="new">extern void dealDamage(OBJECT *attacker, OBJECT *weapon, OBJECT *victim);</li>
<li class="new">extern OBJECT *getOptimalWeapon(OBJECT *attacker);</li>
</ol>
</td>
</tr><tr>
<th>damage.c</th>
</tr><tr>
<td>
<ol>
<li class="new">#include <stdbool.h></li>
<li class="new">#include <stdlib.h></li>
<li class="new">#include <stdio.h></li>
<li class="new">#include "object.h"</li>
<li class="new">#include "misc.h"</li>
<li class="new"></li>
<li class="new">static void describeAttack(OBJECT *attacker, OBJECT *victim, OBJECT *weapon)</li>
<li class="new">{</li>
<li class="new"> const char *weaponDescription = weapon == attacker ? "bare hands"</li>
<li class="new"> : weapon->description;</li>
<li class="new"> if (attacker == player)</li>
<li class="new"> {</li>
<li class="new"> printf("You hit %s with %s.\n", victim->description, weaponDescription);</li>
<li class="new"> }</li>
<li class="new"> else if (victim == player)</li>
<li class="new"> {</li>
<li class="new"> printf("You are hit by %s with %s.\n",</li>
<li class="new"> attacker->description, weaponDescription);</li>
<li class="new"> }</li>
<li class="new"> else</li>
<li class="new"> {</li>
<li class="new"> printf("You see %s hit %s with %s.\n",</li>
<li class="new"> attacker->description, victim->description, weaponDescription);</li>
<li class="new"> }</li>
<li class="new">}</li>
<li class="new"></li>
<li class="new">static void describeDeath(OBJECT *victim)</li>
<li class="new">{</li>
<li class="new"> if (victim == player)</li>
<li class="new"> {</li>
<li class="new"> printf("You die.\n");</li>
<li class="new"> }</li>
<li class="new"> else</li>
<li class="new"> {</li>
<li class="new"> printf("You see %s die.\n", victim->description);</li>
<li class="new"> }</li>
<li class="new">}</li>
<li class="new"></li>
<li class="new">void dealDamage(OBJECT *attacker, OBJECT *weapon, OBJECT *victim)</li>
<li class="new">{</li>
<li class="new"> int damage = (rand() % 6) * weapon->impact * attacker->health / 100;</li>
<li class="new"> if (damage < 0)</li>
<li class="new"> {</li>
<li class="new"> if (victim->health > 0)</li>
<li class="new"> {</li>
<li class="new"> describeAttack(attacker, victim, weapon);</li>
<li class="new"> victim->health += damage;</li>
<li class="new"> if (victim->health <= 0)</li>
<li class="new"> {</li>
<li class="new"> victim->health = 0;</li>
<li class="new"> describeDeath(victim);</li>
<li class="new"> }</li>
<li class="new"> if (attacker == player)</li>
<li class="new"> {</li>
<li class="new"> victim->trust--;</li>
<li class="new"> }</li>
<li class="new"> }</li>
<li class="new"> else if (attacker == player)</li>
<li class="new"> {</li>
<li class="new"> printf("That will have little effect; %s is already dead.\n",</li>
<li class="new"> victim->description);</li>
<li class="new"> }</li>
<li class="new"> }</li>
<li class="new"> else if (attacker == player)</li>
<li class="new"> {</li>
<li class="new"> printf("You try to hit %s with %s, but you miss.\n",</li>
<li class="new"> victim->description,</li>
<li class="new"> weapon == attacker ? "bare hands" : weapon->description);</li>
<li class="new"> }</li>
<li class="new">}</li>
<li class="new"></li>
<li class="new">OBJECT *getOptimalWeapon(OBJECT *attacker)</li>
<li class="new">{</li>
<li class="new"> OBJECT *obj, *weapon = attacker;</li>
<li class="new"> for (obj = objs; obj < endOfObjs; obj++)</li>
<li class="new"> {</li>
<li class="new"> if (isHolding(attacker, obj) && obj->impact < weapon->impact)</li>
<li class="new"> {</li>
<li class="new"> weapon = obj;</li>
<li class="new"> }</li>
<li class="new"> }</li>
<li class="new"> return weapon;</li>
<li class="new">}</li>
</ol>
</td>
</tr></table>
<div class="explanation">
<p>
Explanation:
</p>
<ul>
<li>Line 7-25:
a helper function that generates descriptive text
about attacks taking place during combat.
This covers player attacking NPC (line 12),
NPC attacking player (lines 16-17)
and even NPC attacking NPC (lines 21-22).
The latter could be useful in a game
where the player can team up with friendly NPCs.
</li>
<li>Line 27-37:
another helper function, this time to give descriptive text
about a character dying in combat.
As in the previous function,
attacker and victim can be NPC as well as player.
</li>
<li>Line 41:
this is the ‘damage formula’.
By convention, I will let ‘damage’ be a negative number,
reserving positive numbers for actions
that have a positive effect on a character’s health
(e.g. drinking a healing potion).
</li>
<li>Line 42:
damage has a 1 to 6 chance of being zero;
even more so if attacker and weapon are too weak.
If damage is zero, then execution will continue on line 64,
where we will explain the attack had no effect.
</li>
<li>Line 55:
attacking an NPC has a (negative) effect not only on health,
but also on the NPC’s trust towards the player.
This will have its effect on the NPC’s behavior towards the player.
We already saw an example of this in <i>turn.c</i>.
</li>
<li>Line 64:
we should respond to every command from the player,
but it is not necessary to apologize
for every missed opportunity by a NPC to deal damage.
</li>
<li>Line 77:
you may already have noticed the weapon’s ‘impact’
(another new attribute) as part of the damage formula (line 41).
As explained, we will be using negative numbers.
This explains why there is a ‘less than’ operator here:
the best weapon is the one with the smallest (most negative) impact.
</li>
</ul>
</div>
<p>
Now that we have given other characters the means to attack the player,
it’s time to let the player return the favor!
</p>
<table class="code"><tr>
<th>parsexec.c</th>
</tr><tr>
<td>
<ol>
<li class="old">#include <ctype.h></li>
<li class="old">#include <stdbool.h></li>
<li class="old">#include <stdio.h></li>
<li class="old">#include "object.h"</li>
<li class="old">#include "misc.h"</li>
<li class="old">#include "match.h"</li>
<li class="old">#include "location.h"</li>
<li class="old">#include "inventory.h"</li>
<li class="old">#include "inventory2.h"</li>
<li class="old">#include "openclose.h"</li>
<li class="old">#include "onoff.h"</li>
<li class="old">#include "talk.h"</li>
<li class="new">#include "attack.h"</li>
<li class="old"></li>
<li class="old">typedef struct</li>
<li class="old">{</li>
<li class="old"> const char *pattern;</li>
<li class="new"><span class="old"> </span>int<span class="old"> (*function)(void);</span></li>
<li class="old">} COMMAND;</li>
<li class="old"></li>
<li class="new"><span class="old">static </span>int<span class="old"> executeQuit(void)</span></li>
<li class="old">{</li>
<li class="new"><span class="old"> return </span>-1;</li>
<li class="old">}</li>
<li class="old"></li>
<li class="new"><span class="old">static </span>int<span class="old"> executeNoMatch(void)</span></li>
<li class="old">{</li>
<li class="old"> const char *src = *params;</li>
<li class="old"> int len;</li>
<li class="old"> for (len = 0; src[len] != '\0' && !isspace(src[len]); len++);</li>
<li class="old"> if (len > 0) printf("I don't know how to '%.*s'.\n", len, src);</li>
<li class="new"><span class="old"> return </span>0;</li>
<li class="new">}</li>
<li class="new"></li>
<li class="new">static int executeWait(void)</li>
<li class="new">{</li>
<li class="new"> printf("Some time passes...\n");</li>
<li class="new"> return 1;</li>
<li class="old">}</li>
<li class="old"></li>
<li class="new">int<span class="old"> parseAndExecute(const char *input)</span></li>
<li class="old">{</li>
<li class="old"> static const COMMAND commands[] =</li>
<li class="old"> {</li>
<li class="old"> { "quit" , executeQuit },</li>
<li class="old"> { "look" , executeLookAround },</li>
<li class="old"> { "look around" , executeLookAround },</li>
<li class="old"> { "look at A" , executeLook },</li>
<li class="old"> { "look A" , executeLook },</li>
<li class="old"> { "examine A" , executeLook },</li>
<li class="old"> { "go to A" , executeGo },</li>
<li class="old"> { "go A" , executeGo },</li>
<li class="old"> { "get A from B" , executeGetFrom },</li>
<li class="old"> { "get A" , executeGet },</li>
<li class="old"> { "put A in B" , executePutIn },</li>
<li class="old"> { "drop A in B" , executePutIn },</li>
<li class="old"> { "drop A" , executeDrop },</li>
<li class="old"> { "ask A from B" , executeAskFrom },</li>
<li class="old"> { "ask A" , executeAsk },</li>
<li class="old"> { "give A to B" , executeGiveTo },</li>
<li class="old"> { "give A" , executeGive },</li>
<li class="old"> { "inventory" , executeInventory },</li>
<li class="old"> { "open A" , executeOpen },</li>
<li class="old"> { "close A" , executeClose },</li>
<li class="old"> { "lock A" , executeLock },</li>
<li class="old"> { "unlock A" , executeUnlock },</li>
<li class="old"> { "turn on A" , executeTurnOn },</li>
<li class="old"> { "turn off A" , executeTurnOff },</li>
<li class="old"> { "turn A on" , executeTurnOn },</li>
<li class="old"> { "turn A off" , executeTurnOff },</li>
<li class="old"> { "talk with B about A" , executeTalkTo },</li>
<li class="old"> { "talk about A with B" , executeTalkTo },</li>
<li class="old"> { "talk about A" , executeTalk },</li>
<li class="new"><span class="old"> { "talk A" , executeTalk </span>},</li>
<li class="new"> { "attack with B" , executeAttack },</li>
<li class="new"> { "attack A with B" , executeAttack },</li>
<li class="new"> { "attack A" , executeAttack },</li>
<li class="new"> { "wait" , executeWait<span class="old"> },</span></li>
<li class="old"> { "A" , executeNoMatch }</li>
<li class="old"> };</li>
<li class="old"> const COMMAND *cmd;</li>
<li class="old"> for (cmd = commands; !matchCommand(input, cmd->pattern); cmd++);</li>
<li class="old"> return (*cmd->function)();</li>
<li class="old">}</li>
</ol>
</td>
</tr></table>
<div class="explanation">
<p>
Explanation:
</p>
<ul>
<li>Line 18, 21, 26, 41:
we are changing the return type of the command functions
from <i>bool</i> to <i>int</i>.
This is a sweeping change through a lot of modules
(<i>inventory.c</i>, <i>inventory2.c</i>, <i>location.c</i>,
<i>move.c</i>, <i>onoff.c</i>, <i>openclose.c</i>, <i>talk.c</i>).
Unsurprising; for every command, we need to make up our minds
how many time unit are being consumed by the execution of that command.
</li>
<li>Line 23:
every command function should return the number of time units consumed.
<i>Quit</i> is the exception to the rule: it returns -1,
to signal the main loop that the program should end.
</li>
<li>Line 32:
here you see one of the situations where a command function returns zero.
The command has not been recognized, either because the player made a typo,
or because the game’s vocabulair is too limited.
Neither is considered part of the story; no game time passes.
</li>
<li>Line 35-39, 78:
with the introduction of ‘time’,
there should also be a command that allows the player
to just let time pass without actually doing anything.
This may seem useless, but it can be fun to have a puzzle in the game
that actually relies on the execution of this command.
Patience is a virtue, so why not reward it?
</li>
<li>Line 75-77:
we are introducing a new command ‘attack’, with two arguments:
A represents the victim, B the weapon.
Both are optional; below we will see how this is handled.
Of course, you can register as many synonyms as you like:
<i>hit</i>, <i>kill</i>, <i>stab</i>, <i>slay</i>...
</li>
</ul>
</div>
<p>
It is time to implement the command ‘attack’.
</p>
<table class="code"><tr>
<th>attack.h</th>
</tr><tr>
<td>
<ol>
<li class="new">extern int executeAttack(void);</li>
</ol>
</td>
</tr><tr>
<th>attack.c</th>
</tr><tr>
<td>
<ol>
<li class="new">#include <stdbool.h></li>
<li class="new">#include <stdio.h></li>
<li class="new">#include "object.h"</li>
<li class="new">#include "misc.h"</li>
<li class="new">#include "match.h"</li>
<li class="new">#include "noun.h"</li>
<li class="new">#include "reach.h"</li>
<li class="new">#include "damage.h"</li>
<li class="new"></li>
<li class="new">static OBJECT *victimHere()</li>
<li class="new">{</li>
<li class="new"> OBJECT *victim = actorHere();</li>
<li class="new"> if (victim == NULL)</li>
<li class="new"> {</li>
<li class="new"> printf("There is nobody here to attack.\n");</li>
<li class="new"> }</li>
<li class="new"> return victim;</li>
<li class="new">}</li>
<li class="new"></li>
<li class="new">int executeAttack(void)</li>
<li class="new">{</li>
<li class="new"> OBJECT *victim =</li>
<li class="new"> *params[0] == '\0' ? victimHere()</li>
<li class="new"> : reachableObject("who to attack", params[0]);</li>
<li class="new"> if (victim != NULL)</li>
<li class="new"> {</li>
<li class="new"> OBJECT *weapon =</li>
<li class="new"> *params[1] == '\0' ? getOptimalWeapon(player)</li>
<li class="new"> : getPossession(player, "wield", params[1]);</li>
<li class="new"> if (weapon != NULL)</li>
<li class="new"> {</li>
<li class="new"> dealDamage(player, weapon, victim);</li>
<li class="new"> return 1;</li>
<li class="new"> }</li>
<li class="new"> }</li>
<li class="new"> return 0;</li>
<li class="new">}</li>
</ol>
</td>
</tr></table>
<div class="explanation">
<p>
Explanation:
</p>
<ul>
<li>Lines 10-18, 23:
a little helper function in case the command is given without a victim.
It extends upon function <i>actorHere</i>, which is used
in a similar way for commands <i>ask</i>, <i>give</i> and <i>talk</i>.
</li>
<li>Line 28:
the command can also be given without explicitly specifying a weapon.
In that case, the best weapon at hand will be used.
For this, we use the same function <i>getOptimalWeapon</i> that was
used in <i>turn.c</i> to let non-player characters choose their weapon.
</li>
<li>Line 32:
<i>dealDamage</i> is another function that we were already using
in <i>turn.c</i> to let non-player character make their move.
This time, the player is the attacker rather than the victim.
</li>
</ul>
</div>
<p>
Finally, here are the new attributes,
the weapons and the respawn location.
</p>
<img class="genmap" src="code20/map.png" />
<table class="code"><tr>
<th>object.txt</th>
</tr><tr>
<td>
<ol>
<li class="old">#include <stdbool.h></li>
<li class="old">#include <stdio.h></li>
<li class="old">#include "object.h"</li>
<li class="old">#include "toggle.h"</li>
<li class="old"></li>
<li class="old">typedef struct object {</li>
<li class="old"> bool (*condition)(void);</li>
<li class="old"> const char *description;</li>
<li class="old"> const char **tags;</li>
<li class="old"> struct object *location;</li>
<li class="old"> struct object *destination;</li>
<li class="old"> struct object *prospect;</li>
<li class="old"> const char *details;</li>
<li class="old"> const char *contents;</li>
<li class="old"> const char *textGo;</li>
<li class="old"> const char *gossip;</li>
<li class="old"> int weight;</li>
<li class="old"> int capacity;</li>
<li class="old"> int health;</li>
<li class="old"> int light;</li>
<li class="new"><span class="old"> </span>int impact;</li>
<li class="new"> int trust;</li>
<li class="old"> void (*open)(void);</li>
<li class="old"> void (*close)(void);</li>
<li class="old"> void (*lock)(void);</li>
<li class="old"> void (*unlock)(void);</li>
<li class="old">} OBJECT;</li>
<li class="old"></li>
<li class="old">extern OBJECT objs[];</li>
<li class="old"></li>
<li class="new"><span class="old">- </span>heaven</li>
<li class="new"> description "little heaven"</li>
<li class="new"> tags "heaven", "little heaven"</li>
<li class="new"> details "Everything looks so peaceful here."</li>
<li class="new"> gossip "It's where all the good adventurers go."</li>
<li class="new"> capacity 9999</li>
<li class="new"> light 100</li>
<li class="new"></li>
<li class="new">- respawn</li>
<li class="new"> description "a respawn portal"</li>
<li class="new"> tags "portal", "respawn portal"</li>
<li class="new"> location heaven</li>
<li class="new"> destination field</li>
<li class="new"> details "Looks like a gateway into the unknown."</li>
<li class="new"> textGo "A bright flash of light, and you are back in the field."</li>
<li class="new"> open isAlreadyOpen</li>
<li class="new"></li>
<li class="new">- heavenEWNS</li>