Category Archives: Development

Creating a Blackberry Game – Part 2

GalacticBlast.java

package com.synthdreams.GalacticBlast;

import net.rim.device.api.ui.UiApplication;

/**
 * Initial main class that starts the ball rolling
 * UiApplication is extended to provide Blackberry
 * functionality, specifically the Event Dispatcher
 * and Screen pusher
 */
public class GalacticBlast extends UiApplication
{
  
    public static void main(String[] args)
    {
        GalacticBlast GalacticBlast = new GalacticBlast();
        
        // The Blackberry's message pump, handles key
        // presses and system events
        GalacticBlast.enterEventDispatcher();
    }
    
    public GalacticBlast()
    {
        // The first thing we do is show the menu screen, defined by the
        // 'Menu' class.  We accomplish this with a call to pushScreen,
        // which puts screens on the stack (Class specified must be a type
        // of screen, such as MainScreen).  The top most screen is the
        // one shown.  Our first one will be the menu, and later the game
        // itself will sit on top of this.  When the game quits, it will
        // pop that screen off the stack and return to the menu screen.
        pushScreen(new Menu());              
    }
} 

Nothing major going on there, simply a place to get started. As we can see, things are immediately handed off to our Menu class, which handles the main menu. It is common functionality to have a main menu where the player can play, save, load, configure, quit, etc.

The Main Menu

Our main menu extends MainScreen, as I wanted just a simple screen with text and buttons, using the built in Blackberry look and feel. However, there is nothing stopping you from using the techniques in the actual gameplay section for displaying more advanced graphics in the menu section. But for this tutorial we have a simple main menu.

The concept behind Blackberry forms is there is a layout manager that occupies a certain amount of screen space, and contains fields that it positions accordingly. You can have multiple layout managers on one screen, each with its own child fields. There are different built in layout managers, and you can make your own custom ones as well. For our main menu, we’ll both use the default built in manager that simply repeats fields in the vertical direction, as well as a custom manager that allows us to specify the exact X,Y coordinates of fields within the layout manager.

Additionally, we’ll be making a special start button that will start the game play by instantiating the Gameplay class and pushing it onto the screen stack (just like our initial class pushed our Menu class onto the screen stack). Also check out our custom fields and field manager that allow us to position fields specifically by X and Y coordinate. Our field manager allows us to specify its height, so we can use it as a simple vertical-space buffer as well.

Menu.java

package com.synthdreams.GalacticBlast;

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;

/**
 * The menu class handles showing the main menu and intercepting when the user quits or 
 * begins the game.  If the user presses the button to begin, the Menu class starts
 * the game going.
 */

class Menu extends MainScreen
{
    GamePlay _game;  // GamePlay handles the action part of the game itself
    int _invokeID; // A handle to our invocation of scanning for when the game ends
    
    // To add functionality to clicking the button, we need to override the button's
    // trackwheelClick method.  Here we define _startButton as a button with
    // text, positioning, and trackwheelClick we want.
    ButtonField _startButton = new ButtonField("Start Game!", ButtonField.FIELD_HCENTER | ButtonField.FIELD_BOTTOM)
    {

       protected boolean trackwheelClick(int status, int time)
       {
          // If the button is pressed, we create a new GamePlay object
          _game = new GamePlay();
          
          // Then we push it onto the screen stack.  This then becomes the
          // active screen.  See GalacticBlast.java for notes about pushing
          // screens onto the stack
          getUiEngine().pushScreen(_game);
          
          // The invokeLater method allows us to continually run a segment of
          // code from outside the GamePlay object.  In this case, we do
          // this to monitor if the gameplay object is active our not.  
          // When the player loses, the object marks itself inactive, at
          // which point we first cancel invoking further, then stop
          // the music from playing, then pop the gameplay screen off
          // the stack so we return to the main menu.
          _invokeID = getApplication().invokeLater(new Runnable()
            {
                public void run()
                {
                    // Check to see if the game is done.
                    if (_game.getActive() == false)
                    {
                        // Cancel invoking this piece of code again (normally is invoked
                        // every 500 ms, as specified below)
                        getApplication().cancelInvokeLater(_invokeID);
                        
                        // Kill the music
                        GamePlay.snd.stopMusic();
                        
                        // Pop the gameplay screen off the stack, which returns
                        // the user to the main menu
                        getUiEngine().popScreen(_game);
                        
                        // Display the final score
                        Dialog.inform("Final Score: " + _game.getScore());
                        
                        // We're done with our game object now
                        _game = null;
                    }
                }
            }
            , 500,true); // rerun this code every 500ms
          
          return true;
       }    
    };   
    
    // Normally LabelFields are arranged in a very plain order depending on the
    // Layout manager.  They'll repeat vertically with the option of left/center/right
    // justifying.  But sometimes it's nice to be able to specificy exactly in X,Y coordinates
    // where you want the field to go.  This class, in conjunction with the Custom Manager
    // defined below, allows for this
    // Additionally, a "customStyle" is defined for the field.  For our cases, this 
    // is either left to 0 for normal X,Y positioning, set to 1 for X set to 1/8th the total
    // width of the screen, or set to 2 for X+fieldwidth set to 7/8th the total width of the screen.
    // 1/8th and 7/8th for the edge of the text allows for columns to be made, for scores,
    // instructions, or anything else.  More custom centering or something more dynamic
    // could be done with this variable, but its fine for our purposes right now.
    class CustomTextField extends LabelField
    {
       int _xPos, _yPos, _customStyle; // coordinates and style
       
