• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 382
  • Last Modified:

How do I represent the total time played in seconds in C# for this game application?

How do I represent, in seconds, the total time played for the game represented in the code below.  The code is being run in Visual Studio 2005.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ShootTheGreenLightGame
{
    public partial class Form1 : Form
    {

        private Image redLightImage;
        private Image greenLightImage;
        private Graphics g;

        private Boolean IsGameOver = false;

        private int width;  // Win Mobile Pocket PC screen Width default 230
        private int height; // Win Mobile Pocket PC screen Height default 258

        private int redLightImageW;
        private int redLightImageH;
        private int currentRedLightX;
        private int currentRedLightY;

        private int greenLightImageW;
        private int greenLightImageH;
        private int currentGreenLightX;
        private int currentGreenLightY;

        private int score = 0;

        private const double SPEED = 1000 / 50; // 50 frames per second

        public KeyEventArgs keyState;

       
       
        public Form1()
        {
            width = Width;
            height = Height;

            redLightImage =
                 new Bitmap(System.Reflection.Assembly.GetExecutingAssembly()
                 .GetManifestResourceStream("ShootTheGreenLightGame.RedLightW30H20.gif"));

            redLightImageW = redLightImage.Width;
            redLightImageH = redLightImage.Height;


            greenLightImage =
                new Bitmap(System.Reflection.Assembly.GetExecutingAssembly()
                .GetManifestResourceStream("ShootTheGreenLightGame.GreenLightW30H20.gif"));

            greenLightImageW = greenLightImage.Width;
            greenLightImageH = greenLightImage.Height;

            g = CreateGraphics();
           
            InitializeComponent();
        }

        public void Stop()
        {
            IsGameOver = true;
            MessageBox.Show(String.Format("Game Over\n\nScore = {0}\nTotal Time = {1}", score));
            Application.Exit();
        }


        public void Start()
        {

            score = 0;
            IsGameOver = false;

            currentRedLightX = 0;
            currentRedLightY = 0;

            currentGreenLightX = width / 2;
            currentGreenLightY = height / 2;


            double minIterationDuration = SPEED; // 50 frames / sec

            //game loop
            while (!IsGameOver)
            {
                if (IsCollision())
                {
                    score += 10;
                }

                DateTime startIterationTime = System.DateTime.Now;
                UpdateGameState();
                Render();
                DateTime endIterationTime = System.DateTime.Now;
                TimeSpan iterationDuration = endIterationTime - startIterationTime;
                if (iterationDuration.TotalMilliseconds < minIterationDuration)
                    Thread.Sleep(Convert.ToInt32(minIterationDuration - iterationDuration.TotalMilliseconds));
                Application.DoEvents();
            }

        }


        public void UpdateGameState()
        {
            if (keyState != null)
            {
                switch (keyState.KeyCode)
                {
                    case Keys.Left:
                        currentRedLightX = Math.Max(0, currentRedLightX - 5);
                        break;
                    case Keys.Right:
                        currentRedLightX = Math.Min(width - redLightImageW, currentRedLightX + 5);
                        break;
                }
            }


            if ((currentRedLightY + 5) >= (height - redLightImageH))
            {
                currentRedLightY = 0;
            }
            else
            {
                currentRedLightY += 5;
            }
        }


        public void Render()
        {
            g.Clear(System.Drawing.Color.White);
            g.DrawImage(redLightImage, currentRedLightX, currentRedLightY);
            g.DrawImage(greenLightImage, currentGreenLightX, currentGreenLightY);
        }


        public bool IsCollision()
        {
            if (currentRedLightX >= (currentGreenLightX - 15) && // 15 = 1/2 greenLightImageW
                currentRedLightX <= (currentGreenLightX + 45) && // 45 = 1 1/2 greenLightImageW
                currentRedLightY >= (currentGreenLightY - 10) && // 10 = 1/2 greenLightImageH
                currentRedLightY <= (currentGreenLightY + 30))  // 30 = 1 1/2 greenLightImageH
                return true;
            else
                return false;
        }


        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Render();
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            Start();
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == System.Windows.Forms.Keys.Up))
            {
                // Up
                keyState = e;
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Down))
            {
                // Down
                keyState = e;
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Left))
            {
                // Left
                keyState = e;
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Right))
            {
                // Right
                keyState = e;
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Enter))
            {
                // Enter
                Stop();
            }

        }

    }
}
0
NSing
Asked:
NSing
1 Solution
 
cdaly33Commented:
Setup a timer on load then start it in the Start method and stop it in the Stop method.  You can evaluate the time played using the Elapsed property of the timer.

http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.71).aspx
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Or you can just add it into to your already existing game loop:

            //game loop
            DateTime startTime = DateTime.Now;  //    <--------- record start time before the loop begins
            while (!IsGameOver)
            {
                if (IsCollision())
                {
                    score += 10;
                }

                DateTime startIterationTime = System.DateTime.Now;
                UpdateGameState();
                Render();
                DateTime endIterationTime = System.DateTime.Now;
                TimeSpan iterationDuration = endIterationTime - startIterationTime;
                TimeSpan elapsed = DateTime.Now.Subtract(startTime);  //    <--------- calculate elapsed time
                label1.Text = ((int)elapsed.TotalSeconds).ToString() + " seconds";  //    <--------- somehow display elapsed seconds
                if (iterationDuration.TotalMilliseconds < minIterationDuration)
                    Thread.Sleep(Convert.ToInt32(minIterationDuration - iterationDuration.TotalMilliseconds));
                Application.DoEvents();
            }
0
 
NSingAuthor Commented:
Thanks.  That was the approach that I was attempting to take but was not capturing the time outside the game loop..
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now