Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

StopWatch coding problems 5

Status
Not open for further replies.

OMGNinja

Programmer
Apr 1, 2010
9
US
ok so I am trying to get this game to have a timer and I got it down to the stopwatch thing but Visual Studio 2005 says that
"Error 1 The type or namespace name 'Stopwatch' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Kakashi\Documents\Visual Studio 2005\Projects\ShootTheGreenLightGame\Form1.cs 40 9 ShootTheGreenLightGame
"

Um what am i missing here? I have this in just like the book says it to be, here is the code for the program; The stop watch is declared at the top and then its started in the main game loop ie public void Start()
and the stoped is called at public void Stop()
Thanks for any help
Code:
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;
using System.Diagnostics;




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;

        Stopwatch stopWatch = new Stopwatch();

        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;
            //stop the watch
            stopWatch.Stop();
            long millis = stopWatch.ElapsedMilliseconds;
            // Get the elapsed time as a TimeSpan value.
            TimeSpan ts = stopWatch.Elapsed;

            MessageBox.Show(String.Format("Game Over\n\nScore = {0}", score + "\n\nTime played is = {0}", millis));
            Application.Exit();
        }


        public void Start()
        {
            //makes a new stopwatch for the game timer
            
            stopWatch.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();
            }

        }

    }
}
 
To me it looks like Stopwatch() is a namespace so you need to import it with a "using" statement.

Patrick
 
Actually, Stopwatch is a class, not a namespace. It looks like a class that's supposed to give you the time lapsed for as soon as you stop the application (as a result of pressing ENTER).

Make sure you have the Stopwatch class (probably on another .cs file) included in your project on the same namespace as Form1 class. (Note: C# is case-sensitive)
 
According to this resource the stopwatch class is in the using System.Diagnostics. Which i think I imported correctly. Am i using it wrong in the code did I create it in the wrong place?
 
private int width; // Win Mobile Pocket PC screen Width default 230
private int height; // Win Mobile Pocket PC screen Height default 258

According to MSDN this may not be supported on all .NET compact platforms.

If you choose to battle wits with the witless be prepared to lose.

[cheers]
 
I see, does anyone know o a nother way to get a timer in the code, I was just follwoing a book and it does not have any ting else in it about seeing how long a program takes to run.
 
you could build your own StopWatch and use DateTime.Ticks to determine the difference.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Ok I think I got this figured out with Environment.TickCount
But now I am having a problme with testing it. I am trying to print out the time played here with this line but it prints out this
Time played = {0}
i want it to print out the mills value what is wrong with it?
Code:
MessageBox.Show(String.Format("Game Over\n\nScore = {0}", score + "\n\nTime played is = {0}", millis ));

here is the whole code if that helps;
Code:
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;
using System.Diagnostics;





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 int millis = 0; //no time played
        private int startTime;

        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;
            //stop the watch
            
            int end = Environment.TickCount;
            millis = end - startTime;



            MessageBox.Show(String.Format("Game Over\n\nScore = {0}", score + "\n\nTime played is = {0}", millis ));
            Application.Exit();
        }


        public void Start()
        {
            //time starts here

            startTime = Environment.TickCount;


            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();
            }

        }

    }
}
 
try this -

MessageBox.Show(String.Format("Game Over\n\nScore = {0}\n\nTime played is = {1}", score, millis ));

carl
MCSD, MCTS:MOSS
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top