Hello guys, I hope you are all well!

I am creating a game in Visual Studio using picture box's, but I cannot for the life of me figure out how I can have a nice picture in the background, as when I do put one in there it is constantly redrawn everytime the game refreshes and this make it impossible to play as it slows almost to a halt. My question for you pro's is, can I set the background image of the panel to never refresh?

With the amount of different things Visual Studio can do, I am sure there must be a way to achieve this simple task?

I have tried everything but I cannot figure it out, if anyone can help me I would be greatly appreciative!

Many thanks to you all!!

Cheers!!!!!!

Recommended Answers

All 13 Replies

This is more complicated than you would think, Are you invalidating the entire control surface? or just what may have changed? are your picturebox's userdrawn with a transparent background? or just regular pictureboxes? are you drawing directly to the surface of the panel using its paint event? or are you moving controls in front of it?

The root of the problem would be that you are refreshing the entire panel. Requiring it to be redrawn. GDI+ is slow. That's why games are usually written in XNA for C# or DirectX, openGL, ect. If you are going to use GDI+ for a game, you need to make sure that you only invalidate areas that change, not entire sets of controls or the entire game surface at every update.

for example, if the top left corner 20px wide and 10px tall displays the score, then that information might need to be updated often. If that information is on its own control, then that control will handle invalidating it's self. But if that data is drawn onto the panel, then it should be manually invalidated, but you should pass the rectangle that contains the area to be invalidated to the invalidate method.

Kind of long winded, I hope you got something out of that.
for any other assistance, we will need to see some code to know what we are dealing with.

Hey there, many thanks Diamonddrake for your reply!

You made perfect sense, I a beginner at C# but getting the hang of it, but you made perfect sense with regards to the invalidating. I will post my mainscreen code which conatins the code to create and run the game. If you or anyone else has any ideas on how I could hava background image without it being refreshed I would be over the moon. I just get ideas and I need to know if there is a way to do them and if so how it can be done. That is how I practically created this whole game.

I understand that each picturebox must be refreshed individually, but I am not experienced enough to start editing everything but if you have suggestions please let me know.

Also, how different is it to create games using XNA? Is it the same as doing it in windows forms? It sounds like it could be fun! I will have to look into it!

Many thanks again I appreciate any input whatsoever !!!!

Here is my code I am sorry it is not the neatest, I am still editing it a lot so there will be commented chunks of code here and there and some gaps:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;
using System.Threading;
using IrrKlang;
using System.IO;


//LATEST!!!!!!!!!!!!!!!!!!
namespace SpaceInvaders
{

    public partial class MainScreen : Form
    {

        public ISoundEngine ontheway = new ISoundEngine();
        public ISoundEngine heartbeat = new ISoundEngine();
        public ISoundEngine bckmusic = new ISoundEngine();
        public ISoundEngine imhit = new ISoundEngine();
        public SoundPlayer levelsound = new SoundPlayer(Properties.Resources.levelup);// This plays a sound when the player reaches a level threshold and the game stops to re-setup
        public SoundPlayer gamedone = new SoundPlayer(Properties.Resources.gameoversound);
     

        int rapidkills = 0;
        int kills = 0;
        int threshold = 1;
        int level1 = 400,// Initialising the scores for each level individually, when the score is reached the level is complete
         level2 = 800,
         level3 = 1200,
         level4 = 1600,
         level5 = 20000,
         level6 = 2400,
         level7 = 2800,
         level8 = 3200;
        int framecount = 0;
        int grenadamount = 1;
        int flashbangamount = 200;
        int highscore = 0;
        int Score = 0;
        int playerfire = 0;

        List<Enemy> baddie;// declaring the enemy list

        bool paused = true; //bool to define if the game is paused initially set to true
        Player player;      //instance of the player class
        Alien alien;        //instance of the alien class
        Boss boss;          //instance of the boss class
        Enemy enemy;        //instance of the enemy class
        Care_package cp;    //Instance of the car package class which is a helicopter that drops a bullet, which is the care package reward

