<?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>Toni Westbrook dot Com &#187; Games</title>
	<atom:link href="http://www.toniwestbrook.com/archives/category/games/feed" rel="self" type="application/rss+xml" />
	<link>http://www.toniwestbrook.com</link>
	<description>Sharing Software Development Knowledge With You</description>
	<lastBuildDate>Mon, 06 Sep 2010 01:46:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Blackberry &#8211; Mixing 2 or More Sounds Together (Concept Video)</title>
		<link>http://www.toniwestbrook.com/archives/267</link>
		<comments>http://www.toniwestbrook.com/archives/267#comments</comments>
		<pubDate>Thu, 02 Sep 2010 05:29:19 +0000</pubDate>
		<dc:creator>Toni</dc:creator>
				<category><![CDATA[Blackberry]]></category>
		<category><![CDATA[Games]]></category>

		<guid isPermaLink="false">http://www.toniwestbrook.com/?p=267</guid>
		<description><![CDATA[An Audio Issue One thing that I (and many others judging by forum posts) have run into is the fact that the Blackberry isn&#8217;t very good at mixing more than one sound together. You&#8217;ll be listening to music, or playing a game with music, and suddenly you&#8217;ll get a text message, and it will simply [...]]]></description>
			<content:encoded><![CDATA[<p><b> An Audio Issue </b></p>
<p>One thing that I (and many others judging by forum posts) have run into is the fact that the Blackberry isn&#8217;t very good at mixing more than one sound together.  You&#8217;ll be listening to music, or playing a game with music, and suddenly you&#8217;ll get a text message, and it will simply terminate the current sound and play the new one.  If you&#8217;ve got a friendly application, it will restart/resume the original audio, but it&#8217;s a jarring audio experience.</p>
<p>What I&#8217;m about to post won&#8217;t fix that.  However &#8211; developers also run into the issue when they want to mix sounds together in their applications and games.  Play 2 or more sound effects simultaneously and/or while music is playing.  I&#8217;ve seen official RIM developers comment that certain devices can achieve two simultaneous sounds by instantiating the Player class twice &#8211; but from what I gather, this is on GSM only phones &#8211; and still limited to two.  On CDMA devices, you&#8217;re completely out of luck.</p>
<p><b> The Cheap and Quick Workaround </b></p>
<p>In my 6 part tutorial on writing a Blackberry game, in the <a href="http://www.toniwestbrook.com/archives/75">audio article</a>, I mentioned how the Alert.startAudio method can be used for simple sound effects (tone/duration pairs) that will play simultaneously while your midi or mp3 music plays in the background.  For many applications, this is enough if you don&#8217;t need sophisticated sound effects.</p>
<p><b> The Start of a Mixer </b></p>
<p>I&#8217;m guessing that the limitation is imposed by the audio chipset/DAC inside of CDMA devices, and perhaps RIM realizes the CPU time involved in a software based audio mixer would slow the phone down too much.  However, I think the software option should be there, and developers can use it if they&#8217;d like &#8211; they might not need a large amount of CPU, or might be dealing with low quality sound files &#8211; there are a few scenarios where a software mixer would just be a nice options.</p>
<p>Tonight I sat down and wrote a quick and dirty proof of concept application showing a PCM audio mixer in action.  I loaded in 3 audio 44.1khz 8bit mono files and mixed them together in real time.  I didn&#8217;t normalize the audio at all, so its a little soft, but the code works, and could be expanded on quite a bit to make a full featured mixer. Maybe I&#8217;ll run into problems down the road that RIM already has, but it&#8217;ll be interesting nonetheless.</p>
<p>Here is the video of the test:</p>
<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/h_yWXkBOys8?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/h_yWXkBOys8?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://www.toniwestbrook.com/archives/267/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Blackberry Programming: Increasing Video Speed Through Prerendering</title>
		<link>http://www.toniwestbrook.com/archives/249</link>
		<comments>http://www.toniwestbrook.com/archives/249#comments</comments>
		<pubDate>Sun, 29 Aug 2010 04:34:54 +0000</pubDate>
		<dc:creator>Toni</dc:creator>
				<category><![CDATA[Blackberry]]></category>
		<category><![CDATA[Games]]></category>

		<guid isPermaLink="false">http://www.toniwestbrook.com/?p=249</guid>
		<description><![CDATA[A Problem of Efficiency As I finishing up the full version of Galactic Blast (screenshots on this soon, its a fully fleshed out game inspired by the demo, to be released on App World) &#8211; I ran into an issue in a strange area. The animation was smooth throughout the game, except oddly enough, on [...]]]></description>
			<content:encoded><![CDATA[<p><b> A Problem of Efficiency </b></p>
<p>As I finishing up the full version of Galactic Blast (screenshots on this soon, its a fully fleshed out game inspired by the demo, to be released on App World) &#8211; I ran into an issue in a strange area.  The animation was smooth throughout the game, except oddly enough, on the instructions screen.</p>
<p>The instructions screen in Galactic Blast includes some text describing the storyline, some text describing the keyboard controls, bitmaps showing each of the enemies and power ups with description text, and some credits at the end.  Since there&#8217;s much more than can fit on a single screen, the user can scroll up and down &#8211; nothing fancy, just your basic instructions screen.  However, the scrolling was anything but smooth.  As I debugged more, I found out that redrawing all the bitmaps and text at each scroll was simply taking too long &#8211; all the function and helper calls involved in rendering everything was just too much for the processor.  </p>
<p><b> The Solution</b></p>
<p>As I thought more about it, I realized that it would be much better to simply render one item instead of 20-30 items each time.  And since instructions are static in nature (they don&#8217;t change or animate), it was a prime candidate for prerendering all the text and bitmaps to a single, big bitmap.  However, I wanted the program to prerender the items automatically at runtime &#8211; I didn&#8217;t want to have to create the bitmap manually (which would be a huge pain anytime I needed to edit something &#8211; like adding a new line of text in).  The code below achieves this by creating a bitmap in memory and rendering all the desired text/images to it at the start of the program, and then simply displays (and scrolls) this bitmap on the instructions screen.</p>
<p><b> The Code </b></p>
<p>I&#8217;ve removed the specific text, bitmaps, and positioning from the code to make things a little clearer:</p>
<div style="font-size:10px">
<pre class="brush: java">

// _instructionsBM is the large bitmap we will be rendering all our text
// and images to.  This is the bitmap we will actually
// display on the instructions screen, thereby increasing efficiency
// since we&#039;re only redrawing one bitmap each time the
// player scrolls instead of a bunch of bitmaps.
private static Bitmap _instructionsBM;

   public static void prerenderInstructions() {
      Graphics tempGraphics;
      String objectiveString;
      Bitmap tempBitmap;
      Object castArray[][];     

      // Populate a string with the objective of the game
      objectiveString = &quot;Text describing the objective of the game  &quot;;

      // Populate an array with the enemy bitmaps, their names,
      // and how many points they are
      castArray = new Object[2][];
      castArray[0] = new Object[] { enemyBitmap1, &quot;Enemy 1&quot;, &quot;50 Points&quot; };
      castArray[1] = new Object[] { enemyBitmap2, &quot;Enemy 2&quot;, &quot;75 Points&quot; };

        // Initialize the bitmap, and then give it an alpha channel for
        // transparency, allowing the background to show through
        // behind the text and bitmaps
       _instructionsBM = new Bitmap(Bitmap.ROWWISE_16BIT_COLOR, WIDTH, HEIGHT);
       _instructionsBM.createAlpha(Bitmap.ALPHA_BITDEPTH_8BPP); 

        // Start with a blank, completely transparent image
      _instructionsBM.setARGB(new int[_instructionsBM.getWidth()*_instructionsBM.getHeight()], 0,
                                             _instructionsBM.getWidth(), 0, 0,
                                             _instructionsBM.getWidth(), _instructionsBM.getHeight());

      // The Graphics object acts a surface that drawing operations
      // can be performed on.  By calling the Graphics constructor
      // with the bitmap as an argument, all drawing operations
      // will be performed upon the bitmap itself.
      tempGraphics = new Graphics(_instructionsBM);

      // All operations to follow will be fully opaque (so pixels not
      //acted upon will stay transparent, while any text/images drawn
      // will be solid.
      tempGraphics.setGlobalAlpha(255);

      // Draw the text onto the bitmap
      tempGraphics.setColor(Color.YELLOW);
      tempGraphics.drawText(objectiveString, 5, 5);    

      // Draw enemy bitmaps onto the bitmap
      for (int lcv = 0 ; lcv &lt; castArray.length ; lcv++) {
         tempBitmap = (Bitmap) castArray[lcv][0];
         tempGraphics.drawBitmap(Utils.getDimension(5, 50+lcv*50,
                                                tempBitmap.getWidth(), tempBitmap.getHeight(), tempBitmap, 0, 0);
         tempGraphics.drawText((String) castArray[lcv][1], 100, 50+lcv*50);
         tempGraphics.drawText((String) castArray[lcv][1], 200, 50+lcv*50);
      }
   }
</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.toniwestbrook.com/archives/249/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Blackberry Programming: Alter Bitmap Color on the Fly</title>
		<link>http://www.toniwestbrook.com/archives/169</link>
		<comments>http://www.toniwestbrook.com/archives/169#comments</comments>
		<pubDate>Sun, 21 Feb 2010 21:25:04 +0000</pubDate>
		<dc:creator>Toni</dc:creator>
				<category><![CDATA[Blackberry]]></category>
		<category><![CDATA[Games]]></category>

		<guid isPermaLink="false">http://www.toniwestbrook.com/archives/169</guid>
		<description><![CDATA[While working on my current Blackberry game, I ran into a situation where I needed to change the color of of a bitmap. Specifically, I wanted to signify an object was &#8220;hit&#8221; by temporarily tinting it red &#8211; i.e. I wanted to keep the original bitmap color pattern, but wanted to increase the red portion [...]]]></description>
			<content:encoded><![CDATA[<p>While working on my current Blackberry game, I ran into a situation where I needed to change the color of of a bitmap.  Specifically, I wanted to signify an object was &#8220;hit&#8221; by temporarily tinting it red &#8211; i.e. I wanted to keep the original bitmap color pattern, but wanted to increase the red portion of all the pixels so it had a red shade to it.  </p>
<table style="width:100%;padding-bottom:30px">
<tr>
<td colspan=2 align=center>Example</td>
</tr>
<tr>
<td align=center><a href='http://www.toniwestbrook.com/wp-content/uploads/2010/02/fighter.jpg' title='Fighter - Before'><img src='http://www.toniwestbrook.com/wp-content/uploads/2010/02/fighter.jpg' alt='Fighter - Before' /></a><br />Before</td>
<td align=center><a href='http://www.toniwestbrook.com/wp-content/uploads/2010/02/fighterred.jpg' title='Fighter - After'><img src='http://www.toniwestbrook.com/wp-content/uploads/2010/02/fighterred.jpg' alt='Fighter - After' /></a></a><br />After</td>
</tr>
</table>
<p><b> ARGB Methods </b></p>
<p>Off the bat, I couldn&#8217;t find any method of directly altering the bitmap color using built in routines.  There are a few routines for altering the alpha channel of bitmaps, but nothing for the color channels.  After sifting through all the members of the Bitmap class, I came across the <a href="http://www.blackberry.com/developers/docs/4.0.2api/net/rim/device/api/system/Bitmap.html#getARGB%28int[],%20int,%20int,%20int,%20int,%20int,%20int%29">getARGB</a> method (see link for details).  This method will populate an int array with argb data, e.g. an int (4 bytes) per pixel signifying the alpha, red, green, and blue values (each value stored per byte).  And sure enough, there is a <a href="http://www.blackberry.com/developers/docs/4.0.2api/net/rim/device/api/system/Bitmap.html#setARGB%28int[],%20int,%20int,%20int,%20int,%20int,%20int%29">setARGB</a> method as well, for taking such an int array and applying it to a bitmap object.  </p>
<p><b> The Strategy </b></p>
<p>With these methods at our disposal, it now becomes a matter of populating an array with ARGB data, then altering each int in the manner desired to achieve a specific effect. In this case, increasing the value of the RED byte (2nd byte) to increase the red tint of each pixel.  However, the sky is the limit, as you could alter transparency for each pixel (alpha byte) and create a disintegration effect, average and equalize each of the color bytes to create greyscale, invert the colors, dim/brighten, etc.  However, for now, lets stick to adding a red tint.</p>
<p><b> The Code </b></p>
<div style="font-size:10px">
<pre class="brush: java">
 public static Bitmap generateHitBitmap(Bitmap passBitmap) {
      Bitmap retBitmap;  // Altered, tinted bitmap being returned
      int[] argbData; // Array holding the ARGB data
      int redData;  // The red value of a pixel

      // Create a new, empty bitmap with the same dimensions
      retBitmap = new Bitmap(passBitmap.getType(), passBitmap.getWidth(), passBitmap.getHeight());

      // Prepare the ARGB array
      argbData = new int[passBitmap.getWidth() * passBitmap.getHeight()];

      // Grab the ARGB data
      passBitmap.getARGB(argbData, 0, passBitmap.getWidth(), 0, 0, passBitmap.getWidth(), passBitmap.getHeight());

      // Loop through each pixel in the array
      for (int lcv = 0 ; lcv &lt; argbData.length ; lcv++) {
         // Get the red data by masking out the 2nd byte
         redData = (argbData[lcv] &amp; 0x00FF0000) &gt;&gt; 16;

         // Increase the red value by 80 (maximum of 255)
         redData += 80;
         if (redData &gt; 255) redData = 255;

         // Shift it back to the right place, and set it back into array
         redData = redData &lt;&lt; 16;
         argbData[lcv] = (argbData[lcv] &amp; 0xFF00FFFF) + redData;
      }

      //  Set the return Bitmap to use this altered ARGB array
      retBitmap.setARGB(argbData, 0, passBitmap.getWidth(), 0, 0, passBitmap.getWidth(), passBitmap.getHeight());

      return retBitmap;
   }
</pre>
</div>
<p>Note: There is some bitwise math going on here, and a few ways to accomplish this.  I like to isolate out the value first and work with it separately, but you may feel more comfortable working directly with the array &#8211; either works.  </p>
<p>Please feel free to share any cool effects you&#8217;ve achieved altering the ARGB data, or even constructing completely new ARGB data on the fly &#8211; I would love to see programmatically generated bitmaps! </p>
]]></content:encoded>
			<wfw:commentRss>http://www.toniwestbrook.com/archives/169/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A Quick Kudos to Blender</title>
		<link>http://www.toniwestbrook.com/archives/162</link>
		<comments>http://www.toniwestbrook.com/archives/162#comments</comments>
		<pubDate>Fri, 07 Aug 2009 00:59:20 +0000</pubDate>
		<dc:creator>Toni</dc:creator>
				<category><![CDATA[Games]]></category>

		<guid isPermaLink="false">http://www.toniwestbrook.com/archives/162</guid>
		<description><![CDATA[As I mentioned in a previous post, I&#8217;m currently developing another Blackberry game, one I hope that turns out fun enough that people will want to play. As with most games, it requires graphics &#8211; which has actually always been somewhat of a road block for me. I don&#8217;t have many acquaintances that are able [...]]]></description>
			<content:encoded><![CDATA[<p>As I mentioned in a previous post, I&#8217;m currently developing another Blackberry game, one I hope that turns out fun enough that people will want to play.  As with most games, it requires graphics &#8211; which has actually always been somewhat of a road block for me.  I don&#8217;t have many acquaintances that are able / have time / are interested in doing the artwork for a game, especially one that isn&#8217;t going to make much, if any, money.  I myself love art, but I&#8217;m not very good at it.  That leaves the options of buying stock art for obscene amounts of money (due to rights to use it commercially &#8211; I try to always play by the book), or finding royalty free art &#8211; which is usually difficult and I can never find exactly what I&#8217;m looking for.</p>
<p>3D packages are a good middle ground for me.  Granted &#8211; it takes a boatload of talent and experience to get professional looking results, but you can get respectable art with a little practice.  Most 3D packages are fairly expensive, which can again be a roadblock &#8211; but this is where Blender comes in.  Blender is an open source 3D rendering application available for pretty much all platforms.  I&#8217;ve heard the learning curve is a little steeper with Blender than with other packages like 3DS (I&#8217;ve only used 3DS once so I don&#8217;t quite remember), but after you use it for a week or so, you get into the rhythm and it&#8217;s not bad at all &#8211; and then from there you start learning cool tricks for lighting and textures, and things look better and better.  </p>
<p>Below are a few objects that may appear in the game in one form or another.  They&#8217;re not great by any means, especially compared to what Blender pros have put out (Check out the <a href="http://www.blender.org/features-gallery/gallery/art-gallery/">cream of the crop</a> from the Blender site), but it&#8217;s not bad for a day or twos work, and after getting shrunk down for a mobile platform, is acceptable.</p>
<p><a href='http://www.toniwestbrook.com/wp-content/uploads/2009/08/sr13-2.jpg' title='SR-13'><img src='http://www.toniwestbrook.com/wp-content/uploads/2009/08/sr13-2.jpg' alt='SR-13' style="width:75%"/></a></p>
<p><a href='http://www.toniwestbrook.com/wp-content/uploads/2009/08/drone.jpg' title='Enemy Drone'><img src='http://www.toniwestbrook.com/wp-content/uploads/2009/08/drone.jpg' alt='Enemy Drone' style="width:75%" /></a></p>
<p><a href='http://www.toniwestbrook.com/wp-content/uploads/2009/08/tetronmine.jpg' title='Tetron Mine'><img src='http://www.toniwestbrook.com/wp-content/uploads/2009/08/tetronmine.jpg' alt='Tetron Mine' style="width:75%" /></a></p>
<p>And, Blender is just fun to play around with &#8211; especially when you start getting into animations.  So if you get a chance, definitely check it out, for fun &#8211; or for your next project.  </p>
<p><a href="http://www.blender.org">Blender Website</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.toniwestbrook.com/archives/162/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using Excel to Create Your Game&#8217;s Binary Data Files</title>
		<link>http://www.toniwestbrook.com/archives/160</link>
		<comments>http://www.toniwestbrook.com/archives/160#comments</comments>
		<pubDate>Sat, 01 Aug 2009 02:01:32 +0000</pubDate>
		<dc:creator>Toni</dc:creator>
				<category><![CDATA[Games]]></category>

		<guid isPermaLink="false">http://www.toniwestbrook.com/archives/160</guid>
		<description><![CDATA[I don&#8217;t think I&#8217;ve mentioned it here yet, but I&#8217;m currently in the middle of developing a new Blackberry game that I hope to have on App World when I&#8217;m complete (as I get closer to completion I&#8217;ll put some screen shots up). I&#8217;ve always wanted to put an application or game up on one [...]]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t think I&#8217;ve mentioned it here yet, but I&#8217;m currently in the middle of developing a new Blackberry game that I hope to have on App World when I&#8217;m complete (as I get closer to completion I&#8217;ll put some screen shots up).  I&#8217;ve always wanted to put an application or game up on one of the mobile stores, not so much to make any significant amount of money (which I won&#8217;t), but just to get the program into more people&#8217;s hands easily.  We&#8217;ll see how it goes &#8211; but until then, onto the point of this article.</p>
<p>One of the things I ran into on this game (and others) is the need to generate binary files &#8211; specifically in this case, level data that dictates where and when objects are in the game, their effects, behaviors, etc.  While there is always the option to create a text file to hold this data, this can be problematic in many ways.  First, the data you need to store may actually be binary data that doesn&#8217;t lend itself to text conversion &#8211; also, more handling to read the file (encoding, line feeds, parsing), larger files (which is a concern on devices with little storage like older Blackberrys), and no obfuscation to the end user (which kind of takes the fun out of the game if they can open up this file easily and read where everything is).  Binary files are definitely the way to go.  And while sometimes it makes sense to make a level editor that will generate the binary files, in some instances you may not have the time or resources to accomplish this.  It would be nice to have a tool to generate these files so you don&#8217;t have to go hexediting for hours to make a 1K file.  </p>
<p><b> Excel at Creating These Files! </b></p>
<p>I find Microsoft Excel to be an extremely useful tool in so many situations, especially those where I need to bang out results quickly.  Past the normal math, accounting, and analysis capabilities, Excel is awesome for generating files that depend on working with lots of imported data, such as script files and, in our case, binary data files.  </p>
<p>In my example, each object had 7 values associated with it.  And with some of these values being 2 bytes in size, this came out to 12 or so bytes I would have to enter hex code in with an editor, per object. If I wanted 500 objects, thats 6K of writing hex values.  No thanks.  It would be much easier to write these values into Excel cells (even auto-generating many of them using Fill-Down with an equation).  Then, using VBA (Visual Basic for Applications) that&#8217;s built into Excel, dump the contents of the cells out into the binary format I want them in.  So let&#8217;s see how to do that.</p>
<p><b> Settings Up Your Sheet </b></p>
<p>This is the simple part.  For this example, I have created a fictional game called &#8220;Just Desserts&#8221; in which each level consists of a screen filled with desserts and vegetables, and you must eat the various cakes, pies, and puddings but avoid carrots and celery.  Our data file that describes each level has 4 values per entry. </p>
<p>Value 1: What level this food is on<br />
Value 2: The ID of this food (E.g. 1=cake, 2=pie, 3=pudding, 4=celery, 5=carrot)<br />
Value 3: X coordinate on screen of this food<br />
Value 4: Y coordinate on the screen of this food</p>
<p>Here&#8217;s what an example spreadsheet would look like:</p>
<p><a href='http://www.toniwestbrook.com/wp-content/uploads/2009/07/excel.jpg' title='Excel Data'><img src='http://www.toniwestbrook.com/wp-content/uploads/2009/07/excel.jpg' alt='Excel Data' /></a></p>
<p>So each row is an object, and each column is one of the values.  In our example above, we see on level one we should create a cake at coords (25,70), a pie at (50,20) and another at (10,10), and a celery at (400, 400).  On level 2, we should create a cake at coords (250, 30), a pudding at (20,160), and a celery at (70,90).  You can manually enter your data in, or use the power of excel and generate the data using a formula &#8211; it&#8217;s up to you.  Once your data is in your spreadsheet, then comes time to turn it into a binary file that can be used by your game.</p>
<p><b> Macro Time </b></p>
<p>The power of Excel is increased 10-fold by the ability to include programs in your spreadsheets.  Excel uses Visual Basic to accomplish this.  By creating a new macro, you can attach a Visual Basic function to it that gets called whenever your macro is.  In Excel 2007, Macros are under the View tab.  After you create a new one, you are presented with a code editor where you can write your VB function.</p>
<p>Below is the example VB function that would work with the above data and pump it out into a file.  Please note &#8211; one thing you may run into depending on what language you&#8217;re working with, and what architecture, is a little/big endian conflict.  VBA pumps out little-endian, but since I was creating a BB game in Java, it expects big endian.  I included how to do this inline below, though you could make a function out of it as well.</p>
<pre lang="vb">
Sub GenDatFile()

   Dim TempByte as Byte ' Holds 1 byte
   Dim TempInt as Integer ' Holds 2 bytes

   ' Specify the path and filename of the binary file.  You could turn this into an input to specify it at runtime as well.
   Open "C:\temp\objects.dat" For Binary Access Write As #1 ' Open it for binary writing with the handle #1

   CurrentRow = 1

   ' Keep reading the spreadsheet until we come to a blank row, then we're done
   Do While Not IsEmpty(Worksheets(1).Cells(CurrentRow, 1))
      'Level of object
      TempByte = Worksheets(1).Cells(CurrentRow, 1) ' Get the value from the first cell in the current row
      Put 1, , TempByte ' Write that byte to the data file (handle #1)

      'ID of object
      TempByte = Worksheets(1).Cells(CurrentRow, 2) ' Get the value from the second cell in the current row
      Put 1, , TempByte ' Write that byte to the data file (handle #1)

      'X Coordinate of object - this is a 2 byte value since it can be greater than 255, we need to swap endian
      TempInt = Worksheets(1).Cells(CurrentRow, 3) ' Get the value from the third cell in the current row
      TempByte = TempInt \ 256 ' Integer divide by 256, aka shift right 8 bits and put that into TempByte
      Put 1, , TempByte ' Write that byte to the data file (handle #1)
      TempByte = TempInt AND 255 ' Mask the data to grab the first byte and put that into TempByte
      Put 1, , TempByte ' Write that byte to the data file (handle #1)

      'Y Coordinate of object - this is a 2 byte value since it can be greater than 255, we need to swap endian
      TempInt = Worksheets(1).Cells(CurrentRow, 4) ' Get the value from the fourth cell in the current row
      TempByte = TempInt \ 256 ' Integer divide by 256, aka shift right 8 bits and put that into TempByte
      Put 1, , TempByte ' Write that byte to the data file (handle #1)
      TempByte = TempInt AND 255 ' Mask the data to grab the first byte and put that into TempByte
      Put 1, , TempByte ' Write that byte to the data file (handle #1)

      CurrentRow = CurrentRow + 1 ' Move to the next row in the spreadsheet
   Loop

   Close 1 ' Close the file (handle #1)

End Sub
</pre>
<p>And we&#8217;re done!  A very simple program, with only a tiny bit of magic to flip the bytes when we need to make little endian into big endian.  But a simple program which saves us hours of tedious hex encoding, plus the power of Excel gives us data storage and manipulation that we didn&#8217;t have to take time to manually program ourselves.</p>
<p>Next time you&#8217;re faced with a problem that deals with working with a lot of data, keep Excel (or it&#8217;s open source brethren) in mind &#8211; it can definitely save you a lot of time and headaches.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.toniwestbrook.com/archives/160/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>From Pong to Platformers &#8211; An Introduction to Game Physics &#8211; Part 4</title>
		<link>http://www.toniwestbrook.com/archives/140</link>
		<comments>http://www.toniwestbrook.com/archives/140#comments</comments>
		<pubDate>Sun, 21 Jun 2009 23:24:04 +0000</pubDate>
		<dc:creator>Toni</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Starting Out]]></category>

		<guid isPermaLink="false">http://www.toniwestbrook.com/archives/140</guid>
		<description><![CDATA[Acceleration for Better Goomba Stomping So now we understand positioning an object on a screen, moving the object around using the principles of velocity, and how to handle collisions with walls and other simple objects. While we can do quite a lot with these simple fundamentals, there is one more that is key to modeling [...]]]></description>
			<content:encoded><![CDATA[<p><b> Acceleration for Better Goomba Stomping </b></p>
<p>So now we understand positioning an object on a screen, moving the object around using the principles of velocity, and how to handle collisions with walls and other simple objects.  While we can do quite a lot with these simple fundamentals, there is one more that is key to modeling realistic movement.  We can understand a little how it works by watching how Mario jumps in the Super Mario Bros series.  </p>
<p><a href='http://www.toniwestbrook.com/wp-content/uploads/2009/06/supermario.png' title='Physics - Mario'><img src='http://www.toniwestbrook.com/wp-content/uploads/2009/06/supermario.png' alt='Physics - Mario' /></a><br />
<i> Mario jumps in an arc movement</i></p>
<p>For those who haven&#8217;t played Super Mario Bros, Mario jumps in an arc.  When he begins to jump, the sprite on the screen moves up very quickly, then slows at the top of the arc, then slowly starts moving back down, until he&#8217;s going the same speed as when he started the jump when hitting the ground.  The reason for this movement is due to acceleration.  Specifically, the game is modeling the affects of gravity, gravity being a force that causes acceleration in the downward direction.  </p>
<p>Just as velocity is the rate of change of an object&#8217;s position (e.g. meters per second), acceleration is the rate of change of an object&#8217;s velocity (e.g. meters per second per second).  Gravity is a force that causes constant acceleration in the downward direction.  Because of this, though Mario starts with a velocity that causes him to move in an upward direction, acceleration downward causes this velocity to slowly decrease, then reverse, getting faster in the opposite direction.  </p>
<p>Programatically, we can handle this the same way we do velocity.  In addition to updating position with velocity, we&#8217;ll want to update velocity with acceleration &#8211; so we&#8217;ll need two more variables, AccX and AccY.  During our redraw, we&#8217;ll want to update both velocity and position: (VelX = VelX + AccX) (VelY = VelY + AccY) (X = X + VelX) (Y = Y + VelY).  Acceleration can be used to model many realistic scenarios besides jumping in platform adventures, such engines firing in a spaceship simulator, or shells being fired from a cannon in a tank war game.  </p>
<p><b> Onto More Advanced Topics </b></p>
<p>We&#8217;ve covered position, velocity, acceleration, and basic collisions &#8211; with these basic techniques, a wide range of realistic motions can be accomplished when making your next game.  There are, however, hundreds of more topics, including friction, complex collisions, fluid dynamics, light oriented (shading, diffraction, reflection), etc.  However, before getting too crazy, try some of these techniques in simple games to get familiar with Newtonian Mechanics.  After that, more advanced topics will be easier to handle.  Have fun with you physics!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.toniwestbrook.com/archives/140/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>From Pong to Platformers &#8211; An Introduction to Game Physics &#8211; Part 3</title>
		<link>http://www.toniwestbrook.com/archives/139</link>
		<comments>http://www.toniwestbrook.com/archives/139#comments</comments>
		<pubDate>Sun, 21 Jun 2009 23:22:40 +0000</pubDate>
		<dc:creator>Toni</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Starting Out]]></category>

		<guid isPermaLink="false">http://www.toniwestbrook.com/archives/139</guid>
		<description><![CDATA[Thinking Inside the Box However, now that we have movement, we run into an issue. When we think of a classic video game, we think of boundaries, such as the edge of the screen, or floors/walls/ceilings, or other objects. In many games, such as platformers, these boundaries will stop the object from moving. In games [...]]]></description>
			<content:encoded><![CDATA[<p><b> Thinking Inside the Box </b></p>
<p>However, now that we have movement, we run into an issue.  When we think of a classic video game, we think of boundaries, such as the edge of the screen, or floors/walls/ceilings, or other objects.  In many games, such as platformers, these boundaries will stop the object from moving.  In games such as Pong and Breakout/Arkanoid, the boundaries cause the object to bounce.</p>
<p><a href='http://www.toniwestbrook.com/wp-content/uploads/2009/06/breakout.png' title='Physics - Breakout'><img src='http://www.toniwestbrook.com/wp-content/uploads/2009/06/breakout.png' alt='Physics - Breakout'  style="width:75%" /></a><br />
<i> In the classic game Breakout, the ball bounces off the walls, paddle, and bricks.</i></p>
<p>The idea of bouncing is the boundary only reverses one dimension of the ball&#8217;s direction, while the other dimensions remain unaffected.  This is expected behavior that reflects real life, as remember that vectors are treated independently in each dimension.  E.g. if the ball is traveling right and up, and hits the right wall, it should continue to travel up, but it should start traveling left.  The right wall only affects the left-right dimension, it never affects the up-down direction.  If the ball then hits the ceiling traveling left and up, the ceiling will only affect the up-down direction, and now the ball starts traveling left and down.   </p>
<p><a href='http://www.toniwestbrook.com/wp-content/uploads/2009/06/physics-bounce.jpg' title='Physics - Bounce'><img src='http://www.toniwestbrook.com/wp-content/uploads/2009/06/physics-bounce.jpg' alt='Physics - Bounce' style="width:90%"/></a><br />
<i> Each wall only affects the direction in one dimension. </i></p>
<p>Looking back, our program currently has 4 variables.  X (x position), Y (y position), VelX (x velocity), and VelY (y velocity).  When redrawing our screen, in the case of boundaries, we would check to see if the ball has &#8220;hit&#8221; any boundaries &#8211; that is, if the coordinates of the ball (X and Y) reside in the same space as the coordinates of any of the boundaries.  If so, we adjust the velocity accordingly.  E.g. if the ball has an x velocity of 4 (traveling 4 pixels per redraw to the right) and a y velocity of -2 (traveling 2 pixels per redraw downwards), and hits the right wall, the x velocity will be reversed &#8211; that is, multiplied by -1 (VelX = VelX * -1).  So now the x velocity is -4 (traveling 4 pixels per redraw to the left), and we&#8217;ve achieved our bounce. If we apply this boundary check to a movable paddle, we now have pong.  If we apply this boundary check to bricks at the top of the screen, we now have breakout as well!  </p>
<p><a href="http://www.toniwestbrook.com/archives/140">Onto Part 4</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.toniwestbrook.com/archives/139/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>From Pong to Platformers &#8211; An Introduction to Game Physics &#8211; Part 2</title>
		<link>http://www.toniwestbrook.com/archives/138</link>
		<comments>http://www.toniwestbrook.com/archives/138#comments</comments>
		<pubDate>Sun, 21 Jun 2009 23:19:51 +0000</pubDate>
		<dc:creator>Toni</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Starting Out]]></category>

		<guid isPermaLink="false">http://www.toniwestbrook.com/archives/138</guid>
		<description><![CDATA[Velocity Velocity is a fancy word for speed with a particular direction. Going 88 MPH would be speed. Going north at 88MPH would be velocity. But forgetting the direction component for a moment, speed is measured in distanced traveled over time. For example, when we say 88 Miles per Hour, we&#8217;re saying the object is [...]]]></description>
			<content:encoded><![CDATA[<p><b> Velocity </b></p>
<p>Velocity is a fancy word for speed with a particular direction.  Going 88 MPH would be speed.  Going north at 88MPH would be velocity.  But forgetting the direction component for a moment, speed is measured in distanced traveled over time.  For example, when we say 88 Miles per Hour, we&#8217;re saying the object is moving a distance of 88 miles over a period of an hour &#8211; i.e. the object is changing its position by that much in an hour. </p>
<p>Remember, our video game object has position too &#8211; it has its coordinates.  If we introduce velocity into our game, we now give our object the ability to move by the laws of physics.  If we redraw our object once a second, and the object is going 5 pixels right per second, we would be adding 5 to our X coordinate (the value stored in our X variable) every second, then redrawing the object.  If we want it to move faster, we increase the speed, 6 pixels per second, 7 pixels per second. </p>
<p><b> Don&#8217;t Forget the Vector! </b></p>
<p>Vector is another mathematical term for a quantity with a direction involved.  Remember, velocity is speed with a direction, so it is a vector.  There is a helpful property of vectors that allows us to split them up by dimensions &#8211; that is, if something is moving in two dimensions at once (north and west, up and north, south and east and down), we can handle each direction separately.  If something is moving north and west, we can talk about how much it&#8217;s moving in the north direction and how much it&#8217;s moving in the east directly independently.  In our video game case, we can say &#8220;okay, the pong ball is traveling -3 pixels per second in the X direction, and 2 pixels per second in the Y direction).  That means every second we&#8217;re going to subtract 3 from our X variable, and add 2 to our Y variable, then redraw the ball.  The movement of the ball would appear to be going diagonally up and left, as seen here:</p>
<p><a href='http://www.toniwestbrook.com/wp-content/uploads/2009/03/physics-2.jpg' title='Physics - Velocity'><img src='http://www.toniwestbrook.com/wp-content/uploads/2009/03/physics-2.jpg' alt='Physics - Velocity' style="width:50%" /></a><br />
<i>We handled each dimension separately, but the end result was the diagonal movement.</i></p>
<p>Now we can store our X velocity and Y velocity into variables too (for example, velX and velY).  So, every time we redraw the screen, we are going to add velX to X (x = x + velX), and velY to Y (y = y + velY).  So if we have a very large velX, the ball will be moved across the screen very fast from left to right.  If we have a very large negative velY, the ball will be moved down the screen very fast.  And we don&#8217;t need to press the key each time, our velocity will do the work for us through simple addition (or subtraction if we are adding a negative number).   </p>
<p>If we wanted to design a fun experiment, we could assign our arrow keys to change velocity.  Pressing left would subtract one from velocity in the X direction, pressing up would add one to velocity in the y direction, etc.  This would have the effect of making the ball move in a direction more quickly the more you press the arrow in the same direction, or slow down and start moving backwards if you press the arrow in the opposite direction.  Not pressing the arrows would simply keep the ball doing whatever it was doing &#8211; e.g. traveling in whatever direction it was before.  </p>
<p><a href="http://www.toniwestbrook.com/archives/139">Onto Part 3</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.toniwestbrook.com/archives/138/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>From Pong to Platformers &#8211; An Introduction to Game Physics &#8211; Part 1</title>
		<link>http://www.toniwestbrook.com/archives/132</link>
		<comments>http://www.toniwestbrook.com/archives/132#comments</comments>
		<pubDate>Sun, 21 Jun 2009 23:19:17 +0000</pubDate>
		<dc:creator>Toni</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Starting Out]]></category>

		<guid isPermaLink="false">http://www.toniwestbrook.com/archives/132</guid>
		<description><![CDATA[Before we get started, I feel the need to point out that this entry will in no way even begin to approach the territory of being comprehensive in the study of video game physics. This is targeted toward those who have little background in physics and is very much a starter tutorial. In general, the [...]]]></description>
			<content:encoded><![CDATA[<p>Before we get started,  I feel the need to point out that this entry will in no way even begin to approach the territory of being comprehensive in the study of video game physics.  This is targeted toward those who have little background in physics and is very much a starter tutorial.  In general, the better and more realistic the game physics, the closer you&#8217;re getting to actual physics &#8211; and that&#8217;s a lifetime study in itself.  However, there are some basic tips and tricks to know when dealing with intro action and arcade style games.  </p>
<p><b>Newton and his Mechanics</b></p>
<p>While games have gone from simple squares on the screen to 2D sprites to 3D-super-rendered-polygon-ray-traced-blammo-wow objects, the actual science behind their movement on the screen has stayed relatively the same &#8211; mainly because their movement is based on the movement we&#8217;re used to, what we see all around us every day.  We reproduce it in our video games (for the most part) because it&#8217;s natural and makes sense to us.  We&#8217;re mirroring physics!  Specifically Classical (or Newtonian) Mechanics.  We generally don&#8217;t need to take into account relativity or quantum mechanics when making Mario jump from one green pipe to another.</p>
<p>So to understand how the pod in Lunar Lander works, we need to understand how a real lunar lander would work.  But let&#8217;s start out more simply. </p>
<p><b> Mass and Position</b></p>
<p>What is mass?  This is a large, fundamental question that involves inertia, resistance to movement, the amount of force necessary to move the object, etc.  But we don&#8217;t need to get that deep into it.  Mass is physical stuff.  You have mass, a ball has mass, the planet has mass, your dog has mass, Catholic churches have Mass, etc.  (ba-dum-dum). Anything physical has mass.  It doesn&#8217;t start moving for the most part, it stays where it is until something pushes it (in the case of a person, your muscles).  If it&#8217;s already moving, it doesn&#8217;t stop moving unless something stops it (a wall, friction, a large rope, etc). It basically keeps doing whatever it&#8217;s already doing.  </p>
<p>Reproducing an object that sits there and does nothing is very easy to do in a video game.  Simply create a representation of an object, whether it be a colored square (Pong), a bitmap graphic (Mario), or a polygon object (Lara Croft) and put it on the screen.  The actual way to do this is outside this tutorial (Check out <a href="http://www.toniwestbrook.com/archives/69">Creating a Blackberry Game</a> if you&#8217;d like to see how to do it in Java).  Just as in the real world an object has a position, in the video game world, the object will have a position too &#8211; a coordinate on the screen.  In the below example, we use a simple object that is 1 pixel in size for a pong-like game.  </p>
<p><a href='http://www.toniwestbrook.com/wp-content/uploads/2009/03/physics-1.jpg' title='Physics - Object Location'><img src='http://www.toniwestbrook.com/wp-content/uploads/2009/03/physics-1.jpg' alt='Physics - Object Location' style="width:50%"/></a><br />
<i> The green pixel is our pong ball </i></p>
<p>When programming this, we would need to store the dot&#8217;s X coordinate and Y coordinate into variables, in this case, store a 6 in X, and a 2 in Y.  If we wanted to use the arrow keys to move this object, we would simply add or subtract from the coordinates as the appropriate key is pressed (e.g. pressing up -> Add 1 to Y, pressing down -> Subtract 1 from Y, pressing right -> Add 1 to X, pressing left -> Subtract 1 from X).  Then redraw the object in its new location.  Our drawing routine would always just take the values and of the X and Y variables and draw a pixel at those coordinates on the screen.</p>
<p>While this would be enjoyable for 2-3 seconds, it would overall be a fairly boring game.  We would be doing physics&#8217; job in this case, telling the object how to move every step of the way.  We want physics to carry its load.  So let&#8217;s program in another property.</p>
<p><a href="http://www.toniwestbrook.com/archives/138">Onto Part 2</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.toniwestbrook.com/archives/132/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Blackberry Game &#8211; Part 6</title>
		<link>http://www.toniwestbrook.com/archives/75</link>
		<comments>http://www.toniwestbrook.com/archives/75#comments</comments>
		<pubDate>Sun, 04 May 2008 02:51:24 +0000</pubDate>
		<dc:creator>Toni</dc:creator>
				<category><![CDATA[Blackberry]]></category>
		<category><![CDATA[Games]]></category>

		<guid isPermaLink="false">http://www.toniwestbrook.com/archives/75</guid>
		<description><![CDATA[Looking for part 5? Let&#8217;s Hear It! Our game is almost done &#8211; the only part left is the sound (and vibration) processing. This is a fairly simple class as well &#8211; again, most of the low level processing is done already by the Blackberry. However &#8211; you may want to play with the methods [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.toniwestbrook.com/archives/74">Looking for part 5?</a></p>
<p><strong>Let&#8217;s Hear It!</strong></p>
<p>Our game is almost done &#8211; the only part left is the sound (and vibration) processing.  This is a fairly simple class as well &#8211; again, most of the low level processing is done already by the Blackberry.  However &#8211; you may want to play with the methods in this class.  We have functionality for playing a midi file &#8211; and we could also have functionality for playing a wav file as well, but I haven&#8217;t included it.  The reason &#8211; on my 8830, the sound engine (at least the way I was using it), could only seem to mix one sound at a time, and completely stopped the other sound if a second one was played.  There may be specific methods to mix two sounds together that I did not research, or otherwise it&#8217;s a limitation/bug of the 8830.  So, if music was playing, and I then played a wav sound effect, the music would stop.  </p>
<p>I overcame this by using the Alert.startAudio method.  This takes frequency/duration pairs from an array and plays simple sounds with it.  When this method is used, it does indeed mix the audio with the midi playing in the background, so I stuck with it.  It makes for less sophisticated sound effects, but it helps us for now.  </p>
<p>Additionally, I wanted to include vibration in the game, so I included a small method for triggering this off.  Vibration is used for when spaceships explode, either yours or the enemy&#8217;s.  </p>
<p>SND.java</p>
<div style="font-size:10px">
<pre class="brush: java">
package com.synthdreams.GalacticBlast;

import net.rim.device.api.ui.component.Dialog;
import java.io.InputStream;
import java.lang.Class;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import net.rim.device.api.system.Alert;

// Sound engine
class SND {

    Player _musicPlayer; // Java media player

    SND() { }

    // Play a midi file for background music
    void playMusic(String passMusic)
    {
        try
        {
            // Set InputStream to a midi file included as resource, as specified by
            // passMusic
            InputStream in = getClass().getResourceAsStream(&quot;/&quot; + passMusic);            

            // Create a media player with mime type of audio/midi using our inputstream
            _musicPlayer = javax.microedition.media.Manager.createPlayer(in, &quot;audio/midi&quot;);

            // Ready the data and start playing it.  To loop indefinitely, we set loopcount
            // to -1.
            _musicPlayer.realize();
            _musicPlayer.prefetch();
            _musicPlayer.setLoopCount(-1);
            _musicPlayer.start();

        }
        catch (Exception e)
        {
            Dialog.alert(&quot;Error playing music&quot;);
        }
    }

    // Stop playing music
    void stopMusic()
    {
        try
        {
            // Tell player to stop playing
            _musicPlayer.stop();

        }
        catch (Exception e)
        {
            Dialog.alert(&quot;Error stopping music&quot;);
        }

        // Then release the data and close out the player
        _musicPlayer.deallocate();
        _musicPlayer.close();
    }

    // The Playsound method plays a simple combinations of tones to simulate a firing
    // noise.  This was necessary, as due to a bug or limitation of the BlackBerry 8830
    // (the phone I do my testing on), playing a WAV file stopped the midi player and
    // any other sound effects.  Player doesn&#039;t appear to mix properly (if at all).  However,
    // a midi file can be played while using the Alert objects startAudio method which
    // can play a sequence of tones, so this is what we&#039;ve done for now.
    void playSound()
    {
        // A sequence of frequencies and durations (eg 1400hz for 15ms, 1350hz for 15ms, etc)
        short[] fire = {1400, 15, 1350, 15, 1320, 20, 1300, 20, 1250, 25, 1200, 35};

        try
        {
            Alert.startAudio(fire, 100);

        }
        catch (Exception e)
        {
            Dialog.alert(&quot;Error playing sound effect.&quot;);
        }   

    }

    // Activates the phone&#039;s vibration functionality for a specific number of ms
    void vibrate(int passMilli)
    {
        Alert.startVibrate(passMilli);
    }
}
</pre>
</div>
<p>Nothing too complex at all going on here.  You may wonder what all the player initialization methods are doing &#8211; they deal mainly with making sure the sound data is available and buffered before playing.  Just call them in order and you&#8217;re good to go.</p>
<p><strong> That&#8217;s All Folks! </strong></p>
<p>At this point, you have all the basic functionality necessary for making whatever kind of Blackberry game you&#8217;d like.  Your logic may have to be much more complex, and you may have to include additional classes to accommodate everything, but the basic principles stay the same.  Also &#8211; all the classes used here are unsigned and available without a license from Research in Motion, which means you can make, play, and distribute these games for free.  </p>
<p>Feel free to comment if you have any questions, or even suggestions!  These were my own experiences and suggestions with creating a Blackberry game, but you might have your own!  Thanks for checking out this tutorial, good luck &#8211; and most importantly, have fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.toniwestbrook.com/archives/75/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
	</channel>
</rss>
