forked from munificent/game-programming-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.html
More file actions
920 lines (820 loc) · 59.8 KB
/
Copy pathstate.html
File metadata and controls
920 lines (820 loc) · 59.8 KB
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>State · Design Patterns Revisited · Game Programming Patterns</title>
<!-- Tell mobile browsers we're optimized for them and they don't need to crop
the viewport. -->
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="style.css" />
<link href="http://fonts.googleapis.com/css?family=Merriweather:400,400italic,700,700italic|Source+Code+Pro|Source+Sans+Pro:200,300,400,600,400italic,600italic|Rock+Salt" rel="stylesheet" type="text/css">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-42804721-1', 'gameprogrammingpatterns.com');
ga('send', 'pageview');
</script>
<script src="jquery-1.10.1.min.js"></script>
<script src="script.js"></script>
</head>
<body id="top">
<div class="page sidebar">
<div class="content">
<nav class="top">
<span class="prev">← <a href="singleton.html">Previous Chapter</a></span>
<span class="next"><a href="sequencing-patterns.html">Next Chapter</a> →</span>
<span class="toc">≡ <a href="/">The Book</a></span>
</nav>
<h1>State</h1>
<h1 class="book"><a href="/">Game Programming Patterns</a><span class="section"><a href="design-patterns-revisited.html">Design Patterns Revisited</a></span></h1>
<p>Confession time: I went a little overboard and packed way too much into this
chapter. It’s ostensibly about the <a
href="http://en.wikipedia.org/wiki/State_pattern" class="gof-pattern">State</a>
design pattern, but I can’t talk about that and games without going into the
more fundamental concept of <em>finite state machines</em> (or “FSMs”). But then once I
went there, I figured I might as well introduce <em>hierarchical state machines</em>
and <em>pushdown automata</em>.</p>
<p>That’s a lot to cover, so to keep things as short as possible, the code samples
here leave out a few details that you’ll have to fill in on your own. I hope
they’re still clear enough for you to get the big picture.</p>
<p>Don’t feel sad if you’ve never heard of a state machine. While well known to
<span name="two-camps">AI and compiler</span> hackers, they aren’t that familiar
to other programming circles. I think they should be more widely known, so I’m
going to throw them at a different kind of problem here.</p>
<aside name="two-camps">
<p>This pairing echoes the early days of artificial intelligence. In the ’50s and
’60s, much of AI research was focused on language processing. Many of the
techniques compilers now use for parsing programming languages were invented for
parsing human languages.</p>
</aside>
<h2><a href="#we've-all-been-there" name="we've-all-been-there">We’ve All Been There</a></h2>
<p>We’re working on a little side-scrolling platformer. Our job is to implement the
heroine that is the player’s avatar in the game world. That means making her
respond to user input. Push the B button and she should jump. Simple enough:</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_B</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">yVelocity_</span> <span class="o">=</span> <span class="n">JUMP_VELOCITY</span><span class="p">;</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_JUMP</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>Spot the bug?</p>
<p>There’s nothing to prevent “air jumping” — keep hammering B while she’s in the
air, and she will float forever. The simple <span name="landing">fix</span> is to
add an <code>isJumping_</code> Boolean field to <code>Heroine</code> that tracks when she’s jumping,
and then do:</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_B</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isJumping_</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">isJumping_</span> <span class="o">=</span> <span class="nb">true</span><span class="p">;</span>
<span class="c1">// Jump...</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
<aside name="landing">
<p>There should also be code that sets <code>isJumping_</code> back to <code>false</code> when the
heroine touches the ground. I’ve omitted that here for brevity’s sake.</p>
</aside>
<p>Next, we want the heroine to duck if the player presses down while she’s on the
ground and stand back up when the button is released:</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_B</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Jump if not jumping...</span>
<span class="p">}</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isJumping_</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_DUCK</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">RELEASE_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_STAND</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>Spot the bug this time?</p>
<p>With this code, the player could:</p>
<ol>
<li>Press down to duck.</li>
<li>Press B to jump from a ducking position.</li>
<li>Release down while still in the air.</li>
</ol>
<p>The heroine will switch to her standing graphic in the middle of the jump. Time
for another flag…</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_B</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isJumping_</span> <span class="o">&&</span> <span class="o">!</span><span class="n">isDucking_</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Jump...</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isJumping_</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">isDucking_</span> <span class="o">=</span> <span class="nb">true</span><span class="p">;</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_DUCK</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">RELEASE_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">isDucking_</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">isDucking_</span> <span class="o">=</span> <span class="nb">false</span><span class="p">;</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_STAND</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>Next, it would be cool if the heroine did a dive attack if the player presses
down in the middle of a jump:</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_B</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isJumping_</span> <span class="o">&&</span> <span class="o">!</span><span class="n">isDucking_</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Jump...</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isJumping_</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">isDucking_</span> <span class="o">=</span> <span class="nb">true</span><span class="p">;</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_DUCK</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">else</span>
<span class="p">{</span>
<span class="n">isJumping_</span> <span class="o">=</span> <span class="nb">false</span><span class="p">;</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_DIVE</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">RELEASE_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">isDucking_</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Stand...</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>Bug hunting time again. Find it?</p>
<p>We check that you can’t air jump while jumping, but not while diving. Yet
another field…</p>
<p>Something is clearly <span name="se">wrong</span> with our approach. Every time
we touch this handful of code, we break something. We need to add a bunch more
moves — we haven’t even added <em>walking</em> yet — but at this rate, it will
collapse into a heap of bugs before we’re done with it.</p>
<aside name="se">
<p>Those coders you idolize who always seem to create flawless code aren’t simply
superhuman programmers. Instead, they have an intuition about which <em>kinds</em> of
code are error-prone, and they steer away from them.</p>
<p>Complex branching and mutable state — fields that change over time — are two
of those error-prone kinds of code, and the examples above have both.</p>
</aside>
<h2><a href="#finite-state-machines-to-the-rescue" name="finite-state-machines-to-the-rescue">Finite State Machines to the Rescue</a></h2>
<p>In a fit of frustration, you sweep everything off your desk except a pen and
paper and start drawing a flowchart. You draw a box for each thing the heroine
can be doing: standing, jumping, ducking, and diving. When she can respond to a
button press in one of those states, you draw an arrow from that box, label it
with that button, and connect it to the state she changes to.</p>
<p><img src="images/state-flowchart.png" alt="A flowchart containing boxes for Standing, Jumping, Diving, and Ducking. Arrows for button presses and releases connect some of the boxes." /></p>
<p>Congratulations, you’ve just created a <em>finite state machine</em>. These came out of
a branch of computer science called <em>automata theory</em> whose family of data
structures also includes the famous Turing machine. FSMs are the simplest member
of that family.</p>
<p>The <span name="adventure">gist</span> is:</p>
<ul>
<li>
<p><strong>You have a fixed <em>set of states</em> that the machine can be in.</strong> For our
example, that’s standing, jumping, ducking, and diving.</p>
</li>
<li>
<p><strong>The machine can only be in <em>one</em> state at a time.</strong> Our heroine can’t be
jumping and standing simultaneously. In fact, preventing that is one reason
we’re going to use an FSM.</p>
</li>
<li>
<p><strong>A sequence of <em>inputs</em> or <em>events</em> is sent to the machine.</strong> In our example,
that’s the raw button presses and releases.</p>
</li>
<li>
<p><strong>Each state has a <em>set of transitions</em>, each associated with an input and
pointing to a state.</strong> When an input comes in, if it matches a transition for
the current state, the machine changes to the state that transition points
to.</p>
<p>For example, pressing down while standing transitions to the ducking state. Pressing down while jumping transitions to diving. If no transition is defined for an input on the current state, the input is ignored.</p>
</li>
</ul>
<p>In their pure form, that’s the whole banana: states, inputs, and transitions.
You can draw it out like a little flowchart. Unfortunately, the compiler doesn’t
recognize our scribbles, so how do we go about <em>implementing</em> one? The Gang of
Four’s State pattern is one method — which we’ll get to — but let’s start simpler.</p>
<aside name="adventure">
<p>My favorite analogy for FSMs is the old text adventure games like Zork. You have
a world of rooms that are connected to each other by exits. You explore them by
entering commands like “go north”.</p>
<p>This maps directly to a state machine: Each room is a state. The room you’re in
is the current state. Each room’s exits are its transitions. The navigation
commands are the inputs.</p>
</aside>
<h2><a href="#enums-and-switches" name="enums-and-switches">Enums and Switches</a></h2>
<p>One problem our <code>Heroine</code> class has is some combinations of those Boolean fields
aren’t valid: <code>isJumping_</code> and <code>isDucking_</code> should never both be true, for
example. When you have a handful of flags where only one is <code>true</code> at a time,
that’s a hint that what you really want is an <code>enum</code>.</p>
<p>In this case, that <code>enum</code> is exactly the set of states for our FSM, so let’s
define that:</p>
<div class="codehilite"><pre><span class="k">enum</span> <span class="n">State</span>
<span class="p">{</span>
<span class="n">STATE_STANDING</span><span class="p">,</span>
<span class="n">STATE_JUMPING</span><span class="p">,</span>
<span class="n">STATE_DUCKING</span><span class="p">,</span>
<span class="n">STATE_DIVING</span>
<span class="p">};</span>
</pre></div>
<p>Instead of a bunch of flags, <code>Heroine</code> will just have one <code>state_</code> field. We
also flip the order of our branching. In the previous code, we switched on
input, <em>then</em> on state. This kept the code for handling one button press
together, but it smeared around the code for one state. We want to keep that
together, so we switch on state first. That gives us:</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">switch</span> <span class="p">(</span><span class="n">state_</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">case</span> <span class="n">STATE_STANDING</span>:
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_B</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">state_</span> <span class="o">=</span> <span class="n">STATE_JUMPING</span><span class="p">;</span>
<span class="n">yVelocity_</span> <span class="o">=</span> <span class="n">JUMP_VELOCITY</span><span class="p">;</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_JUMP</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">state_</span> <span class="o">=</span> <span class="n">STATE_DUCKING</span><span class="p">;</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_DUCK</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">break</span><span class="p">;</span>
<span class="k">case</span> <span class="n">STATE_JUMPING</span>:
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">state_</span> <span class="o">=</span> <span class="n">STATE_DIVING</span><span class="p">;</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_DIVE</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">break</span><span class="p">;</span>
<span class="k">case</span> <span class="n">STATE_DUCKING</span>:
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">RELEASE_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">state_</span> <span class="o">=</span> <span class="n">STATE_STANDING</span><span class="p">;</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_STAND</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">break</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>This seems trivial, but it’s a real improvement over the previous code. We still
have some conditional branching, but we simplified the <span
name="invalid">mutable</span> state to a single field. All of the code for
handling a single state is now nicely lumped together. This is the simplest way
to implement a state machine and is fine for some uses.</p>
<aside name="invalid">
<p>In particular, the heroine can no longer be in an <em>invalid</em> state. With the
Boolean flags, some sets of values were possible but meaningless. With the <code>enum</code>,
each value is valid.</p>
</aside>
<p>Your problem may outgrow this solution, though. Say we want to add a move where
our heroine can duck for a while to charge up and unleash a special attack.
While she’s ducking, we need to track the charge time.</p>
<p>We add a <code>chargeTime_</code> field to <code>Heroine</code> to store how long the attack has
charged. Assume we already have an <span name="update"><code>update()</code></span> that
gets called each frame. In there, we add:</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">update</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">state_</span> <span class="o">==</span> <span class="n">STATE_DUCKING</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">chargeTime_</span><span class="o">++</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">chargeTime_</span> <span class="o">></span> <span class="n">MAX_CHARGE</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">superBomb</span><span class="p">();</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
<aside name="update">
<p>If you guessed that this is the <a href="update-method.html"
class="pattern">Update Method</a> pattern, you win a prize!</p>
</aside>
<p>We need to reset the timer when she starts ducking, so we modify
<code>handleInput()</code>:</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">switch</span> <span class="p">(</span><span class="n">state_</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">case</span> <span class="n">STATE_STANDING</span>:
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">state_</span> <span class="o">=</span> <span class="n">STATE_DUCKING</span><span class="p">;</span>
<span class="n">chargeTime_</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_DUCK</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// Handle other inputs...</span>
<span class="k">break</span><span class="p">;</span>
<span class="c1">// Other states...</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>All in all, to add this charge attack, we had to modify two methods and add a
<code>chargeTime_</code> field onto <code>Heroine</code> even though it’s only meaningful while in
the ducking state. What we’d prefer is to have all of that code and data nicely
wrapped up in one place. The Gang of Four has us covered.</p>
<h2><a href="#the-state-pattern" name="the-state-pattern">The State Pattern</a></h2>
<p>For people deeply into the object-oriented mindset, every conditional <span
name="branch">branch</span> is an opportunity to use dynamic dispatch (in other
words a virtual method call in C++). I think you can go too far down that
rabbit hole. Sometimes an <code>if</code> is all you need.</p>
<aside name="branch">
<p>There’s a historical basis for this. Many of the original object-oriented
apostles like <em>Design Patterns</em>‘ Gang of Four, and <em>Refactoring</em>‘s Martin Fowler
came from Smalltalk. There, <code>ifThen:</code> is just a method you invoke on the
condition, which is implemented differently by the <code>true</code> and <code>false</code> objects.</p>
</aside>
<p>But in our example, we’ve reached a tipping point where something
object-oriented is a better fit. That gets us to the State pattern. In the words
of the Gang of Four:</p>
<blockquote>
<p>Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.</p>
</blockquote>
<p>That doesn’t tell us much. Heck, our <code>switch</code> does that. The concrete pattern
they describe looks like this when applied to our heroine:</p>
<h3><a href="#a-state-interface" name="a-state-interface">A state interface</a></h3>
<p>First, we define an interface for the state. Every bit of behavior that is
state-dependent — every place we had a <code>switch</code> before — becomes a virtual
method in that interface. For us, that’s <code>handleInput()</code> and <code>update()</code>:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">HeroineState</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">virtual</span> <span class="o">~</span><span class="n">HeroineState</span><span class="p">()</span> <span class="p">{}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">handleInput</span><span class="p">(</span><span class="n">Heroine</span><span class="o">&</span> <span class="n">heroine</span><span class="p">,</span> <span class="n">Input</span> <span class="n">input</span><span class="p">)</span> <span class="p">{}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">update</span><span class="p">(</span><span class="n">Heroine</span><span class="o">&</span> <span class="n">heroine</span><span class="p">)</span> <span class="p">{}</span>
<span class="p">};</span>
</pre></div>
<h3><a href="#classes-for-each-state" name="classes-for-each-state">Classes for each state</a></h3>
<p>For each state, we define a class that implements the interface. Its methods
define the heroine’s behavior when in that state. In other words, take each <code>case</code>
from the earlier <code>switch</code> statements and move them into their state’s class. For example:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">DuckingState</span> <span class="o">:</span> <span class="k">public</span> <span class="n">HeroineState</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="n">DuckingState</span><span class="p">()</span>
<span class="o">:</span> <span class="n">chargeTime_</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="p">{}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">handleInput</span><span class="p">(</span><span class="n">Heroine</span><span class="o">&</span> <span class="n">heroine</span><span class="p">,</span> <span class="n">Input</span> <span class="n">input</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">RELEASE_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Change to standing state...</span>
<span class="n">heroine</span><span class="p">.</span><span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_STAND</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">update</span><span class="p">(</span><span class="n">Heroine</span><span class="o">&</span> <span class="n">heroine</span><span class="p">)</span> <span class="p">{</span>
<span class="n">chargeTime_</span><span class="o">++</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">chargeTime_</span> <span class="o">></span> <span class="n">MAX_CHARGE</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">heroine</span><span class="p">.</span><span class="n">superBomb</span><span class="p">();</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="nl">private:</span>
<span class="kt">int</span> <span class="n">chargeTime_</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
<p>Note that we also moved <code>chargeTime_</code> out of <code>Heroine</code> and into the <code>DuckingState</code>
class. This is great — that piece of data is only meaningful while in that state,
and now our object model reflects that explicitly.</p>
<h3><a href="#delegate-to-the-state" name="delegate-to-the-state">Delegate to the state</a></h3>
<p>Next, we give the <code>Heroine</code> a pointer to her current state, lose each big <code>switch</code>, and delegate to the state instead:</p>
<p><span name="delegate"></span></p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Heroine</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">state_</span><span class="o">-></span><span class="n">handleInput</span><span class="p">(</span><span class="o">*</span><span class="k">this</span><span class="p">,</span> <span class="n">input</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">update</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">state_</span><span class="o">-></span><span class="n">update</span><span class="p">(</span><span class="o">*</span><span class="k">this</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// Other methods...</span>
<span class="nl">private:</span>
<span class="n">HeroineState</span><span class="o">*</span> <span class="n">state_</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
<p>In order to “change state”, we just need to assign <code>state_</code> to point to a
different <code>HeroineState</code> object. That’s the State pattern in its entirety.</p>
<aside name="delegate">
<p>This looks like the <a href="http://en.wikipedia.org/wiki/Strategy_pattern"
class="gof-pattern">Strategy</a> and <a href="type-object.html"
class="pattern">Type Object</a> patterns. In all three, you have a main object
that delegates to another subordinate one. The difference is <em>intent</em>.</p>
<ul>
<li>
<p>With Strategy, the goal is to <em>decouple</em> the main class from some portion of
its behavior.</p>
</li>
<li>
<p>With Type Object, the goal is to make a <em>number</em> of objects behave similarly
by <em>sharing</em> a reference to the same type object.</p>
</li>
<li>
<p>With State, the goal is for the main object to <em>change</em> its behavior by
<em>changing</em> the object it delegates to.</p>
</li>
</ul>
</aside>
<h2><a href="#where-are-the-state-objects" name="where-are-the-state-objects">Where Are the State Objects?</a></h2>
<p>I did gloss over one bit here. To change states, we need to assign <code>state_</code> to
point to the new one, but where does that object come from? With our <code>enum</code>
implementation, that was a no-brainer — <code>enum</code> values are primitives like
numbers. But now our states are classes, which means we need an actual instance
to point to. There are two common answers to this:</p>
<h3><a href="#static-states" name="static-states">Static states</a></h3>
<p>If the state object doesn’t have any other <span name="fn">fields</span>, then
the only data it stores is a pointer to the internal virtual method table so
that its methods can be called. In that case, there’s no reason to ever have
more than one instance of it. Every instance would be identical anyway.</p>
<aside name="fn">
<p>If your state has no fields and only <em>one</em> virtual method in it, you can
simplify this pattern even more. Replace each state <em>class</em> with a state
<em>function</em> — just a plain vanilla top-level function. Then, the <code>state_</code> field
in your main class becomes a simple function pointer.</p>
</aside>
<p>In that case, you can make a single <em>static</em> instance. Even if you have a
bunch of FSMs all going at the same time in that same state, they can all point
to the <span name="flyweight">same instance</span> since it has nothing
machine-specific about it.</p>
<aside name="flyweight">
<p>This is the <a href="flyweight.html" class="gof-pattern">Flyweight</a> pattern.</p>
</aside>
<p><em>Where</em> you put that static instance is up to you. Find a place that makes
sense. For no particular reason, let’s put ours inside the base state class:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">HeroineState</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">static</span> <span class="n">StandingState</span> <span class="n">standing</span><span class="p">;</span>
<span class="k">static</span> <span class="n">DuckingState</span> <span class="n">ducking</span><span class="p">;</span>
<span class="k">static</span> <span class="n">JumpingState</span> <span class="n">jumping</span><span class="p">;</span>
<span class="k">static</span> <span class="n">DivingState</span> <span class="n">diving</span><span class="p">;</span>
<span class="c1">// Other code...</span>
<span class="p">};</span>
</pre></div>
<p>Each of those static fields is the one instance of that state that the game
uses. To make the heroine jump, the standing state would do something like:</p>
<div class="codehilite"><pre><span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_B</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">heroine</span><span class="p">.</span><span class="n">state_</span> <span class="o">=</span> <span class="o">&</span><span class="n">HeroineState</span><span class="o">::</span><span class="n">jumping</span><span class="p">;</span>
<span class="n">heroine</span><span class="p">.</span><span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_JUMP</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
<h3><a href="#instantiated-states" name="instantiated-states">Instantiated states</a></h3>
<p>Sometimes, though, this doesn’t fly. A static state won’t work for the ducking
state. It has a <code>chargeTime_</code> field, and that’s specific to the heroine that
happens to be ducking. This may coincidentally work in our game if there’s only
one heroine, but if we try to add two-player co-op and have two heroines on
screen at the same time, we’ll have problems.</p>
<p>In that case, we have to <span name="fragment">create</span> a state
object when we transition to it. This lets each FSM have its own instance of the state. Of course, if we’re allocating a <em>new</em> state, that means we need to free the <em>current</em> one. We have to be careful here, since the code that’s triggering the change is in a method in the current state. We don’t want to delete <code>this</code> out from under ourselves.</p>
<p>Instead, we’ll allow <code>handleInput()</code> in <code>HeroineState</code> to optionally return a new state. When it does, <code>Heroine</code> will delete the old one and swap in the new one, like so:</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">HeroineState</span><span class="o">*</span> <span class="n">state</span> <span class="o">=</span> <span class="n">state_</span><span class="o">-></span><span class="n">handleInput</span><span class="p">(</span><span class="o">*</span><span class="k">this</span><span class="p">,</span> <span class="n">input</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">state</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">delete</span> <span class="n">state_</span><span class="p">;</span>
<span class="n">state_</span> <span class="o">=</span> <span class="n">state</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>That way, we don’t delete the previous state until we’ve returned from its method. Now, the standing state can transition to ducking by creating a new instance:</p>
<div class="codehilite"><pre><span class="n">HeroineState</span><span class="o">*</span> <span class="n">StandingState</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Heroine</span><span class="o">&</span> <span class="n">heroine</span><span class="p">,</span>
<span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Other code...</span>
<span class="k">return</span> <span class="k">new</span> <span class="n">DuckingState</span><span class="p">();</span>
<span class="p">}</span>
<span class="c1">// Stay in this state.</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>When I can, I prefer to use static states since they don’t burn memory and CPU cycles allocating objects
each state change. For states that are more, uh, <em>stateful</em>, though, this is the
way to go.</p>
<aside name="fragment">
<p>When you dynamically allocate states, you may have to worry about fragmentation.
The <a href="object-pool.html" class="pattern">Object Pool</a> pattern can help.</p>
</aside>
<h2><a href="#enter-and-exit-actions" name="enter-and-exit-actions">Enter and Exit Actions</a></h2>
<p>The goal of the State pattern is to encapsulate all of the behavior and data for
one state in a single class. We’re partway there, but we still have
some loose ends.</p>
<p>When the heroine changes state, we also switch her sprite. Right now, that code is owned by the state she’s switching <em>from</em>. When she goes from ducking to standing, the ducking state sets her image:</p>
<div class="codehilite"><pre><span class="n">HeroineState</span><span class="o">*</span> <span class="n">DuckingState</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Heroine</span><span class="o">&</span> <span class="n">heroine</span><span class="p">,</span>
<span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">RELEASE_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">heroine</span><span class="p">.</span><span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_STAND</span><span class="p">);</span>
<span class="k">return</span> <span class="k">new</span> <span class="nf">StandingState</span><span class="p">();</span>
<span class="p">}</span>
<span class="c1">// Other code...</span>
<span class="p">}</span>
</pre></div>
<p>What we really want is each state to control its own graphics. We can
handle that by giving the state an <em>entry action</em>:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">StandingState</span> <span class="o">:</span> <span class="k">public</span> <span class="n">HeroineState</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">enter</span><span class="p">(</span><span class="n">Heroine</span><span class="o">&</span> <span class="n">heroine</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">heroine</span><span class="p">.</span><span class="n">setGraphics</span><span class="p">(</span><span class="n">IMAGE_STAND</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// Other code...</span>
<span class="p">};</span>
</pre></div>
<p>Back in <code>Heroine</code>, we modify the code for handling state changes to call that
on the new state:</p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">HeroineState</span><span class="o">*</span> <span class="n">state</span> <span class="o">=</span> <span class="n">state_</span><span class="o">-></span><span class="n">handleInput</span><span class="p">(</span><span class="o">*</span><span class="k">this</span><span class="p">,</span> <span class="n">input</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">state</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">delete</span> <span class="n">state_</span><span class="p">;</span>
<span class="n">state_</span> <span class="o">=</span> <span class="n">state</span><span class="p">;</span>
<span class="c1">// Call the enter action on the new state.</span>
<span class="n">state_</span><span class="o">-></span><span class="n">enter</span><span class="p">(</span><span class="o">*</span><span class="k">this</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>This lets us simplify the ducking code to:</p>
<div class="codehilite"><pre><span class="n">HeroineState</span><span class="o">*</span> <span class="n">DuckingState</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Heroine</span><span class="o">&</span> <span class="n">heroine</span><span class="p">,</span>
<span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">RELEASE_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="k">new</span> <span class="n">StandingState</span><span class="p">();</span>
<span class="p">}</span>
<span class="c1">// Other code...</span>
<span class="p">}</span>
</pre></div>
<p>All it does is switch to standing and the standing state takes care of
the graphics. Now our states really are encapsulated. One particularly nice thing
about entry actions is that they run when you enter the state regardless of
which state you’re coming <em>from</em>.</p>
<p>Most real-world state graphs have multiple transitions into the same state. For
example, our heroine will also end up standing after she lands a jump or dive. That means we would end up duplicating some code everywhere that transition
occurs. Entry actions give us a place to consolidate that.</p>
<p>We can, of course, also extend this to support an <em>exit action</em>. This is just a
method we call on the state we’re <em>leaving</em> right before we switch to the new
state.</p>
<h2><a href="#what's-the-catch" name="what's-the-catch">What’s the Catch?</a></h2>
<p>I’ve spent all this time selling you on FSMs, and now I’m going to pull the rug
out from under you. Everything I’ve said so far is true, and FSMs are a good fit
for some problems. But their greatest virtue is also their greatest flaw.</p>
<p>State machines help you untangle hairy code by enforcing a very <span
name="turing">constrained</span> structure on it. All you’ve got is a fixed set
of states, a single current state, and some hardcoded transitions.</p>
<aside name="turing">
<p>A finite state machine isn’t even <em>Turing complete</em>. Automata theory describes
computation using a series of abstract models, each more complex than the
previous. A <em>Turing machine</em> is one of the most expressive models.</p>
<p>“Turing complete” means a system (usually a programming language) is powerful
enough to implement a Turing machine in it, which means all Turing complete
languages are, in some ways, equally expressive. FSMs are not flexible enough
to be in that club.</p>
</aside>
<p>If you try using a state machine for something more complex like game AI, you
will slam face-first into the limitations of that model. Thankfully, our
forebears have found ways to dodge some of those barriers. I’ll close this
chapter out by walking you through a couple of them.</p>
<h2><a href="#concurrent-state-machines" name="concurrent-state-machines">Concurrent State Machines</a></h2>
<p>We’ve decided to give our heroine the ability to carry a gun. When she’s packing
heat, she can still do everything she could before: run, jump, duck, etc. But
she also needs to be able to fire her weapon while doing it.</p>
<p>If we want to stick to the confines of an FSM, we have to <em>double</em> the number of
states we have. For each existing state, we’ll need another one for doing the
same thing while she’s armed: standing, standing with gun, jumping, jumping with
gun, you get the idea.</p>
<p>Add a couple of more weapons and the number of states explodes combinatorially.
Not only is it a huge number of states, it’s a huge amount of redundancy: the
unarmed and armed states are almost identical except for the little bit of code
to handle firing.</p>
<p>The problem is that we’ve <span name="combination">jammed</span> two pieces of
state — what she’s <em>doing</em> and what she’s <em>carrying</em> — into a single machine.
To model all possible combinations, we would need a state for each <em>pair</em>. The
fix is obvious: have two separate state machines.</p>
<aside name="combination">
<p>If we want to cram <em>n</em> states for what she’s doing and <em>m</em> states for what she’s
carrying into a single machine, we need <em>n × m</em> states. With two machines,
it’s just <em>n + m</em>.</p>
</aside>
<p>We keep our original state machine for what she’s doing and leave it alone. Then
we define a separate state machine for what she’s carrying. <code>Heroine</code> will have
<em>two</em> “state” references, one for each, like:</p>
<p><span name="equip-state"></span></p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Heroine</span>
<span class="p">{</span>
<span class="c1">// Other code...</span>
<span class="nl">private:</span>
<span class="n">HeroineState</span><span class="o">*</span> <span class="n">state_</span><span class="p">;</span>
<span class="n">HeroineState</span><span class="o">*</span> <span class="n">equipment_</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
<aside name="equip-state">
<p>For illustrative purposes, we’re using the full State pattern for her equipment.
In practice, since it only has two states, a Boolean flag would work too.</p>
</aside>
<p>When the heroine delegates inputs to the states, she hands it to both of them:</p>
<p><span name="consume"></span></p>
<div class="codehilite"><pre><span class="kt">void</span> <span class="n">Heroine</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">state_</span><span class="o">-></span><span class="n">handleInput</span><span class="p">(</span><span class="o">*</span><span class="k">this</span><span class="p">,</span> <span class="n">input</span><span class="p">);</span>
<span class="n">equipment_</span><span class="o">-></span><span class="n">handleInput</span><span class="p">(</span><span class="o">*</span><span class="k">this</span><span class="p">,</span> <span class="n">input</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
<aside name="consume">
<p>A more full-featured system would probably have a way for one state machine to
<em>consume</em> an input so that the other doesn’t receive it. That would prevent both
machines from erroneously trying to respond to the same input.</p>
</aside>
<p>Each state machine can then respond to inputs, spawn behavior, and change its
state independently of the other machine. When the two sets of states are mostly
unrelated, this works well.</p>
<p>In practice, you’ll find a few cases where the states do interact. For example,
maybe she can’t fire while jumping, or maybe she can’t do a dive attack if she’s
armed. To handle that, in the code for one state, you’ll probably just do some
crude <code>if</code> tests on the <em>other</em> machine’s state to coordinate them. It’s not the most
elegant solution, but it gets the job done.</p>
<h2><a href="#hierarchical-state-machines" name="hierarchical-state-machines">Hierarchical State Machines</a></h2>
<p>After fleshing out our heroine’s behavior some more, she’ll likely have a bunch
of similar states. For example, she may have standing, walking, running, and
sliding states. In any of those, pressing B jumps and pressing down ducks.</p>
<p>With a simple state machine implementation, we have to duplicate that code in
each of those states. It would be better if we could implement that once and
reuse it across all of the states.</p>
<p>If this was just object-oriented code instead of a state machine, one way to
share code across those states would be using <span
name="inheritance">inheritance</span>. We could define a class for an “on
ground” state that handles jumping and ducking. Standing, walking, running, and
sliding would then inherit from that and add their own additional behavior.</p>
<aside name="inheritance">
<p>This has both good and bad implications. Inheritance is a powerful means of code
reuse, but it’s also a very strong coupling between two chunks of code. It’s a big
hammer, so swing it carefully.</p>
</aside>
<p>It turns out, this is a common structure called a <em>hierarchical state machine</em>.
A state can have a <em>superstate</em> (making itself a <em>substate</em>). When an event
comes in, if the substate doesn’t handle it, it rolls up the chain of
superstates. In other words, it works just like overriding inherited methods.</p>
<p>In fact, if we’re using the State pattern to implement our FSM, we can
use class inheritance to implement the hierarchy. Define a base class for the
superstate:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">OnGroundState</span> <span class="o">:</span> <span class="k">public</span> <span class="n">HeroineState</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">handleInput</span><span class="p">(</span><span class="n">Heroine</span><span class="o">&</span> <span class="n">heroine</span><span class="p">,</span> <span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_B</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Jump...</span>
<span class="p">}</span>
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">PRESS_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Duck...</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">};</span>
</pre></div>
<p>And then each substate inherits it:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">DuckingState</span> <span class="o">:</span> <span class="k">public</span> <span class="n">OnGroundState</span>
<span class="p">{</span>
<span class="nl">public:</span>
<span class="k">virtual</span> <span class="kt">void</span> <span class="n">handleInput</span><span class="p">(</span><span class="n">Heroine</span><span class="o">&</span> <span class="n">heroine</span><span class="p">,</span> <span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">input</span> <span class="o">==</span> <span class="n">RELEASE_DOWN</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Stand up...</span>
<span class="p">}</span>
<span class="k">else</span>
<span class="p">{</span>
<span class="c1">// Didn't handle input, so walk up hierarchy.</span>
<span class="n">OnGroundState</span><span class="o">::</span><span class="n">handleInput</span><span class="p">(</span><span class="n">heroine</span><span class="p">,</span> <span class="n">input</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">};</span>
</pre></div>
<p>This isn’t the only way to implement the hierarchy, of course. If you aren’t
using the Gang of Four’s State pattern, this won’t work. Instead, you can model
the current state’s chain of superstates explicitly using a <em>stack</em> of states
instead of a single state in the main class.</p>
<p>The current state is the one on the top of the stack, under that is its
immediate superstate, and then <em>that</em> state’s superstate and so on. When you
dish out some state-specific behavior, you start at the top of the stack and
walk down until one of the states handles it. (If none do, you ignore it.)</p>
<h2><a href="#pushdown-automata" name="pushdown-automata">Pushdown Automata</a></h2>
<p>There’s another common extension to finite state machines that also uses a stack
of states. Confusingly, the stack represents something entirely different, and
is used to solve a different problem.</p>
<p>The problem is that finite state machines have no concept of <em>history</em>. You know
what state you <em>are</em> in, but have no memory of what state you <em>were</em> in. There’s
no easy way to go back to a previous state.</p>
<p>Here’s an example: Earlier, we let our fearless heroine arm herself to the
teeth. When she fires her gun, we need a new state that plays the firing
animation and spawns the bullet and any visual effects. So we slap together a
<code>FiringState</code> and make <span name="shared">all of the states</span> that she can
fire from transition into that when the fire button is pressed.</p>
<aside name="shared">
<p>Since this behavior is duplicated across several states, it may also be a good
place to use a hierarchical state machine to reuse that code.</p>
</aside>
<p>The tricky part is what state she transitions to <em>after</em> firing. She can pop off
a round while standing, running, jumping, and ducking. When the firing sequence
is complete, she should transition back to what she was doing before.</p>
<p>If we’re sticking with a vanilla FSM, we’ve already forgotten what state she was
in. To keep track of it, we’d have to define a slew of nearly identical states
— firing while standing, firing while running, firing while jumping, and so on
— just so that each one can have a hardcoded transition that goes back to the
right state when it’s done.</p>
<p>What we’d really like is a way to <em>store</em> the state she was in before firing and
then <em>recall</em> it later. Again, automata theory is here to help. The relevant
data structure is called a <a href="http://en.wikipedia.org/wiki/Pushdown_automaton"><em>pushdown
automaton</em></a>.</p>
<p>Where a finite state machine has a <em>single</em> pointer to a state, a pushdown
automaton has a <em>stack</em> of them. In an FSM, transitioning to a new state
<em>replaces</em> the previous one. A pushdown automaton lets you do that, but it also
gives you two additional operations:</p>
<ol>
<li>
<p>You can <em>push</em> a new state onto the stack. The “current” state is always the
one on top of the stack, so this transitions to the new state. But it leaves
the previous state directly under it on the stack instead of discarding it.</p>
</li>
<li>
<p>You can <em>pop</em> the topmost state off the stack. That state is discarded, and
the state under it becomes the new current state.</p>
</li>
</ol>
<p><img src="images/state-pushdown.png" alt="The stack for a pushdown automaton. First it just contains a Standing state. A Firing state is pushed on top, then popped back off when done." /></p>
<p>This is just what we need for firing. We create a <em>single</em> firing state. When
the fire button is pressed while in any other state, we <em>push</em> the firing state
onto the stack. When the firing animation is done, we <em>pop</em> that state off, and
the pushdown automaton automatically transitions us right back to the state we
were in before.</p>
<h2><a href="#so-how-useful-are-they" name="so-how-useful-are-they">So How Useful Are They?</a></h2>
<p>Even with those common extensions to state machines, they are still pretty
limited. The trend these days in game AI is more toward exciting things like
<em><a href="http://web.archive.org/web/20140402204854/http://www.altdevblogaday.com/2011/02/24/introduction-to-behavior-trees/">behavior trees</a></em> and <em><a href="http://web.media.mit.edu/~jorkin/goap.html">planning systems</a></em>. If complex AI is what you’re interested in,
all this chapter has done is whet your appetite. You’ll want to read other books
to satisfy it.</p>
<p>This doesn’t mean finite state machines, pushdown automata, and other simple
systems aren’t useful. They’re a good modeling tool for certain kinds of
problems. Finite state machines are useful when:</p>
<ul>
<li>
<p>You have an entity whose behavior changes based on some internal state.</p>
</li>
<li>
<p>That state can be rigidly divided into one of a relatively small number of
distinct options.</p>
</li>
<li>
<p>The entity responds to a series of inputs or events over time.</p>
</li>
</ul>
<p>In games, they are most known for being used in AI, but they are also common in
implementations of user input handling, navigating menu screens, parsing text,
network protocols, and other asynchronous behavior.</p>
<nav>
<span class="prev">← <a href="singleton.html">Previous Chapter</a></span>
<span class="next"><a href="sequencing-patterns.html">Next Chapter</a> →</span>
<span class="toc">≡ <a href="/">The Book</a></span>
</nav>
</div>
</div>
<footer>© 2009-2014 Robert Nystrom</footer>
</body>
</html>