        public MainScreen()
        {
            InitializeComponent(); //sets up the form

            



            player = new Player(pictureBox1, GamePanel); //creates an instance of the player class
            alien = new Alien(pictureBox1, GamePanel);   //creates an instance of the Alien class
            enemy = new Enemy(pictureBox1, GamePanel);  //creates an instance of the Enemy class
            boss = new Boss(pictureBox1, GamePanel);    //creates an instance of the Boss class
            cp = new Care_package(pictureBox2, GamePanel);
 
          

          


          
         
              
                //("GET READY TO PLAY MODERN SPACE INVADERS WARFARE VI!! \n \n HERE ARE THE KEYBOARD CONTROLS: \n \n A = LEFT \n \n D = RIGHT \n \n S = FIRE \n \n E = GRENADE  YOU ONLY HAVE ONE OF THESE, THEY ARE SPECIAL, THEY ARE AWESOME!!! \n \n Q = FLASHGANG GRENADE, YOU GET TWO OF THESE, THEY WILL STUN THE ENEMIES AND STOP THEM MOVING FOR A WHILE!!  \n \n GET THREE KILLS TO ACTIVATE A CARE PACKAGE, A HELICOPTER WILL DROP DOWN A PACKAGE WITH A RANDOM SURPRISE INSIDE!!!  \n \n GOOD LUCK!!!!!");// First thing to happen, instructions on using the keys
            setupgame();// Calls the setup game method, which holds everything that builds the space invaders game
        }

        

        private void setupgame() // This is the section of code that set up the game, the enemies in the game panel and contains the code that generates the score
        {
           
           
            kills = 0;
            if (baddie != null) // If the enemy exists, for each enemy call the method end which gets rid of the enemies and plays a level up sound
            {
                foreach (Enemy a in baddie)// For every object created from Enemy called baddie
                {
                    GamePanel.Controls.Clear();// The game panel is cleared
                    GamePanel.Controls.Add(pictureBox1);// The picturebox called picturebox1 which hold sthe objects pictures
                    a.levelend(); // The level end method which is in the enemy clas
                }
            }

            baddie = new List<Enemy>(); //  A list which creates the enemeies, each object gets a new picture box, set to the game panel and a unique position

            baddie.Add(new Martian(new PictureBox(), GamePanel, new Point(100, 60))); // The collection of enemies that will be created when setting up the game
            baddie.Add(new Martian(new PictureBox(), GamePanel, new Point(300, 60)));
            baddie.Add(new Martian(new PictureBox(), GamePanel, new Point(500, 60))); // The Martians
            baddie.Add(new Mercurian(new PictureBox(), GamePanel, new Point(100, 200))); // The mercurians are set to sleep for a short time so they are not created simultaneously and therefore fire at different times
            Thread.Sleep(50);
            baddie.Add(new Mercurian(new PictureBox(), GamePanel, new Point(300, 200)));
            Thread.Sleep(50);
            baddie.Add(new Mercurian(new PictureBox(), GamePanel, new Point(500, 200)));
            Thread.Sleep(50);
            baddie.Add(new Vesuvian(new PictureBox(), GamePanel, new Point(100, 340))); // The Vesuvians
            baddie.Add(new Vesuvian(new PictureBox(), GamePanel, new Point(300, 340)));
            baddie.Add(new Vesuvian(new PictureBox(), GamePanel, new Point(500, 340)));
            baddie.Add(new Meteor(new PictureBox(), GamePanel));                         // The Meteor    
            baddie.Add(new Destroyer(new PictureBox(), GamePanel));                      // The Destroyer
            baddie.Add(new Mothership(new PictureBox(), GamePanel, new Point(0, 0)));    // The Mothership

            GamePanel.Refresh();
  
        }// End setup game method


        int level = 1;// Initialise the Level to 1, as the first level is of course 1

        private void levelup()// The level up method that dictates a threshhold in which if a score is met where the variables per level are met the level increases.
        {
           
            switch (level)// Level threshold is set to a high number in case John Issacs gets hooked and wants to reach a high score while giving me an A20 for creating such an addictive game
            {
                case 1: threshold = level1;
                    break;

                case 2: threshold = level2;
                    break;

                case 3: threshold = level3;
                    break;

                case 4: threshold = level4;
                    break;

                case 5: threshold = level5;
                    break;

                case 6: threshold = level6;
                    break;

                case 7: threshold = level7;
                    break;

                case 8: threshold = level8;
                    break;
            }

            if (Score >= threshold)// This is where the levels is incremented by one if the threshold of a specific level is passed.
            {
                level++;// Add one to the level
                player.Lives++;// The lives increase by one per level up as a little bonus to the player
                lbllevel.Text = " " + level.ToString();// Update the level number in the label that holds the score
                player.grenade.active = false;
                paused = true;// Pausing the game to display the message box
                levelsound.Play();
                //MessageBox.Show("WELL DONE!! YOU COMPLETED THE LEVEL AND HAVE BEEN AWARDED AN EXTRA LIFE!!! \n \n PRESS OK TO BEGIN THE NEXT LEVEL CHAMP!");// Displaying the message box, indicating the next level will begin after pressing ok



                //GamePanel.Controls.Clear();
                //GamePanel.Controls.Add(pictureBox3);
               
                //pictureBox3.Visible = true;
                
                //GamePanel.Refresh();
              
                //for (int i = 0; i < 600; i++)
                //{
                //    pictureBox3.Refresh();

                //}

                //Thread.Sleep(500);
                //GamePanel.Controls.Remove(pictureBox3);


                //paused = false;// Once ok is pressed the game unpauses and continues



                setupgame();// This runs everything in the setup game method and creates the game from scratch
            }
        }// End level up method

      