       // We pass in the coordinates and the custom style
       CustomTextField(String passLabel, int passStyle, int passX, int passY)
       {
              super(passLabel);
              _xPos = passX;
              _yPos = passY;
              _customStyle = passStyle;
       }    
       
       // Getters for position and style
       int getX() { return _xPos; }
       int getY() { return _yPos; }
       int getCustomStyle() { return _customStyle; }
    }
    
    // Our custom manager is where the magic happens for allowing customtextfields
    // to be placed at any X,Y coordinate.  It reads in the coordinates from the
    // field and places it at those coordinates in the layout.  It will also
    // look at custom layout, and if centered is specified, will ignore the X coordinate
    // and center it at the Y coordinate on the screen.  Additionally, the total height
    // of the manager can be control how much space it takes up regardless of how many
    // fields it contains
    class CustomManager extends Manager
    {
        int _managerHeight; // Total height of the manager
        
        // Pass in desired height.  Scrolling is turned off in both directions.
        public CustomManager(int passHeight)
        {
            super(Manager.NO_HORIZONTAL_SCROLL | Manager.NO_VERTICAL_SCROLL);
            _managerHeight = passHeight;
        }   
        
        // Sublayout is called automatically to position all the internal fields to this
        // layout.  Its sublayouts job to read in the custom coordinates of each of the fields
        // and place them accordingly.
        protected void sublayout(int width, int height) 
        {
            CustomTextField field;
        
            // Loop through all the fields contained with the layout manager
            for (int lcv = 0; lcv < getFieldCount(); lcv++)
            {
                //Get the field.
                field = (CustomTextField)getField(lcv);
            
                //Obtain the custom x and y coordinates for
                //the field and set the position for
                //the field.
                switch (field.getCustomStyle())
                {
                   // Custom style 1 is for the left side of the text to be at 1/8th the width
                   // of the screen
                   case 1:
                        setPositionChild(field, width / 8 , field.getY());
                        break;
                        
                   // Custom style 2 is for the right side of the text to be at 7/8ths the width
                   // of the screen    
                   case 2:
                        setPositionChild(field, width * 7 / 8 - field.getPreferredWidth(), field.getY());    
                        break;
                        
                   // Any other custom style gets position strictly from X,Y
                   default:
                        setPositionChild(field, field.getX(), field.getY());  
                    
                }
                 
                
                 //Layout the field.
                 layoutChild(field, width, height);
            }

            //Set the manager's dimensions
            setExtent(width, _managerHeight);
        }
        
        public int getPreferredWidth()
        {
            return Graphics.getScreenWidth();
        }

        public int getPreferredHeight()
        {
            return Graphics.getScreenHeight();
        }
    }

    // Menu constructor
    public Menu()
    {
        // First, turn off scroll bars for this screen in case we accidentally push past the 
        // edge with our fields/whitespace
        super(NO_VERTICAL_SCROLL);

        // We set the title on the screen
        LabelField title = new LabelField("Galactic Blast Demo", LabelField.FIELD_HCENTER);
        setTitle(title);

        // CustomManagers can also be used just as space buffers.  First we make
        // 20 pixels of space
        getScreen().add(new CustomManager(20));
        
        // Add some text        
        add(new LabelField("Instructions", LabelField.FIELD_HCENTER));
        
        // Create another custom manager, but this one we'll use for more than just
        // spacing, we'll actually position some text fields (our instructions)
        CustomManager instManager = new CustomManager(Graphics.getScreenHeight() - 145);                
        getScreen().add(instManager);       

        // A multi-d array that will store our instruction fields
        CustomTextField instArray[][] = new CustomTextField[3][2];
        
        instArray[0][0]= new CustomTextField("Trackball", 1, 0, 20);
        instArray[1][0] = new CustomTextField("Space", 1, 0, 40);
        instArray[2][0] = new CustomTextField("Escape", 1, 0, 60);
        instArray[0][1] = new CustomTextField("Move Ship", 2, 0, 20);
        instArray[1][1] = new CustomTextField("Fire Cannon", 2, 0, 40);
        instArray[2][1] = new CustomTextField("Quit Game", 2, 0, 60);

        // Loop through our array and add each field to the layout manager with a different
        // font
        for (int lcv = 0 ; lcv < 3 * 2 ; lcv++)
        {
            instArray[lcv%3][lcv/3].setFont(Font.getDefault().derive(Font.PLAIN, 16));
            instManager.add(instArray[lcv%3][lcv/3]);
        }

        // add our button that has the click method overridden
        add(_startButton);
        
        // Add a buffer of 10 pixels
        getScreen().add(new CustomManager(10));   
        
        // More text
        LabelField copyrightText = new LabelField("Copyright 2008 Synthetic Dreams", LabelField.FIELD_HCENTER);        
        copyrightText.setFont(Font.getDefault().derive(Font.ITALIC, 14));
        add(copyrightText);
       
    }
        
} 

At this point, your program should be able to load with a menu screen (well, you’ll have to comment out any mentions of other undefined classes). You should see something like this:

Only with your own text, of course. Now onto Part 3…

Creating a Blackberry Game – Part 1

Introduction

I’ve used a number of cell phones, and without a doubt RIM’s Blackberry continues to be my favorite by far. Blackberry users will know what I’m talking about – it’s just a fantastic communications device. One of its few shortcomings, though, is its lack of a large game library. Historically, the Blackberry has been targeted at the business market, and its software reflects that. However, more and more of these fantastic cell phones have wound up in the hands of the average consumer, and with good reason. And with that happening, the need for some good, fun games increases. This is where you come in!

