Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Pac-Man for the Smartphone

  The article expains writing a game, Pac-Man for Windows Mobile 5.0 Smartphone platform
Bryan Dougherty's Blog

Difficulty: Intermediate
Time Required: 3-6 hours
Cost: $50-$100
Software: Visual Basic or Visual C# Express Editions
Hardware: Motorola MPX220
Download: Download

Introduction

I've always loved mobile technology and I wanted to try my hand at mobile development. So a little ways back I bought a Smartphone, the Motorola MPX220, which runs the Windows Mobile 2003 OS. I hope to upgrade to a new Smartphone soon, so this article will discuss building an application targeting the Windows Mobile 5.0 Smartphone platform.

When deciding what to do, I thought of a variety of useful applications I could build. Then I decided that making a game would be more fun. I settled on a classic: Pac-Man.

Figure 1: Pac-Man running on Windows Mobile 5.0 Smartphone Emulator

Getting Started

Before diving into code, I thought I'd mention some of the pieces involved in developing for the Smartphone.

Development Environment

In order to create applications for the Windows Mobile 5.0 Smartphone platform, the following applications need to be installed:

  • Visual Studio .NET 2005 Professional Edition

  • Windows Mobile 5.0 Smartphone SDK

  • ActiveSync Version 4.1.0

New Project

Once the development environment is set up, the new Mobile 5.0 Smartphone templates appear under the New Project dialog in Visual Studio.

Click here for larger image

Figure 2: New Project dialog in Visual Studio (click image to zoom)

Note that you choose which version of the Compact Framework you are targeting when you select the project template. Those targeting CF1.0 have 1.0 after the name, while the others target the 2.0 Framework.

Development, in general, feels just like development of any WinForm application. You do need to keep in mind, however, that some functionality supported by the standard .NET Framework is not supported by the Compact Framework. For more on support for classes you can look in the MSDN Library.

The Emulator

While developing, you don't have to deploy your application to an actual phone when you want to test. Instead, a built-in emulator, as seen in the Figure 1, is available. With the click of a button, you can deploy to the emulator and test your application with full debugging capability, just like you would a WinForm application. The behavior and speed of the emulator seemed to provide a reasonable indication of how the application would perform on an actual phone.

Development

Instead of rushing in and trying to crank out the code for Pac-Man, I took a more structured approach. With a few proof of concepts under my belt, I decided to build a framework that would provide the common building blocks needed to create 2-D games for a Smartphone. I tried to focus on the following functionality as goals:

  • A game board that controls efficient painting and game flow

  • A basis for defining game characters supported by the game board

  • Built-in support for common interactions between characters

A basic litmus test for success would be whether someone (like you) could use this framework to build a classic 2-D video game, like Frogger, by only writing the new code managing interactions between the characters specific to the game.

The remainder of the article will highlight a few of the key concepts I built into the framework.

Sprites

The Sprite class provides the basis for all characters in the game. In Pac-Man, this includes ghosts, dots, walls, and Pac-Man himself. The class is abstract, forcing all derived classes to implement two methods:

public abstract void Update();
public abstract void Draw(Graphics gameSurface);

Not surprisingly, they expect the derived class to update their state and draw themselves to the game board, respectively. Methods are provided for getting the instance of the GameBoard the Sprite has been added to, and detecting collisions between one Sprite and a list of other Sprites. In addition, a Sprite instance is expected to manage several state properties:

  • ID—must be unique per GameBoard

  • Bounds—a rectangle that defines the perimeter of the object. A future version could use a Region or other construct to more accurately track the area taken up by the Sprite. This property is used for collision detection and drawing.

  • Invalid—a boolean that tells the GameBoard whether a Sprite needs to be redrawn

  • Visible—a boolean that determines whether a Sprite should be drawn or not

GameBoard

The GameBoard class controls the flow of the game. It derives from System.Windows.Forms.Form, and like the Sprite class, it is not creatable. This inheritance structure allows the developer to handle any Form events needed for his game. Below is an example in which the Pac-Man application's GameBoard class listens to user input by overriding the OnKeyDown method.