        //this is the game loop, it controls what happens when the game is running this is where objects update and refreshes
        private void GamePanel_Paint(object sender, PaintEventArgs e)
        {
            
           
           
            if (!paused)// If the game has not been paused
            {

                cp.Update();
                player.Update(); //update the player
                boss.Update();  //update the Boss enemy
                alien.Update(); //update the Alien enemy
                enemy.Update();

                if (kills == 3)// THIS ACTIVATES THE CARE PACKAGE COPTER TO DROP A CARE PACKAGE
                {
                    cp.Active = true;
                    kills = 0;
                    ontheway.Play2D("ontheway.wav");

                }

                if (rapidkills == 5)// if the player gets five kills with rapd fire, return the bullet speed back to slower speed
                {
                    player.bullet.speed = 5;
                }

                if (playerfire == 5)// if the player has fired 5 times, the enemies are no longer stunned
                {
                    foreach (Enemy b in baddie)// A for each loop that will call methods to move each created object in the list and update each object
                    {  
                        b.Speed -= 100;
                    }
                    playerfire = 0;
                }
                //---------------------------------The Enemy Interface in action----------------------The Enemy Interface in action-------------------The Enemy Interface in action-----------------

                foreach (Enemy a in baddie)// A for each loop that will call methods to move each created object in the list and update each object
                {
                    a.Move();   // Move the baddie object
                    a.Update(); // Update the baddie object

                    if (a is I_can_shoot1)// If the baddie object has an interface allowing them to shoot then the following code applies
                    {
                        if (((I_can_shoot1)a).bullet.active == false)// If the enemy has not already fired
                        {
                            ((I_can_shoot1)a).shoot();// The enemy can shoot
                        }
                        else
                        {
                            ((I_can_shoot1)a).bullet.Update();// update the enemy's bullet
                        }
                        if (a is I_can_cloak)// If an enemy has the cloak interface then is given ability to cloak
                        {
                            if (framecount > 50)// If the frame count is greater than 50 then the enemy can call the cloaking random method, then the frae counter is reset, this reduces the amount of cloaking which is better than a strobe effect kind of cloaking
                            {
                                ((I_can_cloak)a).cloakrandom();
                                framecount = 0;
                            }
                        }

                        //----------------------------------COLLISION DETECTION----------------------------COLLISION DETECTION----------------------COLLISION DETECTION-----------------

                        if (bulletcollision(player.Picture, ((I_can_shoot1)a).bullet))// If there is a collision between the position of the players picture and the Enemy's bullet picture
                        {
                            GamePanel.BackColor = Color.Red;  // Change back colour to red as the player is hit, like in the Call of Duty game
                            GamePanel.Refresh();
                            player.Lives--;// Decrement the players lives
                            imhit.Play2D("ouch.wav");// Sound of player being hit and losing a life
                            heartbeat.Play2D("heartbeat.wav");
                            GamePanel.Controls.Remove(((I_can_shoot1)a).bullet.picture);

                            if (player.Lives < 1)// If no lives left then call the gameover method
                            {
                                gameover();
                            }
                        }
                        lblLives.Text = player.Lives.ToString();// Update the players lives which are displayed in the label                    
                    }
                 // --------------------------------COLLISION DETECTION----------------------------COLLISION DETECTION----------------------COLLISION DETECTION-----------------

                    if (bulletcollision(player.Picture, cp.package))// KILLSTREAK PACKAGE
                    {
                        Random package = new Random();
                        int num = package.Next(1, 5);

                        if (num == 1)
                        {
                            grenadamount++;
                            lblgrenadeamount.Text = grenadamount.ToString();
                            cp.package.active = false;
                            GamePanel.Controls.Remove(cp.package.picture);
                            lblkillstreak.Text = "GRENADE UP" .ToString();
                        }
                        else if (num == 2)
                        {
                            player.Lives++;
                            lblLives.Text = player.Lives.ToString();
                            cp.package.active = false;
                            GamePanel.Controls.Remove(cp.package.picture);
                            lblkillstreak.Text = "LIVES UP" .ToString();
                        }

                        else if (num == 3)
                        {
                            flashbangamount++;
                            lblflashbangamount.Text = flashbangamount.ToString();
                            cp.package.active = false;
                            GamePanel.Controls.Remove(cp.package.picture);
                            lblkillstreak.Text = "FLASHBANG UP" .ToString();
                        }

                        else if (num == 4)
                        {
                            rapidkills = 0;
                            if (rapidkills != 5)
                            {
                                player.bullet.speed = -5;
                                cp.package.active = false;
                                GamePanel.Controls.Remove(cp.package.picture);
                                lblkillstreak.Text = "RAPID FIRE"  .ToString();
                            }
                        }

                        else if (num == 5)
                        {
                            lblkillstreak.Text = "SHIT IT'S EMPTY".ToString();
                        }
                    }

                    //----------------------------------COLLISION DETECTION----------------------------COLLISION DETECTION----------------------COLLISION DETECTION-----------------

                    if (bulletcollision(a.picture, player.bullet))//If the enemy collides with the players bullet then is is removed
                    {
                        if (a is Alien)
                        {
                            a.position = new Point(100, 100);
                            GamePanel.Controls.Remove(player.bullet.picture);
                            Score = Score + a.GetScore();
                            lblScore.Text = Score.ToString();
                            kills++;
                            rapidkills++;
                           
                           
                        }
                        else if (a is Boss)
                        {
                            a.Die();

                            if (a.active == false)
                            {
                                GamePanel.Controls.Remove(a.picture);
                                GamePanel.Controls.Remove(player.bullet.picture);
                                Score = Score + a.GetScore();
                              
                                lblScore.Text = Score.ToString();
                                kills++;
                                rapidkills++;
                            }
                            GamePanel.Controls.Remove(player.bullet.picture);
                        }
                        else
                        {
                            a.Die();
                            GamePanel.Controls.Remove(player.bullet.picture);
                            Score = Score + a.GetScore();
                            lblScore.Text = Score.ToString();
                            kills++;
                            rapidkills++;
                        }
                    }

                    //----------------------------------COLLISION DETECTION----------------------------COLLISION DETECTION----------------------COLLISION DETECTION-----------------

                    if (grenadecollision(a.picture, player.grenade))//If the enemy collides with the players bullet then is is removed
                    {
                        if (a is Alien)
                        {
                            a.position = new Point(100, 100);
                            Score = Score + a.GetScore();
                            lblScore.Text = Score.ToString();
                        }

                        else if (a is Boss)
                        {
                            a.Die();
                            if (a.active == false)
                            {
                                GamePanel.Controls.Remove(a.picture);
                                Score = Score + a.GetScore();
                                lblScore.Text = Score.ToString();
                            }
                        }
                        else
                        {
                            a.Die();
                            Score = Score + a.GetScore();
                            lblScore.Text = Score.ToString();
                        }
                    }

                    //----------------------------------COLLISION DETECTION----------------------------COLLISION DETECTION----------------------COLLISION DETECTION-----------------

                    
                    if (flashbangcollsion(a.picture, player.flashbang))
                    {
                       
                        foreach (Enemy b in baddie)// A for each loop that will call methods to move each created object in the list and update each object
                        {
                            
                            GamePanel.BackColor = Color.White;
                            b.Speed += 100;
                            GamePanel.Controls.Remove(player.flashbang.picture);
                        }

                        
                      
                    }

                    //----------------------------------COLLISION DETECTION----------------------------COLLISION DETECTION----------------------COLLISION DETECTION-----------------

                    if (((player.Picture.Location.X >= a.picture.Location.X)
                            || (player.Picture.Location.X + player.Picture.Width >= a.picture.Location.X))

                            && ((player.Picture.Location.X < a.picture.Location.X + a.picture.Width) //and bullet's X position is within enemy's pic width size
                            || (player.Picture.Location.X + player.Picture.Width < a.picture.Location.X + a.picture.Width))   //or bullet's pic width size is within enemy's pic width size

                            && ((player.Picture.Location.Y >= a.picture.Location.Y)  //and bullet's Y position is within enemy's Y position
                            || (player.Picture.Location.Y + player.Picture.Height >= a.picture.Location.Y))   //or bullet's pic height size is within enemy's Y position

                            && ((player.Picture.Location.Y < a.picture.Location.Y + a.picture.Height)    //and bullet's Y position is within enemy's pic height size
                            || (player.Picture.Location.Y + player.Picture.Height < a.picture.Location.Y + a.picture.Height))

                            ||(a.picture.Location.Y + a.picture.Height == GamePanel.Bottom))// If an enemy hits the ground the player loses a life and the enemy dies awarding the player the points for that enemy

                    {
                        a.Die();
                        player.Lives--;// Decrement the players lives
                        GamePanel.BackColor = Color.Red;  // Change back colour to red as the player is hit, like in the Call of Duty game
                        imhit.Play2D("ouch.wav");/// Sound of player being hit and losing a life
                        heartbeat.Play2D("heartbeat.wav");

                        if (player.Lives < 1)// If no lives left then call the gameover method
                        {
                            gameover();
                        }

                        Score = Score + a.GetScore();
                        lblScore.Text = Score.ToString();
                        lblLives.Text = player.Lives.ToString();// Update the players lives which are displayed in the label
                    }
                }// End the for each enemy loop



                for (int i = 0; i < baddie.Count; i++)
                {
                    if (!baddie[i].active)
                    {
                        baddie.Remove(baddie[i]);
                    }
                }

                GamePanel.Invalidate();  //invalidate the gamepanle so it is redrawn
                levelup();// Call the level up method, its time for a new level!

                framecount++;// Counting the frames so the cloaking enemy knows when to cloak, i.e. after 50 frames
            }
            GamePanel.BackColor = Color.Black;// Change back colour back to black

        }//--------------------------------- END GAME PANEL PAINT--------------------------- END GAME PANEL PAINT--------------------- END GAME PANEL PAINT-----------------