The first thing that happens to me whenever I get a new device, after playing around with it of course, is wanting to program it. It’s just the engineer in me popping out. I’ve made a number of Blackberry applications since I first got my 8830, but I wanted to tackle making a game. There are a few resources on the web, but some are targeted at java devices in general, and others are slightly old, so I wanted to put together a good tutorial about creating a Blackberry game for modern devices from start to finish.

This series of tutorials will document creating a simple space fighter game. A completed example of such a game is available on the Synthetic Dreams website, called “Galactic Blast”. The Galactic Blast Demo is a simple example of how easy it is to create a Blackberry game. With the source code documented here, you can go and create your own game, making it as complex as you want. While Galactic Blast is a space fighter, the principle is the same creating any style, from RPG to platform adventure. All development work will be done in Java, and this tutorial assumes you are familiar with this language. Some quick screenshots from the demo:

Getting Started

While strictly speaking it isn’t necessary to own a Blackberry to do Blackberry development, it definitely helps. While the RIM development tools come with a Blackberry emulator that is pretty spot on to the real thing, there are a few areas where the emulator differs (which will be mentioned as we go), and it’s nice to test it out on a real Blackberry. You definitely will need a compiler and IDE. While there are plugins for Visual Studio, they are limited and not as robust as the full Blackberry Java Development Environment provided by RIM. The Blackberry JDE can be obtained for free from RIM here: http://na.blackberry.com/eng/developers/downloads/jde.jsp.

At the time of this entry, JDE 4.3.0 was used. This download will come with the JDE as well as a device simulator, and tools to simulate being connected to a wireless network on the simulator. The IDE is fairly nice as well, with some intellisense type method/property/class tips.

jde1.jpg

Setting up the Project

After starting up the JDE, you’ll want to create a new workspace/project. Name it whatever you’d like. After your project is open, there are a few things you can set immediately. Right click on the project name in the workspace window, and select “Properties”. In the General tab, you can set information such as Title, Version, Vendor, and Description. This will appear when the user downloads your application, as well as the title of the icon on the Blackberry itself.

Right clicking on the project in the workspace window will also allow you to add existing items (such as png/jpegs/midis) to your project or create new ones (java source). For this project, we make use of 6 source files, though only 4 of them contain anything major.

Note – when you’re compiling and running your program, by default it will run on the emulator. When you want to upload it to your Blackberry to test (without going through the hassle of using the Desktop Manager or OTA downloads), the JDE includes a handy utility called the “javaloader” located in the bin directory. There are a number of tasks it can perform, but one of the most useful is simply copying an executable to an actual device. If your device is connected to your computer via USB, use the “-u” option, and then supply the cod file of the program you wish to upload. E.g. “javaloader -u C:\projects\MyProj1\MyProj1.cod”.

Now that you have your project set up, you’re ready to start the actual programming. See you in part 2…

Creating a PHP Graphing Calculator

When I want to learn a new technology or technique, I like to think about little projects I’ve always wanted to try, and see if the project could be implemented using the new technology.

In this case, I’ve worked quite a bit with .NET’s image and graphic related classes and methods, but had never really investigated the PHP equivalent. After reading up on PHP’s GD library, I decided to give writing a simple graphing calculator a go.

This tutorial will get you started and allow your users to enter in equations to generate graphs like this:

Graph 1

Graph 2

It will also let users use standard PHP functions and code, giving them use of the full math library, modulus, random functions, etc. You can do some really neat things like this:

Graph 3

So let’s get started. In this example, the webpage has a single text box that takes an equation, submits back to the page, and the PHP writes an image directly to the browser. Please note, this example doesn’t do any error checking or sanitation of input – please include it in your final code, especially since this page makes use of the “eval” function which is a huge security risk.