protected override void OnKeyDown(KeyEventArgs e)
{
    _KeyPressed = true;
    base.OnKeyDown (e);
    if(e.KeyCode == Keys.Right || e.KeyCode == Keys.Left || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
    {
        switch(e.KeyCode)
        {
            case Keys.Right:
            {
                _Pacman.MovementDirection = MovementDirections.Right;
                break;
            }
            case Keys.Left:
            {
                _Pacman.MovementDirection = MovementDirections.Left;
                break;
            }
            case Keys.Down:
            {
                _Pacman.MovementDirection = MovementDirections.Down;
                break;
            }
            case Keys.Up:
            {
                _Pacman.MovementDirection = MovementDirections.Up;
                break;
            }
        }
    }
}

Each game application needs to create its own game board class that derives from GameBoard. All character Sprites should then be created and added to the GameBoard's list of Sprites. Then, after the GameBoard loads, a Timer is used to call the Update and Draw methods on Sprites as mentioned above.

Painting

So how exactly does the drawing of the Sprites work? From a Sprite's perspective, it's simple. All a Sprite needs to know is how to draw itself. A Dot Sprite for example, simply draws a rectangle to the game board graphics object.

public override void Draw(Graphics gameBoard)
{
    if(!_IsEaten)
    {
        gameBoard.FillRectangle(new SolidBrush(Color.LightBlue), _Bounds);
    }
}

The Draw methods for Pac-Man and Ghost Sprites are more complicated and draw one of a series of bitmap images to the game board. The changing images, along with updated Bounds create animation. When drawn, a color is chosen (magenta in the Figure 3 below) to indicate portions of the image that should be treated as transparent.

Figure 3: Ghost Sprite image enlarged

The GameBoard class makes the screen painting as efficient as possible. It overrides the Form OnPaint and OnPaintBackground methods since it controls all the updating of the screen. The OnPaint method makes sure that only the portions of the screen that have changed get repainted. In addition, it uses a back buffer to minimize any flicker.

protected override void OnPaint(PaintEventArgs e)
{
    if(_BackBuffer == null) 
    { 
        return;
    }

    Graphics g = Graphics.FromImage(_BackBuffer);

    ArrayList changedSprites = new ArrayList();
    // blank out any invalid Sprites previous position in the back buffer
    foreach(Sprite sprite in _SpritesByZIndex)
    {
        if(sprite.Invalid)
        {
            g.FillRectangle(new SolidBrush(_BackgroundColor), sprite.PreviousBounds);
            changedSprites.Add(sprite);
        }
    }

    // now draw them to the back buffer
    foreach(Sprite sprite in changedSprites)
    {
        if(sprite.Visible)
        {
            sprite.Draw(g);
        }
    }

    if(_FullRepaint)
    {
        // draw the entire back buffer 
        e.Graphics.DrawImage(_BackBuffer, 0, 0);
        _FullRepaint = false;

        foreach(Sprite sprite in _SpritesByZIndex)
        {
            // reset Invalid flag
            sprite.Invalid = false;
        }
    }
    else
    {
        // only draw the parts that have changed
        foreach(Sprite sprite in changedSprites)
        {
            e.Graphics.DrawImage(_BackBuffer, sprite.Bounds, sprite.Bounds, GraphicsUnit.Pixel);
            e.Graphics.DrawImage(_BackBuffer, sprite.PreviousBounds, sprite.PreviousBounds, GraphicsUnit.Pixel);

            // reset Invalid flag
            sprite.Invalid = false;
        }
    }
}

Mobile Development Considerations

As I've said, from a coding perspective, developing mobile applications in .NET is very similar to building standard WinForm apps. However, this little project did bring to light a number of things you have to keep in mind with mobile applications, most centering around the word "small".

The most obvious consideration is that the device has a small screen. That means you have to design a user interface that is easy to use within the minimal real estate. That tends to translate into keeping things simple. One other screen consideration is that from phone to phone, screen size and resolution may change. I didn't address that with my first cut of Pac-Man, but it's on the list. In my testing I targeted a lower resolution that would work on my phone.

With any type of application, but especially with a game, you have to think about how a user will interact with the small keys of his phone, possibly using no more that a thumb! I consciously made controlling Pac-Man a little different than the typical arcade feel to make up for some of the clumsiness of using the phone's directional pad. That change has received mixed reviews from the people who have tried it out. That's what testing is for, though, right?

The other "small" consideration is the phone's horsepower. While a Smartphone blows away my old Tandy 64K Color Computer, the computer I started playing games on, I definitely found myself needing to tweak the code for performance. I was sure ahead of time that highly efficient painting logic would be necessary. I was surprised, however, to find that the code that prepares the possible travel paths for ghosts takes a considerable amount of time to crunch. For that reason, I made sure that this logic is only processed the first time the splash screen is displayed. It is then cached for later reuse.

Conclusion

So there it is...well, the first version, at least. I plan to periodically update the game making it more efficient and more fun—smarter ghosts for starters. Maybe I'll even eat my own dog food and try building Frogger to see if that little framework I put together holds water. I really want to add a feature to report high scores to a web site. What's a game with out a little healthy competition, right?

I recently started a blog about this and other topics related to software development on my company's blog site. The code and compiled game for the all platforms will be available there, too. Feel free to check for updates and post any feedback you may have.

Tags:

Follow the Discussion

  • aliali

    well i read ur coding its really nice , but i need it in c language if u have so pls send me on this mailling address,

    arrow_wazir2001@yahoo.com

  • Tony RichardsTony Richards

    Did you know you've got the 'Required Software' in the description for this article wrong?  You say in the description you only need VB .Net or C# .Net express, when you actually need Visual Studio Professional.

  • AnithaAnitha

    Can any one please explain me how to display the set of images, each image should display for few seconds then display the next image using VB.Net,Windows mobile 5.0 smartphone.

  • Luiz S. PiresLuiz S. Pires

    Easy and Works, very good.

    Congratulations.

  • Bungei SamsonBungei Samson

    Can any one please explain to me how to develop an sms application from the smartphones.

  • Clint RutkasClint I'm a "developer"

    @Bungei Samson:  It is on my summer to do list.  I actually have one done, I just need to test it out.

  • Clint RutkasClint I'm a "developer"

    @ramya On a form, there is the "AutoScroll" property.  Set that and you're good to go Smiley

  • ramyaramya

    can anybody give me ideas for adding scrollbars in smartphone2003

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.