        private void gameover()// This method is called when the player runs out of lives
        {
            paused = true;// Pause the game
            if ((player.Lives == 0) && (Score > highscore))
            {
                highscore = Score;
                lblHighScore.Text = highscore.ToString();
            }

            gamedone.Play();// Play game over sound
            MessageBox.Show("game over insert coin");// Display a fancy message, retro style
            Application.Restart();//Re start the whole application, even if no coinn was inserted

        }

        private bool bulletcollision(PictureBox picture, Bullet bullet)// A generic bullet collision detection method which can be used for both the player and enemies bullets, this returns either true or false
        {
            if (bullet.active)// If the bullet is active then do the following code, all this is the collcion detection between the players bullet and the enemies on screen
            {

                if (((bullet.picture.Location.X >= picture.Location.X)
                            || (bullet.picture.Location.X + bullet.picture.Width >= picture.Location.X))

                            && ((bullet.picture.Location.X < picture.Location.X + picture.Width) //and bullet's X position is within enemy's pic width size
                            || (bullet.picture.Location.X + bullet.picture.Width < picture.Location.X + picture.Width))   //or bullet's pic width size is within enemy's pic width size

                            && ((bullet.picture.Location.Y >= picture.Location.Y)  //and bullet's Y position is within enemy's Y position
                            || (bullet.picture.Location.Y + bullet.picture.Height >= picture.Location.Y))   //or bullet's pic height size is within enemy's Y position

                            && ((bullet.picture.Location.Y < picture.Location.Y + picture.Height)    //and bullet's Y position is within enemy's pic height size
                            || (bullet.picture.Location.Y + bullet.picture.Height < picture.Location.Y + picture.Height)))
                {
                    bullet.active = false;// The bullets is set to inactive
                    return true;

                }

            }
            return false;
        }

