<?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> &#187; Design Patterns</title>
	<atom:link href="http://blog.vortixgames.com/tag/design-patterns/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.vortixgames.com</link>
	<description></description>
	<lastBuildDate>Sun, 05 Feb 2012 00:55:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>BADJ Day 19: So much stuff&#8230;</title>
		<link>http://blog.vortixgames.com/badj-day-19-so-much-stuff</link>
		<comments>http://blog.vortixgames.com/badj-day-19-so-much-stuff#comments</comments>
		<pubDate>Mon, 18 Oct 2010 23:29:33 +0000</pubDate>
		<dc:creator>Vlad</dc:creator>
				<category><![CDATA[Dev Journal: Bruce Ali]]></category>
		<category><![CDATA[Bold Pixel Engine]]></category>
		<category><![CDATA[Bruce Ali]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[FlashGameBlogs]]></category>

		<guid isPermaLink="false">http://blog.vortixgames.com/?p=1007</guid>
		<description><![CDATA[Nineteen days have gone&#8230; WOW! After getting full speed ahead for a number of days, I had a stop for a day&#8230; domestic stuff kicked in. A lot of work was finished in those quick days though. With all physics and blit done, I went straight ahead into coding the level. First task was to [...]]]></description>
			<content:encoded><![CDATA[<p>Nineteen days have gone&#8230; WOW! After getting full speed ahead for a number of days, I had a stop for a day&#8230; domestic stuff kicked in. A lot of work was finished in those quick days though.</p>
<p>With all physics and blit done, I went straight ahead into coding the level. First task was to look at what I had done previously and finding out&#8230; it would be easier to just start over, which I did! One very cool thing is that a Finite State Machine class I wrote earlier really proved its worth and is the base for all stuff in the level. I really have to go through how the level code is structured as soon as the dust settles down since right now a lot can change and it will probably make no sense.</p>
<p>One thing I had to change was the Manager class. Remember I mentioned a dependency to a specific class that put all in motion. That is easier to manage now.</p>
<p>But the really cool thing I did today was to quickly test a console class! I used <a href="http://junkbyte.com/wp/?p=43#more-43" target="_blank">Junkbyte&#8217;s Console 2.4</a> and I just love it! With it we will be able to change a lot of aspects in the game without recompiling.</p>
<p>What is happening right now? Visually? Not much, there&#8217;s a circle representing Bruce on screen. Code wise there&#8217;s a lot of stuff going on. For starters all the level classes (controller, factory, scene, blit, physics, etc) are created and doing their thing, so it&#8217;s just a matter of adding features to it. The state management system is just beautiful and it will save tons of work!</p>
<p>What is missing? Graphics and stuff getting kicked!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vortixgames.com/badj-day-19-so-much-stuff/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>BADJ Day 11: A successful frustration</title>
		<link>http://blog.vortixgames.com/badj-day-11-a-successful-frustration</link>
		<comments>http://blog.vortixgames.com/badj-day-11-a-successful-frustration#comments</comments>
		<pubDate>Wed, 06 Oct 2010 23:56:01 +0000</pubDate>
		<dc:creator>Vlad</dc:creator>
				<category><![CDATA[Dev Journal: Bruce Ali]]></category>
		<category><![CDATA[Bold Pixel Engine]]></category>
		<category><![CDATA[Bruce Ali]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[FlashGameBlogs]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://blog.vortixgames.com/?p=967</guid>
		<description><![CDATA[So I coded and recoded, tested and retested a Object Pool class with a high degree of success and frustration. I wrote and tested three different pool managers, here&#8217;s the story&#8230; Objective: Centralized management of pools This one was easy. There is a PoolManager that has a static method to get a pool for a [...]]]></description>
			<content:encoded><![CDATA[<p>So I coded and recoded, tested and retested a Object Pool class with a high degree of success and frustration. I wrote and tested three different pool managers, here&#8217;s the story&#8230;</p>
<h3>Objective: Centralized management of pools</h3>
<p>This one was easy. There is a PoolManager that has a static method to get a pool for a certain class. If the pool for that class does not exist, it is created, if it does, it is returned. Objective achieved.</p>
<h3>Objective: Lightweight pools</h3>
<p>I don&#8217;t need pools to be amazingly complex, I just need the pools to get the job done, which is: be faster at getting new objects at the expense of memory. That didn&#8217;t go very well. The pools were lightweight alright, but I was not able to make it any faster than creating a objective directly.</p>
<p>This lead to the three versions of the pool manager and still the best performance gain is below 5% for any Bold Pixel entity. I was so frustrated, but then I saw the light!</p>
<h3>Not my fault really</h3>
<p>After testing and more testing I had a epiphany! What if Bold Pixel&#8217;s entities are simply too light to make pooling worth. It would not be something I&#8217;d consider. It really never crossed my mind that a instancing a object could be faster than getting it from a linked list kind of pool, but it is and the classes I was dealing with are somewhat heavy considering the inheritance and and composition of several.</p>
<p>The highest gain I got was 8ms in 1000 object. Creating 1000 objects took 54ms and getting 1000 objects from the object pool took 46ms.</p>
<h3>The unexpected success</h3>
<p>So either my classes are very light or flash behaves rather poorly in managing this. So I tested against some movie clip I had around. Creating 1000 movie clips took 102ms, almost doubling the worst case scenario.</p>
<p>Not only I was happy to note that my classes are lightweight, both pool manager and entity type classes, but I also proved that getting movie clips would make a difference.</p>
<h3>Conclusion</h3>
<p>I&#8217;m not happy with the pool manager for now, but I&#8217;ll work on it some other day. It gets the job done, but the objects I really wanted to make a better use of pooling are the ones that problably will have less impact.</p>
<p>If I regret anything in this bits of code is that I over engineered it at first. Tomorrow blit engine!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vortixgames.com/badj-day-11-a-successful-frustration/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Bold Pixel&#8217;s Namespaces and Interfaces</title>
		<link>http://blog.vortixgames.com/bold-pixels-namespaces-and-interfaces</link>
		<comments>http://blog.vortixgames.com/bold-pixels-namespaces-and-interfaces#comments</comments>
		<pubDate>Wed, 01 Sep 2010 00:46:23 +0000</pubDate>
		<dc:creator>Vlad</dc:creator>
				<category><![CDATA[The code of VGS]]></category>
		<category><![CDATA[Bold Pixel Engine]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[FlashGameBlogs]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://blog.vortixgames.com/?p=911</guid>
		<description><![CDATA[After much thought and discussion by myself or at the FGL chat I made some decisions about how to make Bold Pixel more modular in order to simplify my own work. Since we are still on top of contracts, I couldn&#8217;t give enough attention to this but my brain was dealing with it in the [...]]]></description>
			<content:encoded><![CDATA[<p>After much thought and discussion by myself or at the FGL chat I made some decisions about how to make Bold Pixel more modular in order to simplify my own work. Since we are still on top of contracts, I couldn&#8217;t give enough attention to this but my brain was dealing with it in the background.</p>
<h3>Inheritance Spaghetti</h3>
<p>The problem presented was somewhat simple. My early coding of the blit engine got tangled in the dreadful inheritance headaches. My solution to it was to create one class per major responsibility. It worked fine until the time I decided to expand one of the classes to do something it wasn&#8217;t designed to do. So on one hand I solved the inheritance problems but on the other I lost modularity. At this time I had a OOP doubt that I expressed in the FGL forums and the discussion that started there really helped me to move in a different direction, one that I had never considered.</p>
<p>More over I said that I would not support requests that didn&#8217;t deal with deal with real problems we had in our own development. And while I stick to that, I couldn&#8217;t help but to think: what if Bold Pixel could help someone but it missed one little tiny feature? While this was puzzling me, there was real problem, one with impact in our development that was taunting me&#8230;</p>
<h3>The case of Blit vs Physics</h3>
<p>So Bold Pixel has a blit engine and it will wrap a physics engine (more about the physics engine this later this month) so the question that was on top of the table was: considering there is a blit entity and a physics entity, which one should access the other? Whatever the answer was, modularity was lost in the sense I imagine it. I don&#8217;t want blit to know physics and I don&#8217;t want physics to know blit!</p>
<p>After a nice chat with Antriel at FGL (thanks mate!) I got to know the <a href="http://en.wikipedia.org/wiki/Strategy_pattern" target="_blank">Strategy Pattern</a> and all my problems were solved. In simple terms, I will be defining interfaces for all interchangeable objects but the implementations of the interfaces can exist anywhere. In the case presented, a blit entity will have its spatial properties (rotation, x, y and scale) defined by a spatial interface. By default it will be a simple class and it&#8217;s needed since the properties of the spatial interface are needed to render bitmapdata. A physics entity will be a implementation of  the spatial interface, so if I want to use physics on a blit entity, I simply write: myBlitEntity.position = myPhysicsEntity;</p>
<h3>Visibility and Access Issues</h3>
<p>This brought another problem. Bold Pixel has always kept its inner &#8220;stuff&#8221; hidden. The objective was this was to keep the auto-completion short and the use easy preventing mistakes. In order to implement interfaces I would have to make a lot of code public.</p>
<p>The answer to this would be <a href="http://en.wikipedia.org/wiki/Abstract_class" target="_blank">abstract classes</a>, but ActionScript3 does not support it. That will be addressed with simple naming and convention over configuration. Any class in any namespace in Bold Pixel that starts with Abstract will only have the simplest shortest implementation needed for something to work. For instance, if I want a blit entity that draws pixels I will have to extend a AbstractBlitEntity class (I guess that will be the name) but that brings another problem&#8230;</p>
<p>So ActionScript does not support abstract classes&#8230; convention will say that Abstract defines an abstract class.</p>
<h3>Namespaces (to wrap this up!)</h3>
<p>To have a better code organization I will need more packages and to have more packages I will need to provide access to classes in different packages. This will be done with namespaces. The only thing that annoys me is that Flash Develop in the current version (3.2.2) does not support code-completion with custom namespaces, but what matters is that using custom namespaces solves two problems. First I can have a bunch of private functionality like I like, but second, any coder can with a simple namespace use extend Bold Pixel to his own needs in a full modular way.</p>
<p>While I reckon that this is all just in my head and that a lot of work will have to be done and even considering that probably this will make Bold Pixel a little bit more complicated to the average coder, I feel it sorts a lot of questions, so: Namespaces and Interfaces FTW!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vortixgames.com/bold-pixels-namespaces-and-interfaces/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>From refactor to library</title>
		<link>http://blog.vortixgames.com/from-refactor-to-library</link>
		<comments>http://blog.vortixgames.com/from-refactor-to-library#comments</comments>
		<pubDate>Tue, 30 Jun 2009 23:40:09 +0000</pubDate>
		<dc:creator>Vlad</dc:creator>
				<category><![CDATA[The code of VGS]]></category>
		<category><![CDATA[Bold Pixel Engine]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[FlashGameBlogs]]></category>

		<guid isPermaLink="false">http://blog.vortixgames.com/?p=384</guid>
		<description><![CDATA[Or how to refactor the code from your last game to build up your reusable libs. First and foremost, thanks to the people at FGL chat that brainstormed a jolly good topic to write about. This post also helps me to rethink my strategy about an issue I have with our core libs that I&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<p>Or how to refactor the code from your last game to build up your reusable libs.</p>
<p>First and foremost, thanks to the people at FGL chat that brainstormed a jolly good topic to write about. This post also helps me to rethink my strategy about an issue I have with our core libs that I&#8217;ll hopfully address in the future as soon as I make sense.</p>
<p>Basic question is how do I handle the code I used in the previous game to reuse it&#8230; I&#8217;ll give several examples of how our core classes appeared or changed hoping that you find something useful for your own code and games.</p>
<h2><span style="color: #ff9900;">In the beggining there was music</span></h2>
<p>When we wrote Tech Wars, I had to write a music manager that would know when to change tracks. There are three tracks in Tech Wars, all with the same beats per minute, two share the melody but with different instruments and one has a slight variation of the melody. Each track served a part of the game, such has menus, level, and post-level.</p>
<p>Our current music manager has code from Tech Wars. That code evolved from a game specific class to a generic sound manager class and then to two separate classes: sound manager and music manager. These shifts occured as the next games needed or between projects.</p>
<p><img class="aligncenter size-full wp-image-385" title="core" src="http://blog.vortixgames.com/wp-content/uploads/2009/06/core.jpg" alt="core" width="403" height="184" /></p>
<p>What started with Tech Wars is now what we call the core, which is simply a bunch of abstract, cross-project oriented organization of directories and classes that goes from one project to another. It is not something you do, it is something you keep doing, building and evolving. That sound manager class was a bad case of refactoring, but a good start since we had no reusable AS code.</p>
<h2><span style="color: #ff9900;">Generalization</span></h2>
<p>To create your libs you should make each class abstract from the game code. This maybe trickier than it sounds. For instance, we have a Scene Manager. What it does is quite simple:</p>
<blockquote><p>1. ensures that one and only one scene is running<br />
2. ensures that one and only one dialog is running<br />
3. ensures that when a scene is started the current scene and current dialog are closed<br />
4. ensures that when a dialog is started the current dialog is closed</p></blockquote>
<p>And this has to work in every game. To be sure that it works in every game I made sure that a scene or a dialog is always a movie clip that is linked in the fla library and that I can pass up to five arguments to it. I also made sure that the Scene Manager is a singleton.</p>
<h2><span style="color: #ff9900;">Get yourself organized</span></h2>
<p>To be sure that your code is generic, organize it! Create a structure outside your game logic, as an example, when I start a project I copy the core directory from the previous project to the root of the current project and I create a separate directory &#8220;game&#8221; where all the game specific classes go.</p>
<p>It&#8217;s that simple.</p>
<h2><span style="color: #ff9900;">Refactoring</span></h2>
<p>Refactoring plays a big role in all of this. Now that the core classes are a few and that most of the nasty work is done, the process of refactoring tunes it and adds to it.</p>
<p>Again&#8230; an example. Some hours ago I was using a static method MathKit.AngleBetweenPoints(p1, p2) which is pretty obvious, but for some reason the code did not produce the results I predicted, so I wrote a bit of code to ensure the output I was looking for.</p>
<p>The issue was that MathKit.AngleBetweenPoints(p1,p2) returns an angle in radians and I wanted degrees. I already have two static methods in the MathKit class to convert radians in degrees and vice-versa, so in the next refactoring session I&#8217;ll rename MathKit.AngleBetweenPoints to MathKit.RadiansBetweenPoints and create a new DegreesBetweenPoints.</p>
<p>The refactoring will eliminate generic code from game specific code, it will reuse static methods we already have in the MathKit class, make the method already there more intuitive and create an additional method for other uses.</p>
<h2><span style="color: #ff9900;">Managers = Singletons</span></h2>
<p>Managers are classes that take care of a specific aspect of your game. Scenes, music, sound and so on. You should be sure that your managers are singletons and that you can access them everywhere. To be sure of it, all our managers are loaded by the Application Manager which is what all our document classes extend. Neat trick and quite useful.</p>
<h2><span style="color: #ff9900;">Tools = Static</span></h2>
<p>All our tools are static methods. We don&#8217;t want our tools to be instantiated. We don&#8217;t want our tools to hold data. We want our tools to do something specific and produce an output.</p>
<h2><span style="color: #ff9900;">At the end of the day</span></h2>
<p>Like I said, when we start a new game I copy the core directory of the latest game to the new one. Usually I take a look a t it or look for //TODO remarks for something I want to review. While the code base was growing this was very useful, right now it&#8217;s a matter of tunning some details since most work is done while refactoring.</p>
<p>I do have a damn project to go though&#8230; writing the graphic handling classes&#8230; but I still have a load of doubts to sort first.</p>
<p>Oooops&#8230; big one&#8230; Vlad out! <img src='http://blog.vortixgames.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vortixgames.com/from-refactor-to-library/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Model&#8230; revisited&#8230;</title>
		<link>http://blog.vortixgames.com/model-revisited</link>
		<comments>http://blog.vortixgames.com/model-revisited#comments</comments>
		<pubDate>Fri, 19 Jun 2009 10:25:16 +0000</pubDate>
		<dc:creator>Vlad</dc:creator>
				<category><![CDATA[The code of VGS]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[FlashGameBlogs]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://blog.vortixgames.com/?p=330</guid>
		<description><![CDATA[Hi everyone, it&#8217;s Vlad again. It&#8217;s 10:52AM, 30 degrees Celsius if you stand in the shadow and just a couple of hours ago I hit an issue with our current project. Basically static data regarding gameplay was becoming completely unmanageable. Before moving forward I decided to rethink and drew how my classes were organized. Let [...]]]></description>
			<content:encoded><![CDATA[<p>Hi everyone, it&#8217;s Vlad again.</p>
<p>It&#8217;s 10:52AM, 30 degrees Celsius if you stand in the shadow and just a couple of hours ago I hit an issue with our current project. Basically static data regarding gameplay was becoming completely unmanageable. Before moving forward I decided to rethink and drew how my classes were organized.</p>
<p style="text-align: center;"><img class="size-full wp-image-331 aligncenter" title="no_actual_model" src="http://blog.vortixgames.com/wp-content/uploads/2009/06/no_actual_model.jpg" alt="no_actual_model" width="512" height="232" /></p>
<p>Let me tell you what this is&#8230; Data and Gameplay are folders, packages in AS3 terms. Tokentype1, Tokentype2 and Constants are classes that hold data in the form of static functions and constants. LevelController, LevelView, TokenController and TokenView are classes that are either controllers or views of my gameplay objects.</p>
<p>This is how I&#8217;ve organized most projects until now, so what&#8217;s the problem? For starters, all games until now have only one token type. This game has two but it will have more. I was about to actually copy/paste a method from TokenType1 class to the TokenType2 class&#8230; you know how bad this is right?</p>
<p>On top of that a new problem was present for a couple of days. Some variables names, class names and query methods conflicted, not logically but in terms of what I was reading while coding. Building, IsBuilding, buildings, building and so on&#8230; variables like type, code and state also weren&#8217;t 100% clear.</p>
<p>So I decided that it was time to redesign and refactor before it became too nasty. Here&#8217;s the result:</p>
<p style="text-align: center;"><img class="size-full wp-image-332 aligncenter" title="now_with_a_model" src="http://blog.vortixgames.com/wp-content/uploads/2009/06/now_with_a_model.jpg" alt="now_with_a_model" width="512" height="232" /></p>
<p>I simply took the MVC pattern seriously and created models for both level and tokens. On top of that I changed all ambiguous variables, states and methods to be named consistently throughout the project.</p>
<p>The LevelModel is nothing more than the old Constants class. There&#8217;s no big difference for now except that when gameplay is closed and we move to other stuff, I&#8217;ll have to create models for all the other stuff instead of having all constants inside one &#8220;global&#8221; constants class.</p>
<p>The TokenModel is the big change! It holds all the stuff from TokenType1 and TokenType2 classes, but now I can guarantee that there are no duplication of methods, arrays and so on. Big part of this arrangement was to deal with the inconsistent naming of variables and so on.</p>
<p>I&#8217;m very happy with the solution, now, if you excuse me, I&#8217;ll get back to coding game functionalities.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vortixgames.com/model-revisited/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Model View Controller</title>
		<link>http://blog.vortixgames.com/model-view-controller</link>
		<comments>http://blog.vortixgames.com/model-view-controller#comments</comments>
		<pubDate>Wed, 18 Mar 2009 00:00:08 +0000</pubDate>
		<dc:creator>Vlad</dc:creator>
				<category><![CDATA[The code of VGS]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[FlashGameBlogs]]></category>

		<guid isPermaLink="false">http://blog.vortixgames.com/?p=267</guid>
		<description><![CDATA[I learnt about the MVC pattern when I was presented to the book Game Coding Complete. Although the implementation of this pattern on a game development related environment can take some pre-planning, using it allows a much cleaner implementation of your objects with particular relevance for those that have a visual implementation, such as a [...]]]></description>
			<content:encoded><![CDATA[<p>I learnt about the <a href="http://en.wikipedia.org/wiki/Model_view_controller" target="_blank">MVC</a> pattern when I was presented to the book <a href="http://www.amazon.com/Game-Coding-Complete-Mike-McShaffry/dp/1584506806/ref=sr_1_3?ie=UTF8&amp;s=books&amp;qid=1237298061&amp;sr=1-3" target="_blank">Game Coding Complete</a>. Although the implementation of this pattern on a game development related environment can take some pre-planning, using it allows a much cleaner implementation of your objects with particular relevance for those that have a visual implementation, such as a level or a game token.</p>
<p>I&#8217;m saying object, not as an instance of a class, but rather as an abstract game object from a design point of view.</p>
<p>Let&#8217;s break the pattern down into manageable parts&#8230; after all, that&#8217;s exactly what the pattern does.</p>
<h2><span style="color: #ff9900;">Model</span></h2>
<p>The model is the data representation of your object. Outside game development, model refers to the data model, usually supported by a database engine. From a game development perspective, model is what your object is, like a level, a platform, the player character, an enemy and so on. If you coded a class that represents something, you have already created a model already.</p>
<p>The main difference with application development is that the data models you use are not persistent and are discarded when they&#8217;re not needed.</p>
<p>The idea you should retain game development wise is that your &#8220;typical&#8221; class design, considering variables, constants and so on is your model, even if this is not 100% accurate from the pattern point of view.</p>
<h2><span style="color: #ff9900;">View</span></h2>
<p>The view is the visual representation of your object, which would be any display object, from a movie clip to a bitmap. It is nothing more than this.</p>
<h2><span style="color: #ff9900;">Controller</span></h2>
<p>The controller glues everything together! It is the logic behind the actions of your object. Imagine a player character that moves with WASD for the actions Jump, Crouch, Move Left and Move Right. If the player presses W the controller will receive the event and order the view to run the jump animation. Now imagine that some enemy shoots the player character while it is jumping. The controller receives the information that the player was shot, informs the model to subtract damage to player&#8217;s life and orders the view to run the hurt animation.</p>
<h2><span style="color: #ff9900;">Encapsulating all together</span></h2>
<p>The easiest way to implement OOP on your AS3 game is to simply extend some movie clip to a class and write all code there. With MVC, you need to encapsulate a bit. There are many ways to do this, but this is how I do it.</p>
<p>My controller and view are only one class: the main object class. The view is separated which allows me to have a cleaner interface when I&#8217;m working and the possibility of extending or not the view class. This offers a wide range of possibilities since the view class can hold a large ammount of functionality, such as movement patterns, pathfinding and so on or it can simply be the display object.</p>
<p>Controller and view work together regarding data and logic. As I see it they&#8217;re not even separarated as a proper implementation of MVC. This often means that a simple state machine is at work, like in the example below.</p><pre class="crayon-plain-tag"><code>package
{
   // This is my controller/model class
   public class PlayerController
   {
      public function PlayerController()
      {
         // Creates the view
         playerView = new PlayerView();

         // Code to add it to the level movie clip goes here
      }

      public function Update()
      {
         // This method is called from the gameloop

         // Depending on the state, chooses actions
         switch(state)
         {
            case IDLE:
               playerView.UpdateAnimation(IDLE);
               break;
            case WALK:
               playerView.UpdateAnimation(WALK);
               break;
            case HURT:
               playerView.UpdateAnimation(HURT);
               break;
            case NONE:
               SetState(IDLE);
               break;
         }
      }

      public function SetState(newState:int)
      {
         // No point in doing something that
         if (newState == state) return;

         // Only does something different if the player is hurt
         if (newState == HURT) life--;

         // And assigns the new state
         state = newState;
      }

      // Vars ---------------------------------------------------------------

      private var life:int = 100;      // Hit points
      private var state:int = NONE;   // Current state

      private const NONE:int = 0;
      private const IDLE:int = 1;
      private const WALK:int = 2;
      private const HURT:int = 3;

      private var playerView:PlayerView;   // The view (displayObject)
   }
}</code></pre>
<h2><span style="color: #ff9900;">A word of caution</span></h2>
<p>MVC is very powerful, easy and intuitive, but use it when your game asks for it. If you have an object that only needs a couple of methods, by all means, simply extend the movie class or whatever you are extending. Use it to break the complex objects into manageable parts.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vortixgames.com/model-view-controller/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Factory</title>
		<link>http://blog.vortixgames.com/factory</link>
		<comments>http://blog.vortixgames.com/factory#comments</comments>
		<pubDate>Mon, 09 Mar 2009 00:00:09 +0000</pubDate>
		<dc:creator>Vlad</dc:creator>
				<category><![CDATA[The code of VGS]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[FlashGameBlogs]]></category>

		<guid isPermaLink="false">http://blog.vortixgames.com/?p=238</guid>
		<description><![CDATA[I try to use design patterns to the best possible extent of my ignorance about them. I want to set this straight because like anything found on the Internet, everything here is potentially wrong or a lie. My view on design patterns and so many other things code wise is much more from my own [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_240" class="wp-caption alignleft" style="width: 160px"><img class="size-full wp-image-240" title="Factory" src="http://blog.vortixgames.com/wp-content/uploads/2009/03/blogfactory.jpg" alt="Factory" width="150" height="150" /><p class="wp-caption-text">Factory</p></div>
<p>I try to use design patterns to the best possible extent of my ignorance about them. I want to set this straight because like anything found on the Internet, everything here is potentially wrong or a lie. <img src='http://blog.vortixgames.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p>
<p>My view on design patterns and so many other things code wise is much more from my own personal perspective and experience, if you want to know more, there&#8217;s much more to learn about it, this is just how I see it. </p>
<h2><span style="color: #ff9900;">What is a Factory?</span></h2>
<p>Factory was probably the first I was taught (thanks Diogo!) and one that I used in every single game. From ballons to bullets, every time the need to create objects arises, factory was my choice.</p>
<p>The only purpose of a factory is to create and return objects. From a game development point of view this is useful since the factory is by default reusable code within the game.</p>
<p>If you code a factory class you can use it as a priceless source of objects, from projectiles &#8211; as in this example &#8211; to enemies or whatever you want really, it&#8217;s up to you.</p>
<h2><span style="color: #ff9900;">Example</span></h2>
<p>Imagine you are coding a shooter where the player has four possible weapons: machine gun, rocket, missile and mines. Every time the player shoots, the player object would have to decide what to build based on the current weapon. It would be something like this:</p><pre class="crayon-plain-tag"><code>package FactoryExample
{
	import flash.display.MovieClip;

	public class NoFactoryPlayerClass
	{
		public function FireWeapon() extends MovieClip
		{
			switch(currentWeapon)
			{
				case BULLET: CreateBullet(); break;
				case ROCKET: CreateRocket(); break;

				// And so on and so forth...
			}
		}

		private function CreateBullet()
		{
			var bullet:Bullet = new Bullet(rotation);

			// Plus, add bullet to level bla bla bla
		}

		private function CreateRocket()
		{
			var rocket:Rocket = new Rocket(rotation);

			// Plus, add rocket to level bla bla bla
		}

		private var currentWeapon:int = BULLET;

		private const BULLET:int = 1;
		private const ROCKET:int = 2;
		private const MISSILE:int = 3;
		private const MINE:int = 4;
	}
}</code></pre><p>By the way, the code here is for clarity, I didn&#8217;t even run it to check for errors.</p>
<p>What we have here is bad enough by the way. CreateBullet() and CreateRocket() would roughly have the same construction for instance, but it can get much worse. What if you want to use one, some or all the weapons in different enemies or you want to have more weapons?</p>
<p>I&#8217;m guessing&#8230; copy/paste?</p>
<p>That&#8217;s why you should use a factory from start: because you can manage all your projectiles from a single point and you can extend it to have more weapons without duplicated code which you&#8217;d probably maintain with a higly dangerous dosage of copy and paste.</p>
<p>This would be our factory class:</p><pre class="crayon-plain-tag"><code>package FactoryExample
{
	public class Factory
	{
		public static function CreateProjectile(type:int, data:* = null)
		{
			/* Bullets and Rockets only receive an angle from which they'll
			 * calculate the vector.
			 * Missiles - see FireMissile method.
			 * Mines just stand still. */

			switch(type)
			{
				case BULLET: 	return new Bullet(data);	break;
				case ROCKET:	return new Rocket(data);	break;
				case MISSILE:	return FireMissile(data);	break;
				case MINE:	return new Mine();		break;
			}
		}

		private static function FireMissile(enemy:*)
		{
			// Gets the angle from the level object to create the missile.
			var enemyAngle:Number = LevelObject.GetAngle(enemy);

			// Creates the missile with the target enemy and the angle.
			return new Missile(enemy, enemyAngle);
		}

		// Projectile types ---------------------------------------------------

		public static const BULLET:int	= 1;
		public static const ROCKET:int 	= 2;
		public static const MISSILE:int	= 3;
		public static const MINE:int	= 4;
	}
}</code></pre><p><p>
In this case, the factory is a class that offers static functions, so you don&#8217;t have to instantiate an object from the Factory class. Note that the CreateProjectile receives the type (duh!) and some other data that can be anything or nothing at all.</p>
<p>The purpose of this is to pass angle to bullets and rockets, the target enemy to missiles and nothing to mines.</p>
<p>So now, any class that would need to fire a projectile would need a method like this:</p><pre class="crayon-plain-tag"><code>package FactoryExample
{
	import flash.display.MovieClip;

	public class WithFactoryPlayerClass extends MovieClip
	{
		private function Fire()
		{
			var data:* = null;

			switch(currentWeapon)
			{
				case Factory.BULLET: data = rotation; break;
				case Factory.ROCKET: data = rotation; break;
				case Factory.MISSILE: data = targetEnemy; break;
			}

			var projectile:* = Factory.CreateProjectile(currentWeapon, data);
			// Do more stuff with projectile
		}

		private var currentWeapon:int;
		private var targetEnemy:*;
	}
}</code></pre><p><p>
<h2><span style="color: #ff9900;">And to end&#8230;</span></h2>
<p>Imagine that the enemies in your game have a predifined weapon&#8230; instead of a bunch of code you will only need one line in you enemies classes:</p>
<pre class="crayon-plain-tag"><code>var projectile:* = Factory.CreateProjectile(myWeapon, otherData);</code></pre>
<p>It can&#8217;t get any easier than this!</p>
<p>I hope this helped you sort how factories can help you. Take into consideration that you can use a factory with pools of objects, this is an example that creates all objects on demand. There&#8217;s a lot more that can be done, but the rule of thumb is: a factory can be the answer to many object creation needs a bit everywhere, but in game development it really shows what this design pattern is capable of.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vortixgames.com/factory/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

