<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>designpatterns &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/designpatterns/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Mon, 01 Sep 2014 01:10:36 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>designpatterns &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Finite State Machines in Game Development</title>
		<link>https://jessewarden.com/2012/07/finite-state-machines-in-game-development.html</link>
					<comments>https://jessewarden.com/2012/07/finite-state-machines-in-game-development.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Mon, 09 Jul 2012 15:59:09 +0000</pubDate>
				<category><![CDATA[CoronaSDK]]></category>
		<category><![CDATA[Gaming]]></category>
		<category><![CDATA[corona]]></category>
		<category><![CDATA[coronasdk]]></category>
		<category><![CDATA[designpatterns]]></category>
		<category><![CDATA[gaming]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[statemachines]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=3219</guid>

					<description><![CDATA[Finite State Machines are series of design patterns often used in Game Development. In this article I&#8217;ll define what they are &#038; how they work, go over 3 example implementations I have implemented in Corona SDK, and describe some of the pain points I&#8217;ve encountered using them. I&#8217;ve ported Cassio Souza&#8217;s ActionScript 3 State Machine [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a href="http://jessewarden.com/2012/07/finite-state-machines-in-game-development.html"><img fetchpriority="high" decoding="async" src="http://jessewarden.com/archives/blogentryimages/finitestatemachines/finitestatemachines-logo.jpg" style="padding-right: 8px;" width="320" height="204" align="left" /></a>Finite State Machines are series of design patterns often used in Game Development. In this article I&#8217;ll define what they are &#038; how they work, go over 3 example implementations I have implemented in <a href="http://coronalabs.com">Corona SDK</a>, and describe some of the pain points I&#8217;ve encountered using them.</p>
<p>I&#8217;ve ported Cassio Souza&#8217;s <a href="https://github.com/cassiozen/AS3-State-Machine">ActionScript 3 State Machine</a> to a <a href="https://github.com/JesterXL/Lua-Corona-SDK-State-Machine">Lua State Machine</a>, and recently a <a href="https://pub.dartlang.org/packages/jxlstatemachine">Dart version</a>, and included examples. This article has a companion video embedded below.</p>
<p>&nbsp;</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/ShfT7HiXk3s" frameborder="0" allowfullscreen></iframe></p>
<p><span id="more-3219"></span><strong>What Are State Machines</strong></p>
<p>At their simplest form, State Machines are an <a href="http://en.wikipedia.org/wiki/Observer_pattern">Observer pattern</a> with 2 values they watch internally: an Entity and the Current State. Whenever someone, somewhere changes the internal state, it&#8217;ll let the world know.</p>
<p>The high level parts are:</p>
<ol>
<li>States which contain/define the behavior for the Entity</li>
<li>Transitions which occur when one State changes to another</li>
<li>Rules which define which States can change to certain other States</li>
<li>Events which are internally or externally dispatched which trigger State Transitions</li>
</ol>
<p>When creating State Machines, you usually know all the states up front, hence the word finite. Whether a list on paper or a bunch of boxes on a flow chart with arrows denoting where you can go from where. Some states can have parent child relationships. There can be a variety of rules that allow/prevent some states from changing to others can causing state transitions.</p>
<p><strong>Why Use State Machines</strong></p>
<p>There are 3 use cases State Machines. These are Artificial Intelligence, modeling simulations, and a refactoring path for game entities.</p>
<p>For AI programming, you have the choice of deterministic or non-deterministic. Most video games have deterministic; meaning you know how the enemies will react based on different inputs. If they don&#8217;t see you, they&#8217;ll patrol. If they see you, they&#8217;ll attack you. If you hide and wait, they&#8217;ll eventually go back to patrolling. You can simulate fuzzy logic by using random numbers to change state to something random. For example, sometimes the enemy could use a grenade vs. a gun, or attack you immediately vs. sounding the alarm&#8230; or even run away to get reinforcements. Sometimes they could even talk to you instead. This randomness makes a State Machine non-deterministic, meaning you know all the States, but you don&#8217;t know exactly all the paths between States.</p>
<p>For modeling simulations, whether complex machinery, or situations, you often have a ton of moving parts. You&#8217;re interested in the potential interactions when certain things are in certain states. Sometimes you want these situations to be repeatable.</p>
<p>For example, for simulating hardware of large steel manufacturing machinery for training purposes, you want to setup the machine either in a specific state, or towards one to teach a new operator how to handle a certain negative situation in a safe environment to learn. You start a predefined set of actions to get the machine in a state where something bad is about to happen, and the operator has to learn how to push the right buttons or turn the right knobs to stop things from going bad.</p>
<p>You can do the same at a macro level for emulating events. Think SimCity.</p>
<p>This is also why unit testing deterministic state machines is pretty easy, albeit not as fun as non-deterministic, because you know all the paths ahead of time and the potential interactions.</p>
<p>For the purpose of this article, we&#8217;re concerned with refactoring paths for game entities. Specifically, &#8220;dude, this code is too complex to manage and there are 50 billion boolean flags/if then statements to deal with&#8230;&#8221;. Using State Machines makes your code more manageable as it grows, more organized, and easier to debug.</p>
<p><strong>Behavior in a Class vs. Behavior in States</strong></p>
<p>Alan Skorkin has <a href="http://www.skorks.com/2011/09/why-developers-never-use-state-machines/">a great article</a> on why developers often don&#8217;t use state machines. While he&#8217;s referring to software development as a whole, not just game development, he brings up a lot of valid points. Specifically, <a href="http://www.skorks.com/2009/08/does-yagni-mean-you-ignore-the-obvious/">YAGNI</a>, or if you don&#8217;t know ahead of time you&#8217;ll have a lot of behavior, you start out building only what you need. The issue becomes down the line, the effort towards refactoring it to a proper state machine is a lot of work.</p>
<p>I experienced this from 2 angles. The first is what got me interested in state machines in the first place. My game entities were getting uber complex, and I asked around for advice. Colleagues recommended Finite State Machines to solve all my problems. During the refactoring, I started to learn why they&#8217;re great for lots of behavior in known states.</p>
<p>I then tried implementing one in a brand new code base with only a little behavior&#8230; and it was overly complex. Then I reached this mid-point where the complexity was hard to manage, but I didn&#8217;t want to go back to a State Machine again.</p>
<p>So I&#8217;ve had a frustrating experience and an extremely positive one.</p>
<p>You can see a <a href="https://github.com/JesterXL/ZombieStick/blob/1fdc7a46268f4677eeba41d8512a44d5f9dde33d/code/com/jxl/zombiestick/players/PlayerJXL.lua">before</a> and <a href="https://github.com/JesterXL/ZombieStick/blob/248de162452018834d4765638a0dad393f8b042a/code/com/jxl/zombiestick/players/PlayerJXL.lua">after</a> example of how State Machines can really make your game entity classes smaller and more manageable as their behavior grows.</p>
<p><strong>Example 1: Simple State &#8211; Event Handler</strong></p>
<p>Let&#8217;s show a simple <a href="http://en.wikipedia.org/wiki/1942_(video_game)">1942</a> &#8216;esque example in Lua. You have an overhead view of an airplane that has 3 firing modes: a single bullet, faster dual-bullets, and a 3 pronged super-fast bullet mode.</p>
<p>From our state flow chart below, you can see we have 3 states, with Fire 1 being the initial state. The events between states are when the plane touches a power up. If the plane hits an enemy, they&#8217;ll go back a state, from Fire 3 to Fire 2 and from Fire 2 to Fire 1.</p>
<p><img decoding="async" src="http://jessewarden.com/archives/blogentryimages/finitestatemachines/flowchart-01.jpg" /></p>
<p>Now let&#8217;s setup our State Machine:</p>
<pre lang="lua">fireFSM = StateMachine:new()
fireFSM:addState("fire1", {from="*"})
fireFSM:addState("fire2", {from="*"})
fireFSM:addState("fire3", {from="*"})
fireFSM:setInitialState("fire3")
fireFSM:addEventListener("onStateMachineStateChanged", onChangePlayerFireFunction)</pre>
<p>Whenever anyone changes the fireFSM, it&#8217;ll dispatch the &#8220;onStateMachineStateChanged&#8221; event. We can then set the Entity&#8217;s proper fire function as well as the speed at which it should fire at in milliseconds.</p>
<pre lang="lua" line="67">function onChangePlayerFireFunction(event)
   local fireFunkyFunk
   local state = fireFSM.state
   local fireSpeed
   if state == "fire1" then
      fireFunkyFunk = player.fire1
      fireSpeed = 300
   elseif state == "fire2" then
      fireFunkyFunk = player.fire2
      fireSpeed = 200
   elseif state == "fire3" then
      fireFunkyFunk = player.fire3
      fireSpeed = 150
   end
   player.fire = fireFunkyFunk
   player.FIRE_TIME = fireSpeed
end</pre>
<p>Notice we inspect what the new state is at line 69. From there it&#8217;s just a simple switch statement to determine which firing mode to switch to. Notice we actually set the data on the Entity itself, in this case &#8220;player&#8221;. The player then uses this data in his game tick (slang for a function that fires when the Game Loop decides it&#8217;s time for your game object to do something). Like so:</p>
<pre lang="lua" line="139">function player:tick(millisecondsPassed)
   if self.firing == true then
      self.startFireTime = self.startFireTime + millisecondsPassed
      if self.startFireTime >= self.FIRE_TIME then
         self.startFireTime = 0
         self:fire()
      end
   end</pre>
<p>Notice line 144. The player/plane doesn&#8217;t know what fire actually is, it just executes it every time it&#8217;s allowed to fire. If you change it to a different fire function, it&#8217;ll use that one. Let&#8217;s take a look at those. Here&#8217;s fire1, which fires a single bullet every 300 milliseconds:</p>
<pre lang="lua" line="170">function player:fire1()
   local bullet = getBasicBullet("player_bullet_1.png", self.x + self.width / 2, self.y)
end</pre>
<p>In game, it&#8217;ll look like this:</p>
<p><img decoding="async" src="http://jessewarden.com/archives/blogentryimages/finitestatemachines/fire1.jpg" /></p>
<p>If we press the Fire 2 button (which simulates getting a power up), it&#8217;ll change the Entity&#8217;s fire reference to the fire2 function:</p>
<pre lang="lua">function player:fire2()
   local bullet = getBasicBullet("player_bullet_2.png", self.x, self.y)
   bullet.x = bullet.x + bullet.width / 2
end</pre>
<p>The only difference here is a different image which is larger, and we center it on the player.</p>
<p><img decoding="async" src="http://jessewarden.com/archives/blogentryimages/finitestatemachines/fire2.jpg" /></p>
<p>Finally, if we hit the Fire 3 button, it&#8217;ll change it to the fire3 function.</p>
<pre lang="lua">function player:fire3()
   local bullet1 = getBasicBullet("player_bullet_1.png", self.x, self.y)
   bullet1.rotation = -45
   bullet1.rot = math.atan2(bullet1.y -  -800,  bullet1.x - -800) / math.pi * 180 -90;
   bullet1.angle = (bullet1.rot -90) * math.pi / 180;

   local bullet2 = getBasicBullet("player_bullet_1.png", self.x, self.y)
   bullet2.rotation = 45
   bullet2.rot = math.atan2(bullet2.y -  -800,  bullet2.x - -800) / math.pi * 180 -90;
   bullet2.angle = (bullet2.rot) * math.pi / 180;
   
   -- override the functions with these instead
   function bullet1:tick(millisecondsPassed)
      self.x = self.x + math.cos(self.angle) * self.speed * millisecondsPassed
         self.y = self.y + math.sin(self.angle) * self.speed * millisecondsPassed
   end
   
   function bullet2:tick(millisecondsPassed)
      self.x = self.x + math.cos(self.angle) * self.speed * millisecondsPassed
         self.y = self.y + math.sin(self.angle) * self.speed * millisecondsPassed
   end

   local bullet3 = getBasicBullet("player_bullet_1.png", self.x + self.width / 2, self.y)
end</pre>
<p>Which looks like:</p>
<p><img decoding="async" src="http://jessewarden.com/archives/blogentryimages/finitestatemachines/fire3.jpg" /></p>
<p>Again, the sequence of events for hitting the Fire 2 button are:</p>
<ol>
<li>fireFSM:setInitialState(&#8220;fire1&#8221;) puts the State Machine in the initial fire 1 state.</li>
<li>When you press the Fire 2 button, it&#8217;ll call fireFSM:changeState(&#8220;fire2&#8221;)</li>
<li>The State Machine internally will dispatch the change event &#8220;onStateMachineStateChanged&#8221;</li>
<li>In our event handler for it, we&#8217;ll inspect what the new state is, and assign the appropriate fire function.</li>
</ol>
<p>&nbsp;</p>
<p><strong>Example 1: Simple State &#8211; Event Handlers</strong></p>
<p>While using a change event is simple and results in 1 function, what if you have a lot of states? This is where using enter/exit handlers helps you organize your code more and it scales better. Taking our exact same example above, instead of using our onChangePlayerFireFunction to listen for the State Machine&#8217;s &#8220;onStateMachineStateChanged&#8221; event:</p>
<pre lang="lua">fireFSM:addEventListener("onStateMachineStateChanged", onChangePlayerFireFunction)</pre>
<p>We&#8217;ll instead use an enter handler instead, like so:</p>
<pre lang="lua">fireFSM:addState("fire1", {from="*", enter=onEnterStateFire1})
fireFSM:addState("fire2", {from="*", enter=onEnterStateFire2})
fireFSM:addState("fire3", {from="*", enter=onEnterStateFire3})</pre>
<p>Now, this results in 3 organized functions that are a lot smaller and easier to read. It&#8217;s also obvious what they do based on the naming convention:</p>
<pre lang="lua">function onEnterStateFire1(event)
   player.fire = player.fire1
   player.FIRE_TIME = 300
end

function onEnterStateFire2(event)
   player.fire = player.fire2
   player.FIRE_TIME = 200
end

function onEnterStateFire3(event)
   player.fire = player.fire3
   player.FIRE_TIME = 150
end</pre>
<p><strong>Example 2: Hierarchical State Machine</strong></p>
<p>There are a variety of benefits using a hierarchical State Machine; a State Machine where States have parent child relationships.</p>
<p>First, it helps <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> your code. There are a lot of things some states have in common so you can run that initialization code once. Same goes for destroy/clean up code.</p>
<p>Secondly, it helps you organize your code; ie &#8220;Attacking code goes in this section whereas Defending code goes over here&#8221;.</p>
<p>Third, a State Machine can help you enforce paths to go from child to parent to sibling to child. Just like in <a href="http://en.wikipedia.org/wiki/StarCraft">Starcraft</a>, a Siege Tank must first transform to assault mode from the siege mode before it can actually move and fire again.</p>
<p><img decoding="async" src="http://jessewarden.com/archives/blogentryimages/finitestatemachines/siege-tank.jpg" /></p>
<p>The State Machine will throw errors if you attempt to move to an illegal path which helps you correct your code. It will also showcase missing transitions if you forgot one. Why are paths important? Just like we can&#8217;t go from Siege Mode to Move Mode using a Starcraft Siege tank, we don&#8217;t want our War Robot in Example 2 going from Artillery Mode to Move Mode. There is some time it takes to get setup for long range artillery strikes, as well as getting out of artillery mode. Our example does NOT enforce this but gives you the mechanisms to do so to ensure the player cannot do anything whilst transitioning from one State to the next.</p>
<p>Here&#8217;s the flow chart for Example 2, where our War Robot can be an upright walking robot for recon, a defense mode for holding up shields to protect itself, and an assault mode with 3 firing modes: laser sight, sniper, and artillery (click for larger version).</p>
<p><a href="http://jessewarden.com/archives/blogentryimages/finitestatemachines/flowchart-02.jpg"><img decoding="async" src="http://jessewarden.com/archives/blogentryimages/finitestatemachines/flowchart-02-preview.jpg" /></a></p>
<p>We&#8217;ll set up our State Machine much like before in Example 1, except here we&#8217;ll use a new parameter called &#8220;parent&#8221; like so:</p>
<pre lang="lua">botFSM:addState("scout", {from={"defend", "assault"}, enter=onEnterScout})
botFSM:addState("scoutLeft", {parent="scout", from="scoutRight", enter=onEnterScoutLeft, exit=onExitScoutLeft})
botFSM:addState("scoutRight", {parent="scout", from="scoutLeft", enter=onEnterScoutRight, exit=onExitScoutRight})

botFSM:addState("defend", {from={"scout", "assault"}, enter=onEnterDefendState, exit=onExitDefendState})

botFSM:addState("assault", {from={"scout", "defend"}, enter=onEnterAssaultState, exit=onExitAsstaultState})
botFSM:addState("assaultLeft", {parent="assault", from="assaultRight", enter=onEnterAssaultLeft, exit=onExitAssaultLeft})
botFSM:addState("assaultRight", {parent="assault", from="assaultLeft", enter=onEnterAssaultRight, exit=onExitAssaultRight})
botFSM:addState("sight", {parent="assault", from={"sniper", "artillery"}, enter=onEnterSightState, exit=onExitSightState})
botFSM:addState("sniper", {parent="assault", from={"sight", "artillery"}, enter=onEnterSniperState, exit=onExitSniperState})
botFSM:addState("artillery", {parent="assault", from={"sniper", "sight"}, enter=onEnterArtilleryState, exit=onExitArtilleryState})

botFSM:setInitialState("scout")</pre>
<p>Notice our 3 main States (Scout, Defend, and Assault) clearly define which states they are allowed to be transitioned to via the from parameter. Also notice some special things about the parent parameter. The &#8220;scoutLeft&#8221; State, a child of &#8220;scout&#8221;, does not have to define its parent in the from parameter. It&#8217;s implied in the State Machine that a child state is allowed to be transitioned to by its parent. Finally, notice the use of exit to define exit handlers.</p>
<p>All this setup defines our states, their children, and who&#8217;s allowed to transition to whom. All of this matches our flow chart.</p>
<p>Our Entity, the WarBot class, is handling all the actual animations and storing the data and handling how the behavior works. What behavior it does, and when, is controlled by the State enter and exit functions. The how is affected by its internal variables, also changed by the State changes.</p>
<p>Let&#8217;s take a look at what happens when you enter the parent &#8220;scout&#8221; State by pressing the &#8220;Scout&#8221; button:</p>
<pre lang="lua">function onEnterScout()
   warBot:showSprite("scout")
   warBot:setSpeed(4)
end</pre>
<p>It shows the scout sprite sheet and sets the speed to 4. If you press the &#8220;Scout Right&#8221; button, it&#8217;ll botFSM:changeState(&#8220;scountRight&#8221;) and call:</p>
<pre lang="lua">function onEnterScoutRight()
   warBot:showSprite("scoutRight")
   warBot:setDirection("right")
   warBot:startMoving()
end</pre>
<p>This shows the scoutRight sprite sheet which is an animation of the robot running right. It also ensures it is facing the right direction and informs it needs to start animating. If you let go/stop touching the &#8220;Scout Right&#8221; button, it&#8217;ll go back to the parent &#8220;scout&#8221; state.</p>
<pre lang="lua">function onExitScoutRight()
   warBot:showSprite("scout")
   warBot:stopMoving()
end</pre>
<p>Notice that this does NOT fire an onExitScout function; you&#8217;re still technically in the scout state since scoutLeft and scoutRight are its children. It looks like so:</p>
<p><img decoding="async" src="http://jessewarden.com/archives/blogentryimages/finitestatemachines/scoutmove.jpg" /></p>
<p>Let&#8217;s take a look at the Defense State. He&#8217;s unique in that he doesn&#8217;t care where you came from; as soon as you let go of the Defend button, it&#8217;ll go to whatever the previousState was. Also of note, he&#8217;ll set some initial defense and speed variables (speed to 0 because you can&#8217;t move while in Defend State):</p>
<pre lang="lua">function onEnterDefendState()
   warBot:showSprite("defend")
   warBot:setDefense(10)
   warBot:setSpeed(0)
end</pre>
<p>Notice we didn&#8217;t define an onExitDefendState. It&#8217;s assumed whatever State you&#8217;re going to will handle setting the speed &#038; defense to the appropriate values.</p>
<p>Finally, we&#8217;re offloading a lot of the actual details of firing bullets, laser sights, etc. onto the Entity. Notice how all 3 of the Assault&#8217;s child modes tell the Entity to start or stop showing these effects. The benefit is you don&#8217;t have to worry about checking boolean flags before you run them; you can be sure the State Machine will only start and stop each one at the appropriate time. &#8230; Usually, heh.</p>
<p>Here&#8217;s Sniper mode&#8217;s enter and exit:</p>
<pre lang="lua">function onEnterSniperState()
   warBot:showSprite("sniper")
   warBot:setSpeed(0)
   warBot:startSniperShooting()
end

function onExitSniperState()
   warBot:showSprite("sniperReverse")
   warBot:stopSniperShooting()
end</pre>
<p>Standard stuff here; show the correct sprite sheet, set the speed to 0 when you enter, and telling the entity to start handling touch events as sniper shots. When it exits, it shows the revert animation, and stops handling touch events as sniper shots.</p>
<p><strong>State Changes Observer &#038; Path Enforcement</strong></p>
<p>Remember, the State Machine will both enforce the state paths you put in from as well as dispatch an event. Since it&#8217;s an observer, others can listen to these State changes as well. The ButtonsController we have listens to the state changes and only shows the appropriate buttons that mach our flow chart rules.</p>
<p>We give the ButtonsController a reference to the State Machine:</p>
<pre lang="lua">buttons:setStateMachine(botFSM)</pre>
<p>He&#8217;ll then add an event listener to it and initialize himself to the current state:</p>
<pre lang="lua">function buttons:setStateMachine(fsm)
   if self.stateMachine then
      self.stateMachine:removeEventListener("onStateMachineStateChanged", self)
   end
   self.stateMachine = fsm
   if fsm then
      fsm:addEventListener("onStateMachineStateChanged", self)
   end
   self:onStateMachineStateChanged()
end</pre>
<p>Now, instead of checking a bunch of rules to ensure they match our flow chart, we instead just only show the buttons you&#8217;re allowed to press in certain states:</p>
<pre lang="lua">function buttons:onStateMachineStateChanged(event)
   local state = self.stateMachine.state
   self:hideAllButtons()
   if state == "scout" or state == "scoutLeft" or state == "scoutRight" then
      self.walkLeftButton.isVisible = true
      self.walkRightButton.isVisible = true
      self.defendButton.isVisible = true
      self.attackButton.isVisible = true
   elseif state == "defend" then
      self.defendButton.isVisible = true
   elseif state == "assault" then
      self.rollLeftButton.isVisible = true
      self.rollRightButton.isVisible = true
      self.defendButton.isVisible = true
      self.scoutButton.isVisible = true
      self.sightButton.isVisible = true
      self.sniperButton.isVisible = true
      self.artilleryButton.isVisible = true
   elseif state == "assaultLeft" or state == "assaultRight" then
      self.rollLeftButton.isVisible = true
      self.rollRightButton.isVisible = true
      self.scoutButton.isVisible = true
   elseif state == "sight" or state == "sniper" or state == "artillery" then
      self.attackButton.isVisible = true
   end
end</pre>
<p>This makes your changing the State Machine really easy because you don&#8217;t have to put tests in there; you just react and change it to match the flow chart. Here&#8217;s how moveRight works; if you press the button, it sets it to moveRight, and when you let go, it goes back to scout:</p>
<pre lang="lua">function buttons:onMoveRight(event)
   if event.phase == "began" then
      self.stateMachine:changeState("scoutRight") 
   elseif event.phase == "ended" or event.phase == "cancelled" then
      self.stateMachine:changeState("scout") 
   end
end</pre>
<p><strong>Example 3: Class Based States</strong></p>
<p>Last up is the class version of the State Machine examples. My version of Classes in Lua are just <a href="http://jessewarden.com/2011/10/lua-classes-and-packages-in-corona.html">tables using closures</a> for scope reasons.</p>
<p>The class approach has some advantages. First, as your code grows in size, it&#8217;s easier to scale. You can utilize inheritance and packages help keep it clean, organized, and DRY. This also makes code reuse slightly easier as well. In the first 2 examples, you can see how the actual behavior implementation is separate from the State Machine, in main.lua. It&#8217;s not really grouped together in any organized fashion.</p>
<p>The second advantage is, like the enter and exit functions, the class only handles that behavior in which it is responsible for. If you look in Example 2, you&#8217;ll notice the WarBot, although not determining his behavior, is still responsible for setting himself up internally for it. Using classes, you offload the majority of that code to the appropriate state responsible for it.</p>
<p>The third advantage is leveraging Corona&#8217;s event system. States can both react to events from the global event bus, <a href="http://developer.coronalabs.com/reference/index/events/runtime/runtimeaddeventlistener">Runtime</a>, as well as dispatch their own in case other State Machines need to know about something. This allows a loose coupling for inter-State Machine communication.</p>
<p>Downsides are moar code which requires moar unit tests which in turn is moar code. This is moar complexity which can result in a lower iteration speed. Not always ideal for games. I like it, though, coming from an <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">OOP</a> background.</p>
<p>Let&#8217;s start with a really simple State Machine: a character that can move left, right, jump, and attack.</p>
<p><img decoding="async" src="http://jessewarden.com/archives/blogentryimages/finitestatemachines/example3.jpg" /></p>
<p>And here&#8217;s the flow chart with the State paths. Notice if the character sits still, he can rest. That&#8217;s it (click for larger image).</p>
<p><a href="http://jessewarden.com/archives/blogentryimages/finitestatemachines/flowchart-03.jpg"><img decoding="async" src="http://jessewarden.com/archives/blogentryimages/finitestatemachines/flowchart-03-preview.jpg"></a></p>
<p>Setting up the State Machine is only slightly different; you use addState2, and put a class instance inside it, like so:</p>
<pre lang="lua">fsm:addState2(ReadyState:new())
fsm:addState2(RestingState:new())
fsm:addState2(MovingRightState:new())
fsm:addState2(MovingLeftState:new())
fsm:addState2(JumpLeftState:new())
fsm:addState2(JumpRightState:new())
fsm:addState2(AttackState:new())
fsm:setInitialState("ready")

gameLoop:addLoop(fsm)</pre>
<p>Also note I added it to the Game Loop. I default all States to have a tick method so they can tap into the global Game Loop as well.</p>
<p>Pay special note to the setInitialState; it takes a String name. I used a convention to keep the the API the same: ReadyState becomes &#8220;ready&#8221;, MovingRightState becomes &#8220;movingRight&#8221;, etc. All classes use their name in the constructor so the State Machine knows what their name is.</p>
<p>In a State class, you just import the base class, extend it, and pass in your name.</p>
<pre lang="lua">require "com.jessewarden.statemachine.BaseState"
ReadyState = {}

function ReadyState:new()
   local state = BaseState:new("ready")</pre>
<p>From there, you can do whatever you wish. The standard methods to implement are onEnterState, onExitState, and tick. All State class have references to the Entity they are dealing with as well as the State Machine they are within as illustrated in the tick function getting local references to it:</p>
<pre lang="lua">function state:onEnterState(event)
end

function state:onExitState(event)
end

function state:tick(time)
   local player = self.entity
   local stateMachine = self.stateMachine
end</pre>
<p>Let&#8217;s take a look at the ReadyState&#8217;s onEnterState function. He states the Entity is not recharging his stamina, resets the internal rest timer (since you have to sit still for 3 seconds to trigger a State transition to the RestingState), and listens for global events that can trigger other, valid State transitions.</p>
<pre lang="lua">function state:onEnterState(event)
   local player = self.entity
   self.recharge = false
   
   self:reset()
   
   player:showSprite("stand")
   
   Runtime:addEventListener("onMoveLeftStarted", self)
   Runtime:addEventListener("onMoveRightStarted", self)
   Runtime:addEventListener("onAttackStarted", self)
   Runtime:addEventListener("onJumpLeftStarted", self)
   Runtime:addEventListener("onJumpRightStarted", self)
end</pre>
<p>That last part is the key. I don&#8217;t care where these events come from, I just know, if someone, somewhere says that onMoveLeftStarted, then this State class will react and say, &#8220;Ok, go ahead and change the state to the moveLeft state then.&#8221;:</p>
<pre lang="lua">function state:onMoveLeftStarted(event)
   self.stateMachine:changeStateToAtNextTick("movingLeft")
end</pre>
<p>Notice here there are no rules enforcement. They&#8217;re entirely up to you in an opt-in way. If you do not handle, or allow a State transition here, none occurs. It&#8217;s up to your class to opt in and allow State transitions. Conversely, you can have someone else with a reference to the State Machine to actually change the states; up to you. The downside here is no help from the State Machine to see if your States actually match what&#8217;s in your flow chart. I&#8217;ve thought about adding a way to declaratively add them just like you did in Example 1 and 2.</p>
<p>The JumpLeftState shows the power of inheritance at work:</p>
<pre lang="lua">require "states.JumpState"

JumpLeftState = {}

function JumpLeftState:new()
   local state = JumpState:new("jumpLeft")
   
   state.superOnEnterState = state.onEnterState
   function state:onEnterState(event)
      self:superOnEnterState(event)
      
      local player = self.entity
      player:setDirection("left")
   end
   
   state.superOnExitState = state.onExitState
   function state:onExitState(event)
      local player = self.entity
      player:applyLinearImpulse(-player.jumpForwardForce / 3, 0, 40, 32)
      self:superOnExitState(event)
   end
   
   state.superTick = state.tick
   function state:tick(time)
      local player = self.entity
      player.x = player.x + -(player.jumpForwardForce)
      self:superTick(time)
   end
   
   return state
   
end

return JumpLeftState</pre>
<p>He extends the base JumpState, allowing it to do most of the heavy lifting dealing with Box2D + Game Loop movement timing, etc. This State just sets the direction to the correct way. Notice too a rudimentary super method call to allow the base class to do it&#8217;s work first. I also extend the jump behavior by also moving the Entity in the right direction. I could let the base class do this, or the sub-class&#8230; up to you.</p>
<p>Be aware in all examples, the State classes have their onEnterState and onExitState methods called in the correct order, always. You do NOT have to implement them if you do not wish to. Finally, the most important thing to notice is the State classes use the changeStateToAtNextTick method for the State Machine class vs. changeState. The short reason for this is that it allows all the code in the current stack to run, including State machine class clean up, as well as avoiding common race conditions (if you&#8217;re a Flash Developer, think invalidation).</p>
<p><strong>Real World Challenges</strong></p>
<p>I wanted to show you some of the challenges I&#8217;ve had in the real world. While the design patterns&#8217; rules are quite clear about &#8220;Entity&#8217;s holding the data, States implementing the behavior&#8221; sometimes it&#8217;s easier to let the Entity handle the details&#8230; especially with Box2D collisions.</p>
<p>An example of this is in my ZombieStick game where a Zombie grapples with the player. They get a reference to the player they grappled, add themselves as a grappler, and await the Player&#8217;s State Machine to resolve fighting off the zombie. Off-loading a lot of this code to the Entity makes them much cleaner classes, and results in less code since the Entity&#8217;s already extend a Corona DisplayObject. To pragmatists, sounds legit, to ivory tower purists, it&#8217;s pathetic&#8230; especially in a light weight and powerfully dynamic language like Lua.</p>
<p>This works out ok in that if a collision event fires from a Zombie, but if he&#8217;s in another state where he clearly can&#8217;t grapple the player (prone, stunned, dead), he just ignores the event. Sounds great at first, but Corona collision events are just that&#8230; events, once you miss them, they&#8217;re gone. Therefore, each State class has the burden of in its onEnterState to do some checking to see what it missed. This is basically the same problem <a href="http://puremvc.org" title="Notes on Completing Round 1 of P90X">PureMVC</a> and <a href="http://robotlegs.org">Robotlegs</a> Mediators solve in application development (data is ready, you&#8217;re not vs. you&#8217;re ready, data is not), so you can do the same here as well; you just have to ensure your Entity does a good job of exposing the variables you need to have your State boot up correctly.</p>
<p>For example, here&#8217;s the Zombie&#8217;s Box2D collision handler:</p>
<pre lang="lua">function zombie:collision(event)
   if self.dead == true then return true end
   if event.phase == "began" then
      if event.other.classType == "PlayerJXL" then
         if self.collisionTargets == nil then
            self.collisionTargets = {}
         end
         if table.indexOf(event.other) == nil then
            table.insert(self.collisionTargets, event.other)
         end
      end
   elseif event.phase == "ended" then
      if event.other.classType == "PlayerJXL" then
         table.remove(self.collisionTargets, table.indexOf(event.other))
         if self.targetPlayer ~= nil and event.other == self.targetPlayer then
            self:dispatchEvent({name="onTargetPlayerRemoved", target=self})
         end
      end
   end
end</pre>
<p>All it basically does is manage an internal list of things it hit that are players. If the player moves away, great, it removes them. This allows the State classes to manage whether or not the Zombie should actually act on grappling a player not; ie the actual behavior. As soon as the State boots up, it checks this collisionTargets array in the onEnterSate function. Any time thereafter, it&#8217;ll get the proper events, thus avoiding race conditions. Additionally, the State classes can do it whenever they wish; ie whenever the State Machine moves to the IdleState, that&#8217;s the first thing he checks:</p>
<pre lang="lua">function state:handleCollisionTargets()
   local zombie = self.entity
   local targets = zombie.collisionTargets
   if targets ~= nil and #targets > 0 then
      local first = targets[1]
      zombie.targetPlayer = first
      self.stateMachine:changeStateToAtNextTick("grabPlayer")
   end
end</pre>
<p>Again, following a common solution used in other languages and frameworks&#8230; but just 1 more thing for you to remember, and moar code. I agree with it, and you DO get in a groove, just something to be aware of.</p>
<p>The other thing I noticed is that 90% of the State Machine being changed to different States is handled in the State classes themselves. However, you get into these edge cases where you need someone ELSE to change it. The example I just gave, when the Zombie grapples onto the player, the Player needs to immediately react. Using the above example, it&#8217;d be better to just have the States that are capable of legally going to Grappled Defense State handling it, right? Well&#8230; no. If a Zombie grabs you, you drop what you&#8217;re doing and react&#8230; even if you&#8217;re in the middle of the air in a Jump State. Here&#8217;s a method in the Base Player class (the Entity itself) that does just that:</p>
<pre lang="lua">function player:addGrappler(dudeGrabbingMeUpInThisMug)
   -- TODO: need to ensure you can actually be grappled, need to check state. psuedo code below
   local currentState = self.fsm.state
   if currentState == "firehose" and currentState == "grapple" and currentState == "jump" and current == "jumpLeft" and currentState == "jumpRight" then
      error("Illlegal to grapple player when they're in state: ", currentState)
   end

   -- if you're grappled, you're slowed down
   local grapplers = self.grapplers
   if table.indexOf(grapplers, dudeGrabbingMeUpInThisMug) == nil then
      table.insert(grapplers, dudeGrabbingMeUpInThisMug)
      self:resolveSpeed()
      self.fsm:changeStateToAtNextTick("grappleDefense")
      return true
   else
      error("grappler already added to array")
   end
end</pre>
<p>Yes, a code smell&#8230; further evidence that rules enforcement would mitigate this problem. So would a flow chart indicating what states a Zombie can actually grapple me in. Anyway, if you see things like this in your implementation, hopefully you now know how to solve or refactor them.</p>
<p><strong>Conclusions</strong></p>
<p>Again, the high level characteristics of a State Machine are:</p>
<ul>
<li>States which contain/define the behavior for the Entity</li>
<li>Transitions which occur when one State changes to another</li>
<li>Rules which define which States can change to certain other States</li>
<li>Events which are internally or externally dispatched which trigger State Transitions</li>
</ul>
<p></p>
<p>Using State Machines allows you to more easily scale and organize behavior code for your Game Entities, especially for AI development. The rules engine helps ensure your code matches your flowchart, and tells you at runtime if it does not (except for Classes&#8230; working on it). You can set the StateMachine&#8217;s new state anywhere, and he&#8217;ll both dispatch a change event as well as call your enter/exit functions for you. If you wish for it to utilize the global Event bus, I&#8217;ve included instructions inside of the class on how to enable this. For larger projects, the class based option helps your code scale for larger projects. All of the examples are included in the <a href="https://github.com/JesterXL/Lua-Corona-SDK-State-Machine">Github repo</a> where you can download the code.</p>
<p>Further reading:</p>
<ul>
<li><a href="http://ai-depot.com/FiniteStateMachines/FSM.html">Finite State Machines</a></li>
<li><a href="http://www.troyworks.com/cogs/">Cogs framework with presentation</a> (scroll down)</strong></li>
<li><a href="http://code.google.com/p/flash-state-engine/">Johnathan Kaye&#8217;s ActionScript 3 State Engine</a></li>
<li><a href="http://www.richardlord.net/blog/finite-state-machines-for-ai-in-actionscript">Richard Lord&#8217;s &#8220;Finite State Machines for AI in ActionScript</a></li>
<li><a href="http://www.skorks.com/2011/09/why-developers-never-use-state-machines/">Why Developers Never Use State Machines</a></li>
</ul>
<p>Also posted on <a href="http://www.ios-gaming.com/2012/07/11/finite-state-machines-in-game-development/">iOS Gaming</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2012/07/finite-state-machines-in-game-development.html/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Why Robotlegs For Games?</title>
		<link>https://jessewarden.com/2011/08/why-robotlegs-for-games.html</link>
					<comments>https://jessewarden.com/2011/08/why-robotlegs-for-games.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sun, 07 Aug 2011 18:10:54 +0000</pubDate>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[corona]]></category>
		<category><![CDATA[designpatterns]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[mvc]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=2777</guid>

					<description><![CDATA[Why Robotlegs for Games? The following covers why you would utilize the Robotlegs MVC architecture in a lightweight, Lua game for Corona. I&#8217;ll discuss the refactoring reasoning, the common problems you run across in game architecture, and their solutions with their pro&#8217;s and con&#8217;s discussed. Finally, I conclude on how Robotlegs helps solve these common [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img decoding="async" style="padding-right: 8px;" src="http://jessewarden.com/archives/blogentryimages/corona-robotlegs-games.jpg" alt="" width="300" height="232" align="left" /><strong>Why Robotlegs for Games?</strong></p>
<p>The following covers why you would utilize the <a href="http://robotlegs.org">Robotlegs</a> MVC architecture in a lightweight, <a href="http://lua.org">Lua</a> game for <a href="http://www.anscamobile.com/corona/">Corona</a>. I&#8217;ll discuss the refactoring reasoning, the common problems you run across in game architecture, and their solutions with their pro&#8217;s and con&#8217;s discussed. Finally, I conclude on how Robotlegs helps solve these common issues, specifically in a Lua &amp; Corona context.</p>
<p>I&#8217;ve started the port of Robotlegs to Lua to work in Corona if you&#8217;re interested in <a href="http://jessewarden.com/2011/08/robotlegs-for-corona.html">learning more</a>.</p>
<p><strong><span id="more-2777"></span>Refactor First</strong></p>
<p>In learning Lua &amp; Corona, I quickly ran into 2 problems with the game I&#8217;m working on. The main code controller became way too large to manage. It wasn&#8217;t quite a God object (yes, the anti-pattern) because a lot of the View&#8217;s themselves handled some of the necessary messaging &amp; logic. Regardless, time to refactor.</p>
<p>The first thing was to start using classes. Lua doesn&#8217;t have classes. There are a bunch of resources out there that explain how to do them in various incarnations. I went with a version that Darren Osadchuk, creator of the <a href="http://www.ludicroussoftware.com/corona/simple-oop-with-inheritance-in-corona/">Corona bundle</a> for TextMate.</p>
<p>The second thing was to start using packages. Lua doesn&#8217;t have packages. There are various ways of implementing them which are all confusing as hell. The easiest way is to just put your code in a folder and use that path in the require function, but you can&#8217;t utilize folders for Android in the latest build of Corona at the time of this writing.</p>
<p>These are the low hanging fruit of re-factoring, and has made a huge difference in code readability &amp; maintainability.</p>
<p><strong>Burdens of Encapsulation</strong></p>
<p>The downside of OOP is that it&#8217;s encapsulated. While making something a black box with internally managed state &amp; implied reusability is good on the surface, it pushes the burden of managing communication between those encapsulated objects to someone ones.</p>
<p>You have 3 options: globals, messaging dependencies, or mediation.</p>
<p><strong>Global Variables: The Good</strong></p>
<p>Most people agree global variables are badâ€¦ in larger software development. In smaller scoped software gaming, not so much. Let&#8217;s explore their benefits.</p>
<p>In a lot of languages, globals are part of the language design, irrespective of how the runtime and tools/IDE&#8217;s handle them. Some languages make them first class citizens with mechanisms and rules around how they&#8217;re often used. This makes them formalized, accepted, AND useful. This is important to understand.</p>
<p>If it&#8217;s formalized, it means the language designers deem their usage acceptable, AND expected.</p>
<p>If it&#8217;s accepted, it means others will use them, incorporate them into their projects, libraries, and training &amp; writing materials. This also means it&#8217;s then promoted amongst the community, solutions and coding strategies/solutions are built around it. This doesn&#8217;t make it inherently &#8220;good&#8221;, just accepted in that particular community.</p>
<p>If it&#8217;s useful, the majority of people will use it if their job is using that language as opposed to hobbyists, or those who continue to explore the language and try different ways to solve similar problems with it off of their employer&#8217;s clock.</p>
<p>In Lua, globals are all 3. Formalized via _G, very similar to ActionScript 1&#8217;s _global, accepted in that people do in fact use them (unknowingly a lot I&#8217;d wager), and useful since the syntax to utilize globals is terse; a Lua hallmark. Notice both have the preceding underscore to ensure they don&#8217;t interfere with the developer&#8217;s potential to create a variable called G or global. While ActionScript 1 has some security implementations to prevent certain loaded SWF&#8217;s from writing/modifying existing definitions, they had the same mechinism with strorage, first via _level&#8217;s on a per SWF basis, and later a formalized _global. Lua takes it a step farther with a series of facilities to change &#8220;which&#8221; globals your using, etc. It&#8217;s also used in package naming strategies, OOP, etc.</p>
<p>As a globally accessible table, access to _G is fast. Fast is good in game development. You want to be part of the solution, not part of the problem.</p>
<p><strong>Global Variables: The Bad</strong></p>
<p>This differs from traditional software development. If you come from any formal software development, globals are considered extremely bad practice. There is a common strategy to use the Singleton design pattern to &#8220;get away with it&#8221;. Even those are considered bad practice when over used. In fact, Singletons are often created merely because the language doesn&#8217;t offer a formalized way of doing global variables (like ActionScript 3 vs. ActionScript 1).</p>
<p>Why? The 3 main reasons are application state coupling, access control, and preventing testability.</p>
<p><strong>Application State Coupling</strong></p>
<p>Application State Coupling refers to the state of your application being dependent on usually a series of global variables. I won&#8217;t get into the why&#8217;s, but <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> and it&#8217;s <a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html">MVP</a> derivatives (<a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a>, <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html">Supervising Controller</a>, <a href="http://martinfowler.com/eaaDev/PresentationModel.html">Presentation Model</a>) have solved most of the state problems. They keep visual state in the View&#8217;s (or anything that&#8217;s a GUI that you can see), and application logic &amp; state in the Model layer somewhere. Your application is no longer coupled to a single variable being a specific value for your application to run, to exhibit a certain bug, etc. Each piece can (usually, hehe) be run independently, and if there is a problem, you know where to look, or at least where NOT to look.</p>
<p>An example is if your player is dying too quickly, you know the problem isn&#8217;t in the player code, or the controller code, but rather somewhere in the model where his life state is being access/set/updated. If you used a global, it&#8217;d probably be set in player itself, or perhaps by an enemy bullet that hit him, etc. No clue where to look.</p>
<p>Another side effect is adding new global variables. This leads to certain parts of your application expecting the globals to be a certain value at certain times. If they aren&#8217;t, things don&#8217;t work. Because they are many different places, it becomes extremely time consuming for you to debug and track down because you don&#8217;t necessarily know who is expecting what to be set to what, and why. This is more caused by access control, howeverâ€¦</p>
<p><strong>Access Control</strong></p>
<p>Access Control refers to who can access your data, and how. In Flash &amp; Flex apps that are smaller, we&#8217;ll usually use the server as access control. Meaning, while we provide a GUI to allow people to create, edit, and delete users from a database for example, the actual PHP/Ruby/Python/Java on the server is the access control. No matter what we do in the <a href="http://adobe.com/products/flex">Flex</a>/<a href="http://adobe.com/products/flash">Flash</a>, we can be assured the server (usuallyâ€¦ *sigh*) will ensure we don&#8217;t delete people we&#8217;re not allowed to, delete users en-masse, put illegal characters into their name, etc. Basically anything that would corrupt the data and screw the up the GUI.</p>
<p>In Flex/Flash apps, and nowadays in larger JavaScript web applications, you have a notion of &#8220;application logic&#8221; or &#8220;application state&#8221;. This is because this state is no longer on the server. It used to be with some web applications, usually in the session. When you go add something to your cart on Amazon.com, it&#8217;s not stored on the page that much beyond to show you a slight graphical change. Once you change pages, that JavaScript &amp; HTML page state is now gone and replaced with a new oneâ€¦ but it remembers what you added. It does this because the state is saved on the server since the client needs to be stateless if the user refreshes the page to go to another one.</p>
<p>We don&#8217;t have that problem as much in Flash/Flex apps. We don&#8217;t go to pages insomuch as new &#8220;Views&#8221;. These views, or graphical representations of a GUI that have internal state, are still in the same SWF embedded in the same page in a browser that doesn&#8217;t go anywhere (same thing for an <a href="http://adobe.com/products/air">AIR</a> app on the desktop or on a mobile device). Therefore, someone has to be responsible for holding the data in a variable or series of variables, and updating it when the server gives you new data.</p>
<p>These are usually classes called &#8220;Models&#8221;, and they&#8217;ll usually mirror their server-side equivalents in terms of CRUD operations: create, read, update, and delete. Where they differ is how much of the server-side provided data is parsed, error handling, data access control, and how that server-side data is set internally.</p>
<p>Suffice to say, good Model classes are encapsulated, ensure application logic is accessed by a public API that ensures security, doesn&#8217;t allow the internal data to be corrupted, and does all this within reason. An example is our Player&#8217;s health. If every enemy collision and bullet out there has access to the player&#8217;s health, we have no easy way to track down who may be potentially doing the math wrong on calculating the new hit-points and setting them to invalid values, or thinking the player is dead when she&#8217;s not, etc. If you have a PlayerModel, you can ensure your problem&#8217;s regarding hit-points and letting the world know about player death is in one place, and problems with said state (how much health does the player currently have) starts in that class and those who access him. Access control in this case refers to ensuring the PlayerModel only exposes methods to increment/decrement the Player&#8217;s hit-points vs. allowing them to be set to -16, or NaN/Nil, etc. You don&#8217;t even have to worry about this; you just don&#8217;t allow it to happen.</p>
<p>Thus, the burden on accessing and setting hit-points correctly is pushed to someone else; those who access PlayerModel. THIS is where you look for bugs, but again, you need to ensure only a set few have access to the data access layer (PlayerModel).</p>
<p>In short, Models centralize data access, ensure it&#8217;s correct, testable, and <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> and prevent incorrect access errors, (i.e. global.playerHitPoints = &#8220;dude, pimp!&#8221;).</p>
<p><strong>Preventing Testability</strong></p>
<p>This third problem isn&#8217;t necessarily around unit-testing and <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a> (Test Driven Development), but more around just ripping the class out, putting in a simple main.lua, and seeing if it works. If it has dependencies, they get dragged with itâ€¦ and you have to instantiate and setup those guys. Suddenly quickly confirming some class or method works or not becomes a time consuming process that&#8217;s painful. If you can&#8217;t test something in isolation, you&#8217;ll have huge problems down the road isolating problems in a timely fashion.</p>
<p>Globals by their very nature are&#8217;t testable because they&#8217;re variables, not encapsulated classes. While Lua has some neat mechanisms to encapsulate globals in certain contexts, somewhere, someone is setting a global to some value in their own way. If a class depends on this global, that global must be set the same way before you test the class that relies on the global. Since you may not know who set the global a certain way, that global may not be the same in your test environment vs. in the game proper.</p>
<p><strong>Global Conclusions</strong></p>
<p>While globals in Lua are fast, formalized, and accepted, you must be aware of the rules so you can break them with confidence. First, keep in mind if you want to get something done, premature optimization is the root of all evil. With that in mind, ask yourself the quick question: Does creating a data access control class/layer around your globals to ensure it&#8217;s DRY and secure add so much overhead that the speed makes your game un-playable?</p>
<p>I&#8217;ve found this not to be the case in my implementations in Lua and ActionScript. They run fine, are encapsulated, and succeed in good access control. Thus, while globals are accepted in Lua, implementing a good coding practice via a data access layer does not adversely affect my performance while increasing my productivity in DRY&#8217;er code that&#8217;s easier to test with good encapsulation.</p>
<p><strong>Messaging Dependencies</strong></p>
<p>We&#8217;ve seen how globals can work to allow multiple View&#8217;s to talk to each other directly or indirectly via variables they all reference, or even methods/tables. We&#8217;ve also see how this leads to bad things like harder to find bugs and spaghetti code (you change 1 thing that adversely affects something else seemingly unrelated) as well as making refactoring more challenging than it needs to be.</p>
<p>One way to allow encapsulated objects to communicate is through messaging systems, also know as notifications or events (we&#8217;ll just call them events because that&#8217;s what ActionScript and Corona use). When something happens inside the object, such as a user clicking something, or some internal property changes, it&#8217;ll emit an event. There are 3 types of events we&#8217;re concerned with: local, global, and event context.</p>
<p>A local event is an event issued from an object/table. In ActionScript, anything that extends EventDispatcher, including DisplayObjects (things you can see), can emit events. In Lua, only DisplayObjects can; you have to build your own for regular tables as Lua doesn&#8217;t have an event system. So, if I create a wrapper table in Lua, I can then register for events from that table, and later when it emits them, I&#8217;ll hear them. Those are local events; events dispatched from an object/table directly. Although event objects/tables have the target property on them so I know where they come from, USUALLY event responders are not that encapsulated, and make the assumption that the event is coming from a specific object/table.</p>
<p>A global event is one that&#8217;s received, but we have no clue where it came from. At this point, we&#8217;re inspecting the event object itself to find context. If it&#8217;s a collision, then who collided with who? If it&#8217;s a touch event, then what was touched, and how? Global messaging systems are used for higher-level events and concerns. While you usually won&#8217;t have global events for touches because your mainly concerned with handling the touch event locally, a pause event for example could of been issued from anywhere, and while you don&#8217;t care who issued it, you&#8217;re more than capable of handling it (stopping your game loop, pausing your player&#8217;s movement, etc).</p>
<p>To properly handle an event, we need context. Context is basically the data the event, or message, has stored internally so when the handler gets it, he knows how to handle it. If the event is a touch event, cool, start moving. If it&#8217;s a touch release event, cool, stop moving. If it&#8217;s a collision, is it a bullet? If so, take less damage than say a missile hitting. Is the bullet&#8217;s velocity higher? If so, take more damage than usual. This context is what allows the encapsulation to happen. You issue a message, provide context, and whoever gets it doesn&#8217;t necessarily HAVE to know where it came from; they&#8217;ll have enough information to know how to handle it.</p>
<p>For Corona DisplayObjects, this is easy. You just use dispatch an event. But for Model/data access objects, not so much. You don&#8217;t want the overhead of a DisplayObject to just to send messages, so you build your own. This implies another class/table with the capability of sending/receiving messages. This means your classes will have a dependency on this object. For example, if I want to test my Model class in a brand new main.lua, it&#8217;ll bring along/require the messaging class. This is a dependency. One of the threads (just like OOP, encapsulation, keeping things DRY, don&#8217;t optimize too early, etc) you want to keep in the back of your head is to keep the dependencies low. You don&#8217;t want a class to have too many dependencies. Like globals, dependencies can cause spaghetti code, hard to test &amp; debug situations, and overall just hard to manage code.</p>
<p>Corona makes the event dispatching dependency invisible with DisplayObjects because it&#8217;s built in. Not so for regular tables. Somehow, you have to put this dependency in every class. You can either create a public setter for it, and pass in an instance, or just reference a class globally in a base class. Both are a dependency, the latter just requires a lot less work and code.</p>
<p>Downside? It&#8217;s a dependency. You also force this implementation on everyone who wishes to utilize your class. If you make the messaging system events, 2 things happen. First, people using Corona get it because it&#8217;s the exact same API and functionality (excluding bubbling) that developers are used to. Secondly, it&#8217;s interchangeable and works with Corona DisplayObjects. The best solution would be to do Dependency Injection/Inversion of Controlâ€¦ but I haven&#8217;t figured out how to do this in Lua yet, and I&#8217;m not sure Lua supports metadata annotations. Considering it&#8217;s dynamic, you CAN inject things like this at runtime, but someone, somewhere has to do so. Why do so when every object requiring messaging needs the same mechanism? Thus, the pragmatic thing is to build it in.</p>
<p>Also, more importantly, DOES this messaging system add more performance overhead than using simple globals? To make the question harder to answer, can you make tighter coupling of your code and still get things done?</p>
<p>It&#8217;s been my experience, if you make things easier to use with less coupling, you&#8217;re more productive in the last 10% of your project. While coupling makes things easy in the beginning, it&#8217;s a farce; it has more than an exponential cost at the end.</p>
<p>Besides, you can always increase coupling easily; it&#8217;s removing coupling later that&#8217;s hard. If you need to optimize, great, you can. If not, great, no more work to do; you can instead focus on features. Usually, though, you&#8217;ll know pretty quick if you do iterative builds if a messaging system is making a huge performance impact on your game on not. The only surprises you&#8217;ll get is you spend days on something without a build. Do a small test, see if there is a noticeable difference. Sometimes you&#8217;ll have n-problems you won&#8217;t find till your game gets to a specific size which are unfortunate. An example is a charting component that works great building up to 5000 data points, but suddenly DRASTICALLY slows down beyond that.</p>
<p>These problems aren&#8217;t the fault of the API. If you take a step back, the &#8220;30,000ft view&#8221;, usually it&#8217;s the implementation that&#8217;s at fault, not the code itself.</p>
<p>For example, a little history lesson. Back when ActionScript 1 development was increasing in scope, we went through 4 different messaging systems. The first was the built-in one for Mouse and Keyboard, etc. It was only partially available; there wasn&#8217;t a MovieClip one. So, we used ASBroadcaster; an undocumented one inside of Flash Player. It had a known bug with removing a listener during a dispatch, and other things. Then Bokel released a version on top of that fixed it. Then Adobe created EventDispatcher, mirroring the ECMA one. They then built this into the Flash Player for Flash Player 9&#8217;s new virtual machine.</p>
<p>There were others that came out after ActionScript 3 was born. <a href="http://puremvc.org">PureMVC</a> had notifications in it for an easier port to other platforms &amp; languages. Robert Penner created <a href="http://flashblog.robertpenner.com/2009/09/my-new-as3-event-system-signals.html">Signals</a> for a light-weight, object poolable, quick to develop in C#-esque messaging system.</p>
<p>As you can see, why the bottleneck for most larger Flash &amp; Flex 1.x applications at the time was EventDispatcher, even when they built it into the runtime in C, developers opt-ed for a slower system built by themselves to solve different problems.</p>
<p>So why the continuous talk about performance questions in this section when I rail against premature optimization? Because messaging is the core of any app, or game. The choice you make is the largest impact on what you&#8217;re building, both from performance and from a development perspective. Yes, you can just use direct access to objects, or callbacks, but that&#8217;s not very encapsulated, nor DRY, and is a pain to re-factor later if you need. Messages via Events are more encapsulated, and less coupled, but have a performance impact. Additionally, only DisplayObjects use the internal C implementation; your own uses interpreted Lua with whatever JIT&#8217;ing/machine/voodoo conversion Corona does.</p>
<p>Traditionally, it&#8217;s easy to switch to events from callbacks, but not the other way around. While the performance impact isn&#8217;t that large to utilize a DisplayObject and use the built-in event messaging, based on some benchmarks, this isn&#8217;t a good idea to build upon.</p>
<p><strong>Mediation</strong></p>
<p>The third option is using the <a href="http://flexblog.faratasystems.com/2007/09/26/applying-the-mediator-design-pattern-in-flex">Mediator pattern</a>. Once you have 2 encapsulated objects that need to talk to each other, you utilize a class that handles the communication. It takes the message from ViewA and sends that to ViewB. When ViewB wishes to talk to ViewA, it sends the message and the Mediator relays it.</p>
<p>All the MVC/MVP articles go over A LOT about the different things a View should/should not do,Â particularlyÂ with it&#8217;s needs for data and how to show it. Regardless of the implementation, it&#8217;s generally understood that someone such as a Mediator or a Presenter handels the responses from a View. If it&#8217;s a Presenter, it&#8217;s a dependency in the View, and the View calls methods on it. This allows the actual logic behind both responding to View user gestures (like when I touch a button on the phone) to not muddy up the View (muddy up means TONS of code that has nothing to do with displaying graphics, putting into groups, setting up Sprite Sheets, etc), and allows you to test the behavior in isolation.</p>
<p>Mediator&#8217;s areÂ similar, although, the View has no idea he/she has a Mediator, and the Mediator has the View reference passed into it by someone else. Again, more encapsulation, yet SOMEONE has to have the burden of setting up this relationship. In ActionScript this is easy; Robotlegs just listens for the Event.ADDED_TO_STAGE/REMOVED_FROM_STAGE events and creates/destroys based on an internal hash/table. In Lua, you don&#8217;t have any DisplayObjects events, so you have to manually do it.</p>
<p>Either way, if you DON&#8217;T Mediate your View&#8217;s, you&#8217;ll eventually have a lot of code in there that has to &#8220;know&#8221; about other objects. This&#8217;ll be either a global reference, or a dependency&#8230; and we&#8217;ve already talked about why those things are bad to do. Additionally, tons of code in general is bad; having a View just focus on graphical things and emitting events people outside would care about while the logic can be put elsewhere makes it easier to manage. When you open a View class; you know pretty quickly what you&#8217;re looking at is just GUI specific code.</p>
<p>There&#8217;s another more important aspect of Mediation that isÂ similarÂ to messaging and that is system events that affect Application Logic.</p>
<p>For example, many things in a game care about a Player&#8217;s health.</p>
<ul>
<li>the Sprite that represents the player; it needs to show different graphics for how much health it has</li>
<li>a health bar at the top right of the screen that fills up with green the more health the player has</li>
<li>sounds that play when the player loses and gains health</li>
</ul>
<p>If you use globals, you&#8217;d have all 3 handled by the actual Player sprite class. It&#8217;d update it&#8217;s internal health and update the global variables. Those who have references to the globals would be informed when that value changes. Additionally, you&#8217;ve now wired them together if you do this. If you change one, you&#8217;ll break the other.</p>
<p>Using a Mediator allows:</p>
<ul>
<li>the player and the health bar both the capability to react to the change in the hit points in an encapsulated way. If you change how the Player and HealthBar look/work, the actual logic on how yo do that is centralized to either them, or their Mediators&#8230; and usually Mediators are like 1 line of actual code to change.</li>
<li>The application logic of how hit points are updated and changed to be done in 1 place. As your game grows and different enemies need to do different types of damage to your player, and sometimes react differently depending on how much health the player has, this is all done and updated in 1 place. It&#8217;s DRY, and easy to find where the logic bugs are.</li>
<li>A side effect of this is&#8230; the Mediator pattern (lolz). You can have View&#8217;s the capability of talking to each other without having tight coupling.</li>
</ul>
<p>The most important feature is solving the classic race condition of is the data ready for a View when he&#8217;s created, or is it null and he has to wait. Using Medaitors, you don&#8217;t have this problem. In the onRegister, you just set it if you have it on whatever Model(s) you need, else just wait for the Model(s) to be updated and inform the view.</p>
<p>&#8230;I wouldn&#8217;t say totally solved; handling &#8220;null&#8221; or &#8220;nil&#8221; is still a challenge for developers even in simple View&#8217;s. Those are good problems to have, though vs. race conditions.</p>
<p>If you enter the optimization phase of your game and want to remove events, use callbacks, and have hard-wired references, that&#8217;s fine if benchmarks truly identify that you need theÂ performanceÂ gains. Usually, though, Mediator communication isn&#8217;t your bottle neck, it&#8217;s collisions, lack of object-pooling, and how messages are handled.</p>
<p><strong>Quickie on Commands</strong></p>
<p>Commands are just formalized Controller logic. In fact, in other frameworks, they&#8217;re simply Controller classes with methods. They&#8217;re called &#8220;Commands&#8221; because they do 1 thing&#8230; and can potentially undo it. If you&#8217;ve ever used an Adobe Product, a few of them like Dreamweaver, Fireworks, Flash, and Photoshop will have a Command list, also called &#8220;History Panel&#8221;. In Flash and Fireworks, you can even get the code for these Commands. The line blurs here once you lump them all together, but in my experience, good Controllers have 2 things in common:</p>
<ol>
<li>They contain the only code in the application that updates the Models (update/delete in CRUD for internal data)</li>
<li>They contain all application logic&#8230; or at least share the burden with the Models.</li>
</ol>
<p>For #1, this is important in tracking down bugs and keeping your code DRY. You always know who&#8217;s changing your Player&#8217;s hit points, who&#8217;s actually applying your level up rewards, etc. If you can test your Models in isolation, and they&#8217;re good&#8230; then you know who to blame. This is good because again, they tend to often start by being 1 line functions with the potential to grow to 30 to 60&#8230; not a bad way to start life, nor grow. Small, readable code.</p>
<p>For #2, whether you have a Controller class function, or a Command, SOMEONE in your application needs to &#8220;load the level data&#8221; from your level editor. SOMEONE needs to handle the fact that your player just drank a health potion, but he&#8217;s also wearing a Ring of Health Boost + 2, and this positively affects the effects of the health potions she drinks. SOMEONE needs to handle calling the loadSaveGame service, ensuring it worked, and updating all the Models with theirÂ relevantÂ Memento data.</p>
<p>This orchestrator of pulling everyone together, to read multiple Models and &#8220;make decisions&#8221;, they&#8217;re the brains of your application. For performance reasons, a lot of Controller logic is often done directly in game views, even if it just references a Controller class for ensuring logic is somewhat DRY.</p>
<p>There&#8217;s a lot of loathing in the community by those with a moreÂ pragmaticÂ bent, or just on smaller code bases with shorter deadlines. The overhead associated with them completely negates their perceived value when you can just call a centralized Controller logic function via&#8230; a function call vs. some event that magically spawns some other class that has 1 function with a bunch of injected dependencies. Just depends in you read that last sentence and go &#8220;Makes sense to me, don&#8217;t see what the issue with it is&#8230; &#8221; or &#8220;w&#8230;t&#8230;f&#8230; why!?&#8221;.</p>
<p><strong>Conclusions</strong></p>
<p>Remember, the above is all complete bs. If you or your team have a way of building games that works for you, great. This is just helpful tool I&#8217;ve found in Flash &amp; Flex application development, and it seems to help me in Corona games, specifically around the GUI/HUD portions. I still have globals in my collision routines for speed purposes, hehe.</p>
<p>Additionally, it&#8217;s a great teaching tool, too. <a href="http://joelhooks.com">Joel Hooks</a> got someÂ similarÂ schlack like I did in using <a href="http://puremvc.org">PureMVC</a> when he was first starting out in Objective C for iPhone. Providing a comfortable &amp; familiar framework of development really helped him learn and have context how the new language &amp; platform work with certain concerns; it&#8217;s how he shipped his first app on the app store. Same with me in Corona&#8230; and game development.</p>
<p>Finally, this isn&#8217;t an all or nothing approach. You can just use it on the parts you need, or perhaps just to learn. I find its helped me learn a lot about Lua and Corona, as well as having theÂ flexiblyÂ to change the API of my Player and Enemies without affecting how the GUI itself around the game works. In true spirit of total disclosure, I&#8217;ll report on any adverse overhead if I find it.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2011/08/why-robotlegs-for-games.html/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
	</channel>
</rss>