        private bool grenadecollision(PictureBox picture, Grenade grenade)// A generic bullet collision detection method which can be used for both the player and enemies bullets, this returns either true or false
        {
            if (grenade.active)// If the bullet is active then do the following code, all this is the collcion detection between the players bullet and the enemies on screen
            {
                if (((grenade.picture.Location.X >= picture.Location.X)
                            || (grenade.picture.Location.X + grenade.picture.Width >= picture.Location.X))

                            && ((grenade.picture.Location.X < picture.Location.X + picture.Width) //and bullet's X position is within enemy's pic width size
                            || (grenade.picture.Location.X + grenade.picture.Width < picture.Location.X + picture.Width))   //or bullet's pic width size is within enemy's pic width size

                            && ((grenade.picture.Location.Y >= picture.Location.Y)  //and bullet's Y position is within enemy's Y position
                            || (grenade.picture.Location.Y + grenade.picture.Height >= picture.Location.Y))   //or bullet's pic height size is within enemy's Y position

                            && ((grenade.picture.Location.Y < picture.Location.Y + picture.Height)    //and bullet's Y position is within enemy's pic height size
                            || (grenade.picture.Location.Y + grenade.picture.Height < picture.Location.Y + picture.Height)))
                {
                    return true;
                }
            }
            return false;
        }