< ? php
if ($_POST['tempBox'] != '')
{
   // width, height, and scale of graph.  These could also be user defined values.
   $GLOBALS['width'] = 500;
   $GLOBALS['height'] = 500;
   $GLOBALS['scale'] = 1;


   // drawGrid draws X and Y axis with markers every 50 points
   // We pass in the image resource to draw to
   function drawGrid($passGraphic)
   {
      // Grid is grey
      $gridColor = imagecolorallocate($passGraphic, 200, 200, 200);

      // Draw two lines, one vertical in the middle of the grid (width/2)
      // and another horizontal in the middle of the grid (height/2)
      imageline($passGraphic, $GLOBALS['width']/2, 0, $GLOBALS['width']/2, $GLOBALS['height'], $gridColor);
      imageline($passGraphic, 0, $GLOBALS['height']/2, $GLOBALS['width'], $GLOBALS['height']/2, $gridColor);
      
      // Draw a marker ever 50 points on the X axis.  We do this by starting at the center
      // of the board, then incrementing 50 with every iteration.  We also
      // draw a mark in the mirror location to cover the negative side of the axis
      for ($lcv = 0 ; $lcv < $GLOBALS['width'] / 2 / $GLOBALS['scale']; $lcv += 50)
      {
           // Set tempX and tempY to the current marker location
           $tempX = $lcv;
           $tempY = 0;
  
           // Convert to image coordinates
           cartToPixels($tempX, $tempY);

           // Draw the line
           imageline($passGraphic, $tempX, $tempY - 10, $tempX, $tempY + 10, $gridColor); 

           // Now do the same for the negative side of the axis
           $tempX = $lcv * -1;
           $tempY = 0;
           cartToPixels($tempX, $tempY);
           imageline($passGraphic, $tempX, $tempY - 10, $tempX, $tempY + 10, $gridColor); 
      } 

      // We use the same method for drawing markers on the Y axis.
      for ($lcv = 0 ; $lcv < $GLOBALS['height'] / 2 / $GLOBALS['scale'] ; $lcv += 50)
      {
           $tempX = 0;
           $tempY = $lcv;
           cartToPixels($tempX, $tempY);
           imageline($passGraphic, $tempX - 10, $tempY, $tempX + 10, $tempY, $gridColor); 
           $tempX = 0;
           $tempY = $lcv * -1;
           cartToPixels($tempX, $tempY);
           imageline($passGraphic, $tempX - 10, $tempY, $tempX + 10, $tempY, $gridColor);
      } 


   }

   // cartToPixels converts Cartesian coordinates to image coordinates, using the SCALE variable to
   // do a zoom conversion between the two.  
   // The two gotchas are, coordinates start from the center, and the Y axis goes in the
   // opposite direction (image coordinates, increase in Y goes down.  Cartesian, increase
   // in Y goes up).
   function cartToPixels(&$passX, &$passY)
   {
      // Start from the middle, otherwise 1 to 1 for X
      $passX = $GLOBALS['width'] / 2 + $passX * $GLOBALS['scale'];

      // Start from the middle, also subtract to flip for Y
      $passY = $GLOBALS['height'] / 2 - $passY * $GLOBALS['scale'];

   }

   // pixelsToCart converts from image coordinates to
   // Cartesian coordinates.  Uses the same process as
   // above but reversed.
   function pixelsToCart(&$passX, &$passY)
   {
      $passX = ($passX - $GLOBALS['width'] / 2) / $GLOBALS['scale'];
      $passY = ($passY + $GLOBALS['height'] / 2) / $GLOBALS['scale'];
   }

   // The plot function simply takes Cartesian coordinates and 
   // plots a dot on the screen
   function plot($passGraphic, $passCartX, $passCartY)
   {
      // We use green for our graphs
      $plotColor = imagecolorallocate($passGraphic, 0, 255, 0);

      // Convert Cartesian coordinates to image coordinates
      cartToPixels($passCartX, $passCartY);

      // Then draw a dot there
      imagesetpixel($passGraphic, $passCartX, $passCartY, $plotColor);
   }

   // Push out an image/png mime type to the browser so it knows
   // a PNG image is coming and not HTML
   header ("Content-type: image/png");

   // Create a new image resource with the dimensions dictated
   // by our width and height globals.  Starts off with a black
   // background automatically.
   $im = @imagecreatetruecolor($GLOBALS['width'], $GLOBALS['height'])
      or die("Cannot Initialize new GD image stream");
  
   // Draw the grid on our graph first (under everything) 
   drawGrid($im);

   // We start a loop from 0 (First pixel in width of graph) to the width end,
   // converting image X coordinate to Cartesian X coordinate, then retrieving
   // the corresponding Y Cartesian coordinate (remember, our equations are
   // in 'y =' form.  We multiply it by 50 to give a better resolution - e.g. multiple dots on
   // the Y axis for each X.  This gives us a solid line instead of a bunch of dots for steep
   // functions.  The higher the number, the smoother the line (and the slower the program)
   for ($lcv = 0 ; $lcv < $GLOBALS['width'] * 50 / $GLOBALS['scale'] ; $lcv++)
   {
      // Get the left most point on the graph in Cartesian coordinates
      $tempX = 0;
      $tempY = 0;
      pixelsToCart($tempX, $tempY);
    
      // Now get the current Cartesian X coordinate by adding our current loop 
      // value divided by 50
      $tempX += $lcv/50;
 
      // Here's where the magic happens.  In a nutshell, we're setting the Y coordinate
      // ($tempY) in relation to the current X coordinate ($tempX)
      // by using the expression specified by the user.  We use PHP's eval function,
      // which allows us to take a string (the user's input box) and run it as if it
      // were PHP code.  We're also converting X to $tempX because that's the actual
      // name of our X variable in our code, not just
      // 'X' - but we don't want the user to have to type '$tempX', so we make it easy for
      // them.  This is the line of code to be especially careful of, as a user could insert 
      // malicious PHP code and do bad things.  
      @eval("\$tempY = " . str_replace('X', '$tempX', $_POST['tempBox']) . ";");

       // Now that we have both coordinates, we plot it!
      plot($im, $tempX, $tempY); 
   }

   // We write the equation on the graph in red
   $textColor = imagecolorallocate($im, 255, 0, 0);

   // Now write the equation on the graph
   imagestring($im, 4, 10, $GLOBALS['height'] - 25, 'y = ' . $_POST['tempBox'], $textColor);

   // Output a PNG file now that it's all built
   imagepng($im);

   // Free up the resource
   imagedestroy($im);
}
else
{
? >

<html>
   <body>
      
      <div style="margin-bottom:20px; font-weight:bold; font-size:16px">Simple Grapher</div>

      <form id="graphForm" action="?< ? php echo rand(); ? >" method="post">
         Enter expression: y = <input type="input" id="tempBox" name="tempBox"> <input type="submit" value="Graph!">
      </form>

      <div style="margin-bottom:15px">Enter expression using variable X (PHP code accepted).  Both axes in range of -250 to 250.</div>
      <div>Examples:
         <ul>
            <li><a href="javascript:populate('cos(X / 30) * 50')">cos(X / 30) * 50</a></li>
            <li><a href="javascript:populate('pow(X / 30, 3) - X')">pow(X / 30, 3) - X</a></li>
            <li><a href="javascript:populate('pow(X, 2) / 15 - 200')">pow(X, 2) / 15 - 200</a></li>
            <li><a href="javascript:populate('2000 / X')">2000 / X</a></li>
            <li><a href="javascript:populate('tan(X/ 25) * 20')">tan(X/ 25) * 20</a></li>
            <li><a href="javascript:populate('-3 * X + 50')">-3 * X + 50</a></li>
            <li><a href="javascript:populate('rand() % X')">rand() % X</a></li>
            <li><a href="javascript:populate('pow(X,2) % X - X')">pow(X,2) % X - X</a></li>
            <li><a href="javascript:populate('pow(X,2) % X - cos(X/20) * 40')">pow(X,2) % X - cos(X/20) * 40 (favorite)</a></li>
         </ul>
      </div>
   </body>
</html>

< script type="text/javascript">

   function populate(passExpression)
   {
      document.getElementById('tempBox').value = passExpression;
      document.getElementById('graphForm').submit();
   }

< /script>

< ? php
}
? >

