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

Upgrade Your Game: TinyTennis (C#)

  This article is a part of Upgrade Your Game series of tutorials. It walks you through the game architecture components for our tribute to Pong!, which we'll call TinyTennis.
The Z Buffer

Difficulty: Intermediate
Time Required: 1-3 hours
Cost: Free
Software: Visual Basic or Visual C# Express Editions
Hardware:
Download:

Demo Video

Download Video

Visual C# Upgrade Your Game Series

 

Introduction

Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds on the last to improve your skills. The skills can be applied to more complex games including 3D games using Microsoft DirectX.

Let's begin by creating a really simple game like Pong!, which uses only three moving objects and a straightforward gameplay and scoring technique. Given that you probably play games thousands of times more complex than this (such as The Sims or Half Life), you may initially dismiss this exercise as a waste of time; however, it's a great way to learn some of the fundamental concepts of video games in just a few lines of code. If these techniques are already familiar to you, then you may be interested in the MSDN game development webcasts, which cover 2D and 3D game development with Managed DirectX.

This tutorial walks you through the game architecture components for our tribute to Pong!, which we'll call TinyTennis.

You are also free to use the source code as the basis for your own projects, and to share your work with others or upload it to the Internet.

Note: This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics in the product documentation by clicking Help on the menu bar, and then clicking Contents, Index, or Search. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.

Getting Started

Building and Running TinyTennis

Once your project is loaded into the Visual Basic environment, you can compile and run the program in one step.

To build and run TinyTennis:

  • Press F5 to build and start the game under the debugger.

The game launches and you can control the left bat using the Q and A keys.

Files

  • Sprite.cs
    The base class for the sprites. It contains initialization code and basic movement code.
  • TinyTennis.cs
    The main form for the application. It initializes the sprites for the bats and ball, passes keyboard intput to the bats, and controls drawing the game to the screen.
  • ControlSprite.cs
    An implementation of a sprite that uses a Windows control to draw to the screen.
  • Bat.cs
    A ControlSprite representing the bat. Contains the keyboard movement code for human players and AI code for computer players.
  • Ball.cs
    A ControlSprite representing the ball. Contains the code for checking for collisions with the walls and the bats and the bounces. Also plays the only sound in the game.
  • GameState.cs
    Stores the scores.

 

Game Development Concepts

If you are new to 2D game development, check out the 2D Game Primer (Visual Basic).

Implementing Sprites

For TinyTennis, you'll need three very simple rectangular sprites that can be moved around the screen. In order to keep things simple for the first game (and because I recognize that a lot of .NET developers come from a Windows Forms background), I have chosen to use PictureBox controls to represent the sprites. A picture box has all the characteristics needed for this simple game:

  • It's rectangular.
  • It can have a background color.
  • It can be positioned at specific positions on the screen.

Using a picture box is not something you would do in a real computer game, but it's something that is very simple to get started with and hopefully something you already know about. In the next game, you will replace the picture box with real graphics.

The base class definition is:


public class Sprite
{
public PointF Velocity;
public PointF Location;
public SizeF Size;

The inherited class adds a member for the control.


public class ControlSprite : Sprite
{
public Control Control;

The inherited class defines how to draw it. Since Windows Forms can only be positioned at integer pixel boundaries, you have to round the sprite positions.


public override void Draw()
{
//Move the control to the correct location
Control.Location = new Point((int)(Location.X + .5f), (int)(Location.Y + .5f));
//and redraw it
Control.Refresh();
}

The Windows Forms controls used in this game are created in the designer by dragging picture boxes onto the form. Since the size and position are set in the code, there's no need to position or size them correctly in the designer. All you need to do is name them correctly.

(Click image to zoom)

Code structure

Just because the game is simple doesn't mean that you should avoid good software engineering practices. This is especially important since you want to create a base on which to build the next two games. And, although Visual Studio Express has some refactoring support, it always helps to get things right from the beginning.

The most important class is the sprite. Sprites have a position and a velocity. Velocity is how fast the position changes in pixels per second. If velocity is 0, then the position will stay the same and you'll have a static sprite. In addition, you need to remember how big the sprite is so that you can work out collisions.

The game loop needs to call each sprite and perform two tasks: update and draw. Since you know the velocity, you can implement the movement part of the animation in the base class. Any complex or additional updates will be handled in an inherited class. For this game, drawing the sprite will be left to an inherited class since there is no general case.

Because I'm using PictureBox controls, I've decided to create an inherited ControlSprite class that can be thrown away in the later examples. ControlSprite sets the position of the control that represents the sprite and calls the RefreshMethod to paint it on the screen.

The Bat and Ball objects inherit from ControlSprite and provide the special processing that each of those require. For example the Bat class changes its velocity based on keyboard presses and AI. The Ball class changes its velocity based on collisions with bats and the edges of the gameplay area.

(Click image to zoom)

Implementing Time Based Animation

As mentioned in 2D Game Primer (Visual Basic), it's important to move the sprites based on time rather than a fixed distance per frame.

The first thing to do is make sure you have an accurate measure of the time. The .NET Framework 2.0 added the StopWatch class, which uses the most accurate measure available on your computer.


private Stopwatch _timer = new Stopwatch();
public TinyTennis()
{
//Initialise and start the timer
_lastTime = 0.0;
_timer.Start();
}
private void TinyTennis_Paint(object sender, PaintEventArgs e)
{
//Work out how long since we were last here in seconds
double gameTime = _timer.ElapsedMilliseconds / 1000.0;
double elapsedTime = gameTime - _lastTime;
_lastTime = gameTime;
}

Sometimes animation is based on how far into the game you are; sometimes it's based on how long it has been since the last time around the game loop. Rather than having every object calculate these two values, you do it once and pass it to the Update() function for each object.

The Update method of the Sprite objects and their inherited classes eventually gets called with these times:


public virtual void Update(double gameTime, double elapsedTime)
{
//Move the sprite based on the velocity
Location.X += Velocity.X * (float)elapsedTime;
Location.Y += Velocity.Y * (float)elapsedTime;
}

Simple AI (Artificial Intelligence)

The interesting thing about AI for TinyTennis is actually making the AI do things wrong. It's interesting because normally AI is about making a computer play well. For this game playing, a perfect game is trivial for the computer:

  • Calculate the exact position the ball will end up and move the bat there. This involves some math but is simple to do.
  • Track the ball by moving the bat towards the current Y position of the ball. There is no math involved, but as long as the ball speed is not greater than the bat speed this will always work.

Of course this kind of opponent is no fun to play against, so the AI challenge for this game is making the computer miss the ball in a realistic, human way. I have chosen to take three approaches to this:

  1. The computer doesn't start moving the bat until the ball is close to the computer side of the screen. How close can be varied to make the AI smarter or dumber.
  2. The computer doesn't track bounces — it will look which way the ball is heading and move towards it, but a last-minute bounce may throw it off.
  3. Just like a human, sometimes the computer will over- or underestimate how well it tracks the ball. This is implemented by adding a random offset into the movement that can, once again, be varied to change the skill level.

Extending TinyTennis

  • Add a start-up splash screen that allows the player to choose between one and two players.
  • Add an additional bat for each player by creating an extra picture box, and then creating additional Bat objects.
  • Add multiple balls. The game play will need to change a little. For example, do you want to pause the game when a point is scored? Or, do you want to score the point and make a new ball appear?
  • Since the sprites are just picture boxes, you can set the background image property to give the game a whole new look and feel. Remember that the collision detection is done based on the rectangular shape of the picture box; if the image does not fill the picture box, it might look odd when the ball bounces.

Follow the Discussion

  • ERicERic

    It is near the top of the pace labeled "C# Download".

  • bpbp

    near the top of this page is a link that says 'C# Download' which is a download of a .vsi file that installs a .zip file containing the source. Pay attention to where it installs the .zip file, to make sure you can find it and unzip it. On my PC it put it in a Visual Studio 2005 templates directory.

  • NeverCrackerNeverCracker

    To download the TinyTennis kit:

    http://download.microsoft.com/download/0/7/8/078f6de6-4b20-47a3-9a94-dbf3a0131ca0/tennis.vsi

  • GeorgeGeorge

    You can download TinyTennis from the top of this page. Click "C# Download" under the "Download:" heading.

  • cichlasomacichlasoma

    Mackan: go for "C# Download" at the top of the site. Smiley

  • samsam

    click on the link above the demo video and save the file then open it and it should extract all the required files

  • PaulPaul

    I got this message error trying to install this started kit, any idea why this is going on?

    Installation stopped because the directory for the ProjectType value did not exist.  The project type is invalid for your installation of Visual Studio

    what can i do, Thanks.

  • BcaseyBcasey

    I downloaded unzipped and opened the tiny tennis solution using visual c# 2008 express edition.  This required a conversion. After compilation I got errors and warnings, which I've pasted in at the bottom of this. I hope I'm not just being a greenie, and I'm bringing up a relevant question but in either case, hopefully you will still have an answer.

    Thank you

    Following are the warnings and error messages:

    Warning 1 Load of property 'RootNamespace' failed.  The string for the root namespace must be a valid identifier. TinyTennis

    Error 2 Unexpected character '$' C:\Documents and Settings\Brendan Casey\My Documents\Visual Studio 2008\Projects\tinytennis\Sprite.cs 7 11 TinyTennis

    Error 3 Unexpected character '$' C:\Documents and Settings\Brendan Casey\My Documents\Visual Studio 2008\Projects\tinytennis\Sprite.cs 7 27 TinyTennis

    Error 4 Identifier expected C:\Documents and Settings\Brendan Casey\My Documents\Visual Studio 2008\Projects\tinytennis\Sprite.cs 7 11 TinyTennis

  • SamSam

    This is all very interesting, but I have about the stupidest question asked ever: How do you move your own bat thingy to block the ball???

  • BillBill

    The download link is at the top of the page.

  • Clint RutkasClint I'm a "developer"

    @Nick:  I Just downloaded it, unzipped the tinytennisstarterkit

    C:\Users\crutkas\Documents\Visual Studio 2008\Templates\ProjectTemplates\Visual C#\TinyTennisStarterKit

    Started a new project with it as the template and it compiled just fine.  I didn't even have to convert it.  To get it as a Template, I clicked on "Visual C#" in my project types in the "New Project" dialog.

  • Clint RutkasClint I'm a "developer"

    @Nick:  What are the errors?  The source is a tad old for this game judging by the date but I'll see what I can't do to help out.

  • NickNick

    41 errors after conversion for VS2008.  Anyone figured out how to get this running under '08?  

  • CaioCaio

    About the errors.

    Is just erase the "$" caracters from the classes names.

    Then it should compile nicely.

  • Clint RutkasClint I'm a "developer"

    Welcome to the Upgrade Your Game series of tutorials. In this article, we will develop a role-playing

  • Coding4Fun : Intro to XNA Part 1: Building Tiny TennisCoding4Fun : Intro to XNA Part 1: Building Tiny Tennis

    PingBack from http://blogs.msdn.com/coding4fun/archive/2006/12/10/1256876.aspx

  • Clint RutkasClint I'm a "developer"

    This article is the first part of the Upgrade Your Game series of tutorials. It walks you through the

  • JamieJamie

    For those of you who are receiving this error posted earlier by Paul:

    "Installation stopped because the directory for the ProjectType value did not exist.  The project type is invalid for your installation of Visual Studio"

    It is because you have changed the default location of where Visual Express saves projects and templates.  To fix this go into tools>options>projectsandsolutions>general:

    from here reset the saving folders back to the default location which should be something like:

    C:\Documents and Settings\User\My Documents\Visual Studio 2008\Projects

    C:\Documents and Settings\User\My Documents\Visual Studio 2008\Templates\ProjectTemplates

    C:\Documents and Settings\Aeklad\My Documents\Visual Studio 2008\Templates\ItemTemplates

    After I did this I was able to install all of the .vsi files no problem.

  • elaheelahe

    hi i glad to see you're website.

    thank's alot and i want you're email because i have a problem how i get u're email?

  • Clint RutkasClint I'm a "developer"

    @elahe http://blogs.msdn.com/coding4fun/contact.aspx

  • jh1507jh1507

    Umm...

    I find the code abit onfussing do you have

    any other recomendation where i can learn

    2D game programming on the internet with C#?

    Nice into!

    jh1507

  • Clint RutkasClint I'm a "developer"

    @person, the link for the installer for the game (with source code) is at the top of the page labeled "c# Download"

  • personperson

    any chance you want to post the code for the entire game... Smiley please!

  • JeffJeff

    One word Awesome Wink

  • DoktorDoktor

    Yupp,it just works fine in vs2010 too when you go on new project and then c# template and you will find tinytennis among the others in the list.

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.