        private bool flashbangcollsion(PictureBox picture, Flashbang flashbang)// A generic bullet collision detection method which can be used for both the player and enemies bullets, this returns either true or false
        {
           
            if (flashbang.active)// If the bullet is active then do the following code, all this is the collcion detection between the players bullet and the enemies on screen
            {
                
                
                GamePanel.BackColor = Color.White;
                if (((flashbang.picture.Location.X >= picture.Location.X) || (flashbang.picture.Location.X + flashbang.picture.Width >= picture.Location.X))

                     && ((flashbang.picture.Location.X < picture.Location.X + picture.Width) //and bullet's X position is within enemy's pic width size
                      || (flashbang.picture.Location.X + flashbang.picture.Width < picture.Location.X + picture.Width))   //or bullet's pic width size is within enemy's pic width size

                         && ((flashbang.picture.Location.Y >= picture.Location.Y)  //and bullet's Y position is within enemy's Y position
                            || (flashbang.picture.Location.Y + flashbang.picture.Height >= picture.Location.Y))   //or bullet's pic height size is within enemy's Y position

                                && ((flashbang.picture.Location.Y < picture.Location.Y + picture.Height)    //and bullet's Y position is within enemy's pic height size
                                    || (flashbang.picture.Location.Y + flashbang.picture.Height < picture.Location.Y + picture.Height)))
            {
                flashbang.active = false;// The bullets is set to inactive
                playerfire = 0;
                    return true;
                }
            }
            return false;
        }



        //--------------------------------- THE BUTTONS--------------------- THE BUTTONS---------------------- THE BUTTONS----------------------


        //pauses or restarts the game
        private void button1_Click(object sender, EventArgs e)
        {
            if (paused)
            {
                paused = false;
                GamePanel.Refresh();
                bckmusic.Play2D("soundtrack2.wav", true);
                bckmusic.SetAllSoundsPaused(false);
            }
            else
            {
                paused = true;
                bckmusic.SetAllSoundsPaused(true);
            }
        }

        //the following 5 methods control the movement of the player through the button presses
        private void btnLeft_MouseDown(object sender, MouseEventArgs e)
        {
            player.MoveLeft();
        }

        private void btnRight_MouseDown(object sender, MouseEventArgs e)
        {
            player.MoveRight();
        }

        private void btnLeft_MouseUp(object sender, MouseEventArgs e)
        {
            player.StopMovingLeft();
        }

        private void btnRight_MouseUp(object sender, MouseEventArgs e)
        {
            player.StopMovingRight();
        }

        private void btnFire_Click(object sender, EventArgs e)
        {
            player.Shoot();
            playerfire++;
        }

        private void btngrenade_Click(object sender, EventArgs e)
        {
            if (grenadamount > 0)
            {
                player.Shoot2();
                grenadamount--;
                lblgrenadeamount.Text = " " + level.ToString();
            }
        }

        private void btnflashbang_Click(object sender, EventArgs e)
        {
            

            if (flashbangamount > 0)
            {
                player.Shoot3();
                flashbangamount--;
                lblflashbangamount.Text = " " + level.ToString();
            }
        }


        private void MainScreen_Load(object sender, EventArgs e)
        {


        }

        private void lblScore_Click(object sender, EventArgs e)// This is the label that holds the score
        {
            enemy.GetScore();
        }

        private void MainScreen_KeyDown(object sender, KeyEventArgs e)// This a key event where S calls the players shoot method
        {
            if (e.KeyCode == Keys.S)
            {
                player.Shoot();
                playerfire++;
            }

            if (e.KeyCode == Keys.E)
            {
                if (grenadamount > 0)
                {
                    player.Shoot2();
                    grenadamount--;
                    lblgrenadeamount.Text = grenadamount.ToString();
                }
            }
            if (e.KeyCode == Keys.Q)
            {
               
                if (flashbangamount > 0)
                {
                    player.Shoot3();
                    flashbangamount--;
                    lblflashbangamount.Text = flashbangamount.ToString();
                }
            }


            else if (e.KeyCode == Keys.A)// This a key event where A keydown calls the players move left method
            {
                player.MoveLeft();
            }

            else if (e.KeyCode == Keys.D)// This a key event where D keydown calls the players move right method
            {
                player.MoveRight();
            }
        }

        private void MainScreen_KeyUp(object sender, KeyEventArgs e)// These key up events stop calling the key down events for moving the player
        {
            if (e.KeyCode == Keys.A)
            {

                player.StopMovingLeft();
            }

            else if (e.KeyCode == Keys.D)
            {
                player.StopMovingRight();
            }
        }

        private void lblgrenadeamount_Click(object sender, EventArgs e)
        {

        }

        //--------------------------------LOAD SAVE LOAD SAVE---------------LOAD SAVE LOAD SAVE------------------LOAD SAVE LOAD SAVE-------------------