That’s it – a few things to note: We tack on a random value to the URL (check out the form code in the HTML section) to ensure our browser doesn’t show a cached copy of the image. Since its always using the same filename, the browser would almost certainly show old copies unless a refresh was requested or cache was cleared (depending on the browser).

As you might have seen from the code, generating images is very easy in PHP. We can create a new image resource using the imagecreatetruecolor function. This creates a blank resource, we can also create from preexisting images. Once we have an image resource, we can perform basic graphic functions on it like lines, dots, fill, text, etc. Once we’re done, the imagepng function can convert it into actual PNG binary code (in our case we dump it to the browser, but you can specify a filename too to save it to).

It’s definitely fun to play around with the graphic library, you can do a lot of neat things and add some needed graphics to normally text-only server side output. Have fun!

What Language to Choose, What Compiler to Use?

Whether you’re completely new to programming, or have been out of the game for so long that you’re completely lost, an important first step in becoming a coder is choosing your first language. While it is true that learning the principles behind Computer Science is what is truly important, in practice one needs a way of implementing these important concepts, converting theoretical into reality, and a trusted language is necessary for this. There are thousands of programming languages at the disposal of the modern day programmer, and making a choice of which one to use can be a little daunting. Coupled with this, there is no one language that fits all situations, each language has its own strengths and weaknesses in different areas.

What Platform Will You be Programming For?

The first question to ask is what system are you creating software for? This isn’t simply a question of Windows vs OS X vs Linux. You could be programming console systems like your Playstation 3 or Dreamcast. You could be interested in creating applications for your smart phone, such as a Blackberry or Treo. Or perhaps you want to write a small program to run a microcontroller in a robot you’ve built.

If you are indeed completely new to programming, you may want to start by writing programs for your computer. Programming for unique architectures can often have their own slew of hiccups and peculiarities that will detract from learning core ideas. The goal is to become comfortable with the idea of programming in general, get the general concepts under your belt, then move on to the more advanced stuff as you feel more confident.

Okay, So What Language Do I Choose?

Even after making the decision of starting with your PC as a platform, the choices aren’t over yet. Most languages can be used to create programs on your desktop. The ones we tend to hear a lot about are BASIC/Visual Basic, C/C++/C#, and Java. Once you have chosen a language, you need a program called a “compiler” which converts your code into machine code the computer can understand. Below I’ve posted links to a few popular choices.

BASIC / Visual Basic

BASIC has typically been used as a beginner’s language. It’s easy to learn and quick to implement. However, the same simplicity that makes it a great language to start with also limits its potential as projects get bigger and more complex. In comes Visual Basic (especially modern day VB.NET). It combines the simplicity of BASIC’s syntax with the power of .NET and object oriented programming. While you may not be familiar with these concepts, VB.NET paves the way of making life easy until you’re ready to tackle these advanced topics.

