By

Introduction:

A game loop is one of the most fundamental requirements for a game, it is what makes the game move forward in time, that is, real-time. This is opposed to a standard forms application which is non real-time and requires user’s input to function.

Note: This is not in any way best practices and is not “production” ready (eg. one can use DirectX timers etc.) but it is fine if you just want to create a simple game for fun.

So hear it is:

public partial class Form1 : Form
{
        /// <summary>
        /// change in time since the last time the game’s
        /// state/dynamics was updated
        /// (last time the form was refreshed)
        /// </summary>
       double deltaTime = 0;

        /// <summary>
        /// used to calculate the deltaTime above
        /// </summary>
       Stopwatch stopwatch = new Stopwatch();

        /// <summary>
        /// a custom class used to store variables for the
        /// dynamics of the game, AI’s state etc.
        /// </summary>
	GameState gameState = new GameState();

	/// <summary>
        /// a custom class used to  draw the Game State’s
        /// (shapes, game objects etc)
        /// </summary>
	GameStateDrawer gameStateDrawer;

	public Form1()
	{
                // required to initialise the windows form
		InitializeComponent();

                // ensures that all painting on the form takes
                // place in OnPaint Event
               // (if this is not included the painting of
               // the background color is handled by Windows
               // Forms elsewhere)
		this.SetStyle(ControlStyles.AllPaintingInWmPaint
                          | ControlStyles.Opaque, true);

		gameState = new GameState();

		gameStateDrawer = new GameStateDrawer();
	}

        // you create this method by double clicking
        // on the Paint event in the windows forms UI designer.
	private void Form1_Paint(object sender, PaintEventArgs e)
	{
                // In here you would make heavy
                // use of the .NET System.Drawing
                // Namespace. For example you can
                // call e.Graphics.DrawRectangle()
		gameStateDrawer.Draw(ref e.Graphics,
                                                gameState);

		deltaTime = stopwatch.Elapsed.TotalSeconds;

                // pass the change in time into the
                // game state (this would be used to
                // update the dynamics of the game,
                // object positions etc).
                // eg. objectPositionNew = objectPositionOld +
                // (deltaTime * objectPositionSpeed)
		gameState.UpdateGameState(deltaTime);

		stopwatch.Restart();

                // this essentially makes the game real-time,
                // it recalls this paint method
		this.Invalidate();
	}

	private void Form1_KeyUp(object sender, KeyEventArgs e)
	{
		gameState.HandleKeyPress(e.KeyValue);
	}
}

Post Addition: Response to Joel’s comment – August 23, 2011
GameState Example:

public class GameState
{
    // used to control game state
    // like is user looking at a game menu or playing etc.
    public enum State
    {
        InMenu1,
        Playing
    }

        public State CurrentGameState { get; set; }
        
        public int PlayerPosition;

        public int PlayerVelocity;

        public GameState()
        {
           CurrentGameState = State.InMenu1;
        }

        public void UpdateGameState(double deltaTime)
        {
              switch (CurrentGameState)
             {
                case State.InMenu1:

                break;

                case State.Playing:
                 //update the position of the player
                PlayerPosition = PlayerPosition + (PlayerVelocity*deltaTime);
                break;
             }
        }

        public void HandleKeyPress(int keyValue)
        {
            switch (CurrentGameState)
            {
                case State.InMenu1:
                    if(keyValue == 'S')
                    {
                        //start the game
                        CurrentGameState = State.Playing;
                    }
                    break;
                case State.Playing:
                     if(keyValue == '+')
                    {
                        //increase player velocity
                        PlayerVelocity++;
                    }
                    else if(keyValue == '-')
                    {
                        //decrease player velocity
                        PlayerVelocity--;
                    }
                     else if(keyValue == 'e')
                    {
                        //exit and go back to the menu
                        CurrentGameState = State.InMenu1;
                    }
                    break;
                default:
                    break;
            }
        }
}

GameStateDrawer Example:

public class GameStateDrawer
{
          int rectangleWidth = 5;
          int rectangleHeight = 5;
          public GameStateDrawer()
          {
            
          }

          public void Draw(ref Graphics graphics, GameState gameState)
          {
                //draw the player at his current position as a rectangle we set the player y position to 5 here
                // note the windows forms top left corner is 0 x and 0 y. as you go down the form y increases and as you go right x increases.
                 graphics.FillRectangles(new SolidBrush(Color.Black),  new Rectangle(gameState.PlayerPosition,5, rectangleWidth , rectangleHeight));  
          }
}

Share


  Hi, I'm Steven and the author of this blog
  Follow me on or