        private void btnload_Click(object sender, EventArgs e)
        {
            paused = true;  //pause the game
            OpenFileDialog op = new OpenFileDialog();   //creates an OpenFileDialog
            op.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //default open directory

            op.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; //text filter
            op.FileName = "saved_game.txt";   //default filename shown
            op.CheckFileExists = true;
            op.CheckPathExists = true;

            DialogResult result = op.ShowDialog();
            if (result == DialogResult.OK)  //if the dialogbox's OK button is pressed
            {
                using (StreamReader sr = new StreamReader(op.FileName)) //creates a StreamReader
                {
                    while (!sr.EndOfStream)  //while not at the end of the stream, set values of highscore, score, and lives
                    {
                        lblHighScore.Text = sr.ReadLine();
                        lblScore.Text = sr.ReadLine();
                        lblLives.Text = sr.ReadLine();
                        lbllevel.Text = sr.ReadLine();
                    }
                }

                highscore = int.Parse(lblHighScore.Text);   //set highscore's value to saved highscore value
                Score = int.Parse(lblScore.Text);           //set score's value to saved score value
                player.Lives = int.Parse(lblLives.Text);    //set lives's value to saved lives value
                level = int.Parse(lbllevel.Text);           //set level's value to saved level value
                setupgame();                            //Re-create enemies

            }//close the StreamReader
        }

        private void btnsave_Click(object sender, EventArgs e)
        {
            paused = true;  //pause the game
            SaveFileDialog save = new SaveFileDialog();   //creates a SaveFileDialog
            save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //default open directory

            save.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; //text filter
            save.FileName = "saved_game.txt";   //default filename shown
            save.CheckPathExists = true;

            DialogResult result = save.ShowDialog();
            if (result == DialogResult.OK)  //if the dialogbox's OK button is pressed
            {
                using (StreamWriter sw = new StreamWriter(save.FileName)) //creates a StreamWriter
                {
                    if (player.Lives <= 0)  //if the player has lost, only highscore's value is saved
                    {
                        sw.WriteLine(highscore);    //write the value of highscore
                        sw.WriteLine(0);            //reset value of score back to 0
                        sw.WriteLine(3);            //reset value of lives back to 3
                        sw.WriteLine(1);            //reset value of level back to 1
                    }
                    else    //else, save the values normally
                    {
                        sw.WriteLine(highscore);    //write the value of highscore
                        sw.WriteLine(Score);        //write the value of score
                        sw.WriteLine(player.Lives); //write the value of lives
                        sw.WriteLine(level);        //write the value of level
                    }
                }
            }
        }

        private void pictureBox3_Click(object sender, EventArgs e)
        {

        }


    }
}

Thanks!!!!!!!!!!!!!!!!

I see, it appears that the all your trouble stems from the fact that you are doing all your game logic in the paint event.

All your frame advance type game logic should be handled in a timer event or something, NOT the panels paint event.

every time anything moves or changes in or over the panel, the paint event gets called, and it should ONLY handle DRAWING for the panel. Since you are using pictureboxes for most of your characters and such they handles thier own redraws, thats the only reason this works at all.

create a timer timer that fires how ever many millisecons you want your frame difference to be, and on its Tick event put practically all that code that you have in the game panel's tick event. then when the game starts, be sure to start the timer and then your panel's background should be fine.

during that paint event, that's what draws the background on the panel, its sealed in the Panel class and happens before anything you added there, but it isn't update til all that's code runs. Pain events are for PAINTING! remember that and you will see a big performance increase.

More on XNA, xna is in C#, but supports 2 different drawing systems, a specialed managed directX which lets you use the client's graphics card to make the game run faster. and then a 2d drawing system that is 1000 times more efficient than using GDI+ and windows naive controls for game graphics. I personally don't do much game development. I could do the coding, I just don't have the original ideas or talent in the art department :)

Post us a link to your game when you get a solid demo rolling :) Good luck

Diamonddrake, many thanks for all your help. Can I ask you a huge favour, I read your post three times then attempted to try your suggestion, but when I add this in my class

Timer myTimer = new Timer();

I get this error:

'Timer' is an ambiguous reference between 'System.Windows.Forms.Timer' and 'System.Threading.Timer'


Can I bother you for an example of how to do this, as I mentioned before this is basically my first project which I have worked on for approximately 12 hours a day for the past week, and now I am dertrmined to get your suggestion working, but I feel I may need a bit more help to do this.

Do a I get the ambiguity error due to already having a thread.sleep in my code?

I think I understand the idea you have with making the game refresh using a timer instead of invalidating the game panel, but I'm afraid this may be too difficult for me at this moment. It would be incredible to achieve this, as since I started this project I have been so limited due to slowness of the game, this was initially coursework for university which I completed but I just had so many ideas athat I wanted to implement and the game has taken over my holiday! :)

I appreciate any further help, I want to learn how to complete my ideas and I'll never give up.

I will of course share the finished result as it will be my pride and joy!

:)

as for the XNA, maybe this would be something for me to think about as I really enjoy coding since I am getting better at it and achieving more and more, it's becoming a great hobby of mine, i just wish that I was as good at programming as you pro's out there!