For those looking to start with BASIC, especially one geared toward game development, Dark BASIC (http://darkbasic.thegamecreators.com/) is an excellent choice. Though it is not free, there is a trial version, and the full version is only $39.99 (at the time of this article).

If you’re looking to go with Visual Basic, which is this author’s suggestion, Microsoft currently offers Express editions of all its products, completely for free. The entire product family is incredibly powerful and a very good deal (free!). Check out Visual Basic Express 2008 (http://www.microsoft.com/express/vb).

C / C++ / C#

The C family of languages are definitely less fluffy than Visual Basic. However, this fits their purpose – less of beginner languages, and more powerful as projects get larger and more involved. This is not to say it is impossible or even a bad idea to learn programming using C – there are many concepts central to Computer Science and computer architecture in general that can be demonstrated much more clearly with C than with VB, such as memory management.

C/C++ have been around for a while and are the preferred languages in many different environments – because of which a large number of tools can be found. Again, Microsoft offers Visual Studio Express versions of their C++ compiler. The far most well known compiler, however, is the GNU compiler, which can be found on countless platforms, including UNIX, Linux, OS X, etc. For more information, check it out here (http://gcc.gnu.org/)

C# is a creation of Microsoft and tied much more closely to the .NET framework. While it may be not the perfect choice for a beginner language, it is a great language for both web application work as well as creating applications for Pocket PCs and Windows Mobile powered smart phones. Visual Studio Express also contains a C# module.

Java

Java is another interesting choice – it looks similar to C++ at first glance, but offers something quite different. Java is geared toward true cross platform portability. When you write and compile Java code, it is turned into what’s called “Byte Code” which actually runs on a virtual machine on top of your real machine. What’s neat is that while the real machine underneath can be different, each machine will run the same virtual machine, so the code you write for one platform will theoretically work for another. Java, for this reason, is an excellent choice for client side web applications and mobile applications on cell phones. When I write applications for my Blackberry, I always use Java. Sun offers its official (and free) Java compiler as a part of the Java SDK (JDK) – you can find it here (http://java.sun.com/javase/downloads/index.jsp).

You’re On Your Way

The language you begin with is important – it is your first companion as you explore the sights and wonders that are Computer Science. Don’t be too worried about picking the perfect language though – if you’re fairly comfortable with your choice you’ll be fine, and once you’ve built up some programming skills, you can easily branch out and try new languages, especially ones that might suit your needs in the particular project you’re working on. Good luck!

Rotate, Flip, and Resize Images in .NET

Often times if you’re writing a web application that deals with user uploaded photographs and other images, a nice feature set to have is one that allows users to do basic manipulations on their photos, such as rotating, flipping, and resizing (the last being very important for download friendly images). Luckily, the .NET framework makes such functionality easy to implement.

Read the Image

Once the image has been uploaded and saved into a directory somewhere accessible by the web server, the first step common to all the procedures is to take the image data inside of the file and get it into memory usable by .NET. We do this by loading the image into a System.Drawing.Bitmap object. One of the constructors of Bitmap class can take the filename of an image, thereby automatically decoding the format and reading in the data into the Bitmap object. .NET supports the most common image formats, such as JPEG, GIF, BMP, and PNG.

        Dim PhotoBMP As Bitmap

        PhotoBMP = New Bitmap(“myfile.jpg”)

Above we have statically specified a filename, but you may, of course, dynamically pass in the filename saved on the webserver.

Flips and Rotations

Reorienting the image is incredibly easy. The Bitmap class contains a method called “RotateFlip” that does what you would think – rotates and/or flips. The RotateFlip method takes a single argument, one of RotateFlipType type. Intellisense will enumerate all the options, but each combination of rotation and flip is included: 90, 180, 270 degrees, and flips across X, Y or both axes.

        PhotoBMP.RotateFlip(RotateFlipType.Rotate270FlipNone)

Above we rotate our image clockwise 270 degrees (i.e. counter-clockwise 90 degrees). We do not perform a flip.

        PhotoBMP.RotateFlip(RotateFlipType.RotateNoneFlipY)

Above we flip our image across the Y axis but do not perform a rotation. You may also combine both flips and rotations simultaneously if desired.

Saving (and Converting) the Image

At this point, our reorientation has only been performed upon the bitmap data we have in memory, our file is still untouched. We can save our changes back to the original file, or to a new file if desired. The Bitmap class contains an easy to use Save method.

        PhotoBMP.Save(“myfile.jpg”)

Save is overloaded in a number of ways, but you may also specify a filetype as the second argument. In our example, if we wanted to convert our jpg to a png:

        PhotoBMP.Save(“myfile.png”,ImageFormat.Png)

Very easy as can be seen, no need to lookup file formats and encodings. You may also want to read in the current extension to direct what actions are taken. I use the following regular expression to parse the ending extension of the file.

        Regex.Match(FileName, ".[^.]+$")

Resizing Images

Resizing images is a little more difficult, but not too bad once you know the procedure. You start by loading bitmap data in the same fashion we did for rotating and flipping. Assuming you want to keep the image in proportion when changing the size, as well as resize with a maximum resolution in mind, we’ll need to calculate the aspect ratio of the image and our conversion coefficient. This may sound complicated, but fear not.

Calculate Aspect Ratio

There are a few methods of doing the math, but in general we know the maximum dimension we want. E.g. 1024×768, 800×600, 640×480, etc. We calculate the aspect ratio of our maximum desired size by dividing the width by the height. In these examples it is 1.333.

Then we must calculate the aspect ratio of the current image. We can obtain the width and height of our bitmap with the width and height properties of the Bitmap class. We know if we have a greater aspect ratio than our target max size’s aspect ratio, then our width is larger and is the confining dimension. If our aspect ratio is less, our height is larger and is the confining dimension. Once we know our confining dimension, to get the conversion coefficient, we divide our current image confining dimension size by the target confining dimension size.

E.g. If we’re converting 2048×1800 to a maximum of 1024×768, we calculate our target image aspect ratio, which we already know is 1.333. Then we calculate our original image aspect ratio, which is 1.138. This is less than 1.333, so we know height is our confining dimension. So we divide 1800 by 768 to get our conversion coefficient, or 2.344. Now we can calculate our target width size by dividing our current width by 2.344, which is 874. Our new image will by 874×768.

Confused? It’s not really as bad as it sounds. First you’re figuring out which dimension will match the largest dimension of your target size, then you’re decreasing the other dimension by the same amount. Here it is in code.

        OrigAspectRatio = PhotoBMP.Width / PhotoBMP.Height

        TargetAspectRatio = 1024 / 768

        If OrigAspectRatio < TargetAspectRatio
   	     ‘Height is confining
	     NewHeight = 768
	     NewWidth = PhotoBMP.Width / (PhotoBMP.Height / 768)
        Else
	     ‘Width is confining
	     NewWidth = 1024
  	     NewHeight = PhotoBMP.Height / (PhotoBMP.Width / 1024)
        End If

Perform the Resize

Now we have our target width and height via good old fashioned math, now the technical bits for .NET to perform its magic. .NET can perform resizing via the Graphics class, by resizing data from the original bitmap data into a new, smaller bitmap. First we make a new, blank Bitmap of the correct new size.

        NewBMP = New Bitmap(newWidth, newHeight)

Then we create a new Graphics image using the reference of this new Bitmap object.

        ConvertGraphics = Graphics.FromImage(NewBMP)

Then we specify the method of scaling the image. Different methods work better for different amounts of scaling, but High Quality Bicubic is the one I tend to use.

        ConvertGraphics.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic

Now comes the actual conversion, we use the DrawImage method to draw our original bitmap into the new bitmap at the new size (at the starting coordinates of 0,0 in the new bitmap

        ConvertGraphics.DrawImage(PhotoBMP, 0, 0, NewBMP.Width, NewBMP.Height)

Dispose our old bitmap

        PhotoBMP.Dispose()

Save our new

        NewBMP.Save(“new.jpg”, ImageFormat.Jpeg)

And dispose

        NewBMP.Dispose()

And we’re done! You can also use the Graphics object to perform a number of paint-oriented operations on your image, such as lines and drawing text, but that you can have fun experimenting with.

With the exception of resizing which requires a few calculations, .NET makes image manipulation exteremly easy, and when combined into a web application, offers users some useful tools at virtually no cost to you.

Dynamically Truncate SQL Parameters in .NET

[SQL Server] String or Binary data would be truncated.

Run into this error before? The cause is usually fairly clear, we’re attempting to insert or update a field in a table with more data than it can hold. E.g. we’ve executed a SQL insert statement that attempts to assign a string 100 characters in length to a varchar field that can hold 80 characters max. Microsoft SQL Server complains, and we receive a nice error in our .NET application.

Solution 1: Don’t send too much data

This is an easy solution (and not the purpose of the article) and not always possible, but it is completely valid and often times desirable if you are writing an application that works with a SQL database in a static manner where the fields you’re updating are known ahead of time. There are a number of ways to ensure you don’t exceed the maximum size of a field.

If your data is coming from a form item, such as a text box, ensure the maximum size of the text box doesn’t exceed the maximum size of the field in the database. If you’re working with items that cannot be limited, simply take a substring of the data and manually truncate it to a size allowed by the field in the database. Many times we know what data and what sizes we’re working with at design time.

Solution 2: Read field sizes from database and dynamically truncate data

There are many times when solution 1 is not an option, mostly in situations where the database we’re working with is unknown, whether partially or fully, at design time. I’ve worked on a number of ETL tools and interoperability oriented applications where I can’t know the field size in the database at design time, it must be discovered at runtime.

One of the great parts about ADO.NET is the ease in which it deals with parameters. At the core of executing SQL statements is the SqlCommand (or OleDbCommand, or odbcCommand) class. After obtaining an instance associated with a database connection, we assign our SQL statement to it and all our parameters and values to it. In our case, the size of the parameter values we assign to it may exceed the maximum size of our receiving database fields. We need a method of iterating through each parameter and ensuring the value assigned isn’t too big.

Reading table schema

The heart of this routine is detecting which table you’re dealing with, then reading the schema of that table, then discovering the max size of each field.

I start by declaring a sub procedure that takes a SqlCommand as argument by reference.

        Sub TruncateParameters(ByRef passCommand As SqlCommand)

I then declared the following variables

        Dim targetTable As String 
        Dim LCV As Integer
        Dim tableCommand As SqlCommand
        Dim tableReader As SqlDataReader
        Dim tempRow As DataRow

targetTable is the name of the table we’ll be checking. I read it from the actual SQL statement in the SqlCommand – but I was dealing with fairly simple SQL statements. You may want to manually pass the table names in if you’re dealing with SQL statements that will be difficult to parse.

tableCommand, tableReader, and tempRow will be used to read in the schema of our targetTable.

Next I parse the SQL statement inside of passCommand to obtain the targetTable name, but again, you may want to manually pass the name of the table ahead of time if you’re dealing with difficult to parse SQL statements. Also, if you are familiar with regular expressions, you can pare this routine down quite a bit – I present it here completely algorithmically for people who aren’t familiar with regular expressions.

       If passCommand.CommandText.ToLower().IndexOf("update") > -1 Then
             'UPDATE command
             targetTable = passCommand.CommandText.Substring(passCommand.CommandText.ToLower().IndexOf("update") + 7)
       Else
             'INSERT command
             targetTable = passCommand.CommandText.Substring(passCommand.CommandText.ToLower().IndexOf("insert") + 12)
       End If

       targetTable = targetTable.Substring(0, targetTable.IndexOf(" "))

Next we read (up to) 1 row from our target table to obtain the schema.

        ' Open Data Reader for schema table
        tableCommand = New SqlCommand("SELECT TOP 1 * FROM " & targetTable, passCommand.Connection)
        tableReader = tableCommand.ExecuteReader()

This is where the magic happens – we iterate through each parameter in our passCommand, examine the field matching the parameter, get its max length, then truncate the value assigned to each respective parameter to the max size of the field. This routine assumes that you’ve used the same parameter names as field names. If you haven’t, you would need to do further parsing of the SQL statement to deduce a parameter name -> field name mapping. This routine is also targeted for strings, but would work just as well for binary data assuming you had a method of truncating such data. Also, there are a lot of shortcuts for doing case insensitive compares, my style is to convert to lower case and compare as I can never remember what is case sensitive and what is not. Feel free to use your own style.

        ' Loop through each parameter

        For LCV = 0 To passCommand.Parameters.Count - 1
            For Each tempRow In tableReader.GetSchemaTable().Rows
                If "@" & tempRow("ColumnName").ToString().ToLower() = passCommand.Parameters.Item(LCV).ParameterName.ToLower() Then
                    If tempRow("DataType").ToString().ToLower() = "system.string" Then
                        If passCommand.Parameters.Item(LCV).Value.ToString().Length > tempRow("ColumnSize") Then
                            passCommand.Parameters.Item(LCV).Value = passCommand.Parameters.Item(LCV).Value.ToString().Substring(0, tempRow("ColumnSize"))
                        End If
                        Exit For
                    End If
                End If
            Next
        Next

Finally, we close out our connection and end the sub procedure.

        tableReader.Close()

End Sub

There is some work involved, but the idea of the above routine can be customized to fit your situation. Once you have a solid parameter truncating routine in your arsenal, you can call it for any SqlCommand object, and ensure you never get a “String or Binary data would be truncated.” error message again!

Play Adventure Games, Be a Better Programmer

> Open trapdoor
> Go down
> Turn on lantern

I can’t count the number of times I typed the sentences above on my faithful Commodore 64 immediately after getting home from school every weekday afternoon. An explanation to the uninitiated: these simple statements were a way of communicating with a style of game known as “interactive fiction”, or “text adventure”. The particular one that started it all for me was the classic masterpiece known as Zork, where every day I could explore a mysterious underground empire from my room. While the magic of text adventures is an article in itself, after playing Zork once I was completely hooked. Not only did I seek out more adventures to sink my teeth into, I was also lucky enough that my parents purchased a PC for me soon after. From there I discovered the wonder of graphical adventure games, like the Monkey Island series from Lucas Arts and the Kings Quest series from Sierra. From then, and even to this day, I was a complete adventure game junky. No other genre of game could come close to giving me as much enjoyment.

How are adventure games relevant though?

For those who haven’t played an adventure game before, the premise is generally one of accomplishing goals through a series of small tasks. For example, in the popular classic from Lucas Arts, “The Secret of Monkey Island” (spoilers ahead!), at one point in the game it’s necessary to obtain money to purchase a number of items. There isn’t, of course, a pile of money sitting on the ground – that would be too easy. You need to earn it, in this case, from getting paid to get yourself shot out of a cannon at the circus. However, they won’t stick you in the cannon unless you’re wearing a helmet. Guess what? You need to find a helmet, and there is no helmet in the game. There is, however, a cooking pot in the tavern’s kitchen that would fit perfectly on your head. However, you can’t get into the kitchen because the cook won’t let you in…

As you can see, there is a goal (obtain sum of money), and a number of tasks involved in getting there (get into kitchen, get pot, wear it, fire out of cannon). Before you can accomplish a task, there are a number of prerequisite tasks that must be completed first. Each of those tasks has its own set of tasks to complete first, etc. In Computer Science, we call this step-by-step procedure an algorithm.

Algorithms are the heart of programming

Computers, the powerful machines they are, are at their core relatively dumb. They need to be given a list of instructions to follow. They can perform about 4 billion of them a second, but at the end of the day they still need that list of procedures, outlined step-by-step. This is where you, the programmer comes in. Given a goal you wish to accomplish, you must devise a series of steps to lead to that goal, then translate these steps into a language the computer (ultimately) recognizes, such as Visual Basic, C++, or Java.

The same mentality that guides us to get the helmet, to get the cannon, to get the money, is the same process that guides us to be good programmers: to think in steps. A top down approach of taking an overall goal, breaking it into smaller pieces, further dividing each of those pieces into easy steps, until we’ve turned a very large and complex problem into a series of tiny, easy to handle tasks. And sometimes in programming we need to take alternate avenues – just as there is no helmet in Money Island but a cooking pot which makes an excellent substitute, there will be many times in programming where alternative over conventional thinking is necessary to accomplish a goal.

Why adventure games build these skills effectively

The one issue with programming, especially if you’re new to it as I imagine many people reading this article are, is it is a fairly foreign concept. You’re so busy struggling with the syntax of the new language you’re learning that the overall design of the program itself suffers. While this is a necessary part of learning to program, wouldn’t it be great if there were other exercises you could do in the meantime to strengthen your algorithm building skills?

Enter adventure games. They are a great tool to improve your “algorithmic dexterity” as they are enjoyable and usually take place in recognizable situations that you are accustomed to. We all know what a cooking pot is, and we all know we can put it on our head. We know if we turn a lantern on, it’s going to provide light. These are situations we’re used to seeing. However, these common situations put to the extreme focus of step-by-step procedures are what build our instruction-making skills – and adventure games are the absolute masters of requiring this brand of thinking for hours at a time.

So start playing games!

I don’t want to give the wrong impression – learning to program is a lot of hard (but enjoyable!) work, and there are some dry moments when it takes memorization and reading a book/screen. However, when dealing with the flowcharts academia will make you draw out when learning algorithms (a favorite seems to be “Draw out your morning routine!”), or if you’re learning on your own, try supplementing the boring with a little fun. Fire up an adventure game and train your algorithmic brain! Not only will you build a necessary skill, but you’ll also have fun doing it.