Cheers!!!!!!!!!!

The error is due to a namespace conflict. at the top of your class the using statements that are in place are there to limit the amount of typing you have to do. Since you have a "system.windows.forms" and a "system.threading" using declarations, in order to disambiguate you will have to use the full namespace to the timer basically you just have to use

System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

The game will still likely be slow, just because its a GDI and winforms control based game. But it should drastically speed the game up. It would be better if you used directX or XNA but both of which would require a total rewrite and you would have a lot of learning to do before you could actually start writing reliable code.

Programming is a great hobby, but as the human condition goes, there will always be someone way better than you, no matter how good you are. And with programming, you can be a great great at one thing, and suck at another. I love programming and have enjoyed doing it for the past 3 years or so, started as a hobby, still is for the most part. I sold an automation app to a multi-international corporation that designs and manufactures stoves so technically I am a pro :) but only technically. lol

The guys to look out for here in the C# department are sknake, ddanbe, adatapost, and Ryshad many people make good contributions these are just the ones I trust the most, not to mention myself.

good luck!

Wow that is pretty amazing, you started programming a few years ago as a hobby and you eventually sold software to a company? That is nuts! I am at university in my second year of a Computing degree, it covers the major computing technologies, and they are all manageable but programming was something I was so worried I would never understand it as it just seems too complicated and difficult, turns out all I needed was some coursework that I was really interested in and could have fun with, this game!

As for the game I have given up, I have spent too much time on it and it would take me forever to figure out how to try your method with the timer, thanks for the tip with using a full namespace for disambiguation, I will rememeber that! It got rid of the errors but I've not used timers before I looked online found some code and experimented all morning, trying to get the game panel code to refresh on a timer as oppossed to constantly using invalidate.

I appreciate your help and advice, take it easy!!!


Ray

if you post your project, I will take a look at it. See if I can integrate it for you.

I didn't have the finances to go to school, but hopefully I will soon. I'm 23, I see the software I marketed to be a sign that I have what it takes, but there is a long way for me to go. Really I should get into games, that seems to be the future of the programming industry. That's all that really sells these days, I'm thinking of getting into programming for the android and windows phone 7. Maybe I can make some money. :)

Cheers Diamonddrake, that would be awesome if you could have a look at it, I'd really appreciate it! I'd love to see what you could do with it!

I am 32 and I worked for years in the building trade and I just knew I had to better my life, so as I love computers so much I decided to do this course, but is its costing me an absoulte fortune, lets just hope that it pays off. I am going to the USA in may for four months to work during the summer holiday and I am applying to complanies everywhere trying to get an internship, if I can't get one I'll just do a casual job, it will be an experience anyway. I wanted to get into games development but apparantly its not a well paying industry to be in? I don't know how that can be the case as the guys who develop games must be amazing programmers! I've seen how difficult this little game I made but as its my first project it may just be that time will get me better at coding. So how did you manage to teach yourself C#? wasn't that difficult to do?

I dont know how to post my whole project on the forum so I uploaded a zipped file which is about 30mb to megaupload, hopefully the link works!

Also I have to add I added a third party library for a sound engine to the game, I don't know if you need to know this or not.

Here is the link to my project

http://www.megaupload.com/?d=4IAMGIMT

if you have any problems or want to contact me directly my email address is:

Diamonddrake, you are a star, thanks a lot!


Ray

I am downloading it now, I taught myself through books, trial and error, codeproject articles and from help of people here on daniweb. C# is an easy language. Programming is a challenge. I guess that's why I do it.

Ok, putting all your logic code that was in the on paint into the timer event was very simple, just a copy and paste and it worked without a fuss. still flickered with a bacground and then I found that you were invalidating the panel from the paint event (you should never do that) So i removed that call from the logic loop and now the background doesn't flicker.

the move speeds need to be modified but other than that, it does seem to work.

I'll email it to you.

Ok, putting all your logic code that was in the on paint into the timer event was very simple, just a copy and paste and it worked without a fuss. still flickered with a bacground and then I found that you were invalidating the panel from the paint event (you should never do that) So i removed that call from the logic loop and now the background doesn't flicker.

the move speeds need to be modified but other than that, it does seem to work.

I'll email it to you.

Wow that didnt take you long at all!! Thanks so much!!

Have you emailed it already, it hasn't arrived if you have sent it mate. Well done for helping me out I really appreciate it!! Can't wait to see it!!

Ray

My email provider refused to send the attachment because of its file size, I have uploaded it to megaupload you can find it here

Thanks mate I have downloaded it and am looking at it now, it is what I wanted, the background is in there, I will get the moving sorted out hopefully.

Thanks for all your help with this adn your time.

Cheers!!!!!!!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.