12 Replies - 636 Views - Last Post: 21 May 2020 - 06:42 AM Rate Topic: -----

#1 brean   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 18-May 20

Snake game in Windows forms

Posted 18 May 2020 - 06:13 AM

I wrote a snake game, but I have questions and problems:
1. The painted walls disappear after eating first fruit.
2. How to make the game end wwhen the snake touches the painted walls?
3. When a snake dies (or click the stop button), data: date, player name, score, etc. should be saved, but an exception is thrown to me.
4. I don't understand how to make new fruit is generated if the snake doesn't eat this in 30 seconds?
5. Also in the task, I need to make a change of levels when typing a units of snake length(the snake returns to its start position and to its start length (3 units), fruit and walls are regenerated). Levels are considered by the formula a = a + a / 3. first value a = 15.
Sorry, if I I have mistakes, English isn't my native language.

Is This A Good Question/Topic? 0
  • +

Replies To: Snake game in Windows forms

#2 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Snake game in Windows forms

Posted 18 May 2020 - 06:18 AM

You must provide some relevant code, posted between code tags.

If there are exceptions then, again, provide the exception details, and confirm which line(s) of code produce the exception(s).
Was This Post Helpful? 0
  • +
  • -

#3 brean   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 18-May 20

Re: Snake game in Windows forms

Posted 18 May 2020 - 06:19 AM

View Postbrean, on 18 May 2020 - 06:13 AM, said:

I wrote a snake game, but I have questions and problems:
1. The painted walls disappear after eating first fruit.
2. How to make the game end wwhen the snake touches the painted walls?
3. When a snake dies (or click the stop button), data: date, player name, score, etc. should be saved, but an exception is thrown to me.
4. I don't understand how to make new fruit is generated if the snake doesn't eat this in 30 seconds?
5. Also in the task, I need to make a change of levels when typing a units of snake length(the snake returns to its start position and to its start length (3 units), fruit and walls are regenerated). Levels are considered by the formula a = a + a / 3. first value a = 15.
Sorry, if I I have mistakes, English isn't my native language.

Link for downloading the archive:https://drive.google.com/file/d/1WjzvVqhPk1Yzap7hEd8zRh-q_4ksApU1/view?usp=sharing
Was This Post Helpful? 0
  • +
  • -

#4 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Snake game in Windows forms

Posted 18 May 2020 - 06:20 AM

How To Ask Questions The Smart Way

N.B. A link for downloading an archive is not suitable, post relevant code directly here in the forum.
Was This Post Helpful? 0
  • +
  • -

#5 brean   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 18-May 20

Re: Snake game in Windows forms

Posted 18 May 2020 - 06:24 AM

View Postandrewsw, on 18 May 2020 - 06:18 AM, said:

You must provide some relevant code, posted between code tags.

If there are exceptions then, again, provide the exception details, and confirm which line(s) of code produce the exception(s).

I gave a link to the archive with the program in a new message.

View Postandrewsw, on 18 May 2020 - 06:20 AM, said:

How To Ask Questions The Smart Way

N.B. A link for downloading an archive is not suitable, post relevant code directly here in the forum.

But I have data base in my program and music
Was This Post Helpful? 0
  • +
  • -

#6 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Snake game in Windows forms

Posted 18 May 2020 - 06:26 AM

We aren't going to download and debug your entire program. Provide the relevant code that shows where you have problems.
Was This Post Helpful? 0
  • +
  • -

#7 brean   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 18-May 20

Re: Snake game in Windows forms

Posted 18 May 2020 - 06:58 AM

I wrote a snake game, but I have questions and problems:
1. The painted walls disappear after eating first fruit.
private void drawwall()
        {
            Random rnd = new Random();
            int numwall = rnd.Next(3, 10);
            for (int a = 1; a < numwall; a++)
            {
                int ranX = rnd.Next(50) * 15;
                int ranY = rnd.Next(42) * 15;

                int wallrnd = rnd.Next(2, 7);
                wallparts = new PictureBox[wallrnd];
                int xy = rnd.Next(1, 3);
                if (xy == 1)
                {
                    for (int i = 0; i < wallrnd; i++)
                    {
                        wallparts[i] = new PictureBox();
                        wallparts[i].Size = new Size(15, 15);
                        wallparts[i].BackColor = Color.Brown;
                        wallparts[i].BorderStyle = BorderStyle.FixedSingle;
                        wallparts[i].Location = new Point(ranX - (15 * i), ranY);
                        GamePanel.Controls.Add(wallparts[i]);

                    }
                }
                else {
                    for (int i = 0; i < wallrnd; i++)
                    {
                        wallparts[i] = new PictureBox();
                        wallparts[i].Size = new Size(15, 15);
                        wallparts[i].BackColor = Color.Brown;
                        wallparts[i].BorderStyle = BorderStyle.FixedSingle;
                        wallparts[i].Location = new Point(ranX, ranY - (15 * i));
                        GamePanel.Controls.Add(wallparts[i]);

                    }
                }
            }
            
        }


2. How to make the game end when the snake touches the painted walls?
//snake hits drawwall
            if (snakeParts[0].Location.X ==wallparts[0].Location.X || snakeParts[0].Location.Y == wallparts[0].Location.Y)
            {
                stopgame();
            }

3. When a snake dies (or click the stop button), data: date, player name, score, etc. should be saved, but an exception is thrown to me.
https://drive.google...iew?usp=sharing (picture with description)
4. I don't understand how to make new fruit is generated if the snake doesn't eat this in 30 seconds?
5. Also in the task, I need to make a change of levels when typing a units of snake length(the snake returns to its start position and to its start length (3 units), fruit and walls are regenerated). Levels are considered by the formula a = a + a / 3. first value a = 15.
Sorry, if I I have mistakes, English isn't my native language.
All code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Schema;


namespace Snake
{
    public partial class Snake : Form
    {
        SoundPlayer sp = new SoundPlayer();

        Timer myTimer = new Timer();
        //Snake def
        PictureBox[] snakeParts;
        int snakesize = 3;
        Point location = new Point(120, 120);
        string direction = "Right";
        bool changingDirection = false;
        //fruit def
        PictureBox food = new PictureBox();
        Point foodlocation = new Point(0, 0);
        PictureBox[] wallparts;

        //database
        static String path = Path.GetFullPath(Environment.CurrentDirectory);
        static String dataBaseName = "date.mdf";
        string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + @"\" + dataBaseName + "; Integrated Security=True";
        public Snake()
        {
            InitializeComponent();
         
        }
            
        void myTimer_Tick(object sender, EventArgs e)
        {
            int currentScores = Int32.Parse(Score_count.Text);
            int newScore = currentScores + 1;
            Score_count.Text = newScore + "";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            stopgame();
        }

        private void Start_Click(object sender, EventArgs e)
        {
            //play again
            GamePanel.Controls.Clear();
            snakeParts = null;
            Score_count.Text = "0";
            level_count.Text = "1";
            fruit_count.Text = "0";
            snakesize = 3;
            direction = "Right";
            location = new Point(120, 120);
            //start game
            drawsnake();
            drawfood();
            drawwall();
            timer1.Start();
            //control
            trackBar1.Enabled = false;
            Start.Enabled = false;
            namebox.Enabled = false;
            //enable pause
            Pause.Enabled = true;
            // timer +1 on
            myTimer.Interval = 1000;
            myTimer.Enabled = true;
            myTimer.Tick += myTimer_Tick;
            myTimer.Start();
            //snake long label
            longlabel.Text = snakesize + "";


        }

        private void drawsnake()
        {
            snakeParts = new PictureBox[snakesize];

            //one part after another
            for (int i = 0; i < snakesize; i++)
            {
                snakeParts[i] = new PictureBox();
                snakeParts[i].Size = new Size(15, 15);
                snakeParts[i].BackColor = Color.LawnGreen;
                snakeParts[i].BorderStyle = BorderStyle.FixedSingle;
                snakeParts[i].Location = new Point(location.X - (15 * i), location.Y);
                GamePanel.Controls.Add(snakeParts[i]);

            }

        }
        private void drawfood()
        {
            Random rnd = new Random();
            int Xrand = rnd.Next(38) * 15;
            int Yrand = rnd.Next(30) * 15;

            bool isOnSnake = true;
            // chek food on snake
            while (isOnSnake)
            {
                for (int i = 0; i < snakesize; i++)
                {
                    if (snakeParts[i].Location == new Point(Xrand, Yrand))
                    {
                        Xrand = rnd.Next(38) * 15;
                        Yrand = rnd.Next(30) * 15;
                    }
                    else
                    {
                        isOnSnake = false;
                    }
                }
            }

            //draw food
            if (isOnSnake == false)
            {
                int col = rnd.Next(1, 6);
                foodlocation = new Point(Xrand, Yrand);
                food.Size = new Size(15, 15);
                if (col == 1)
                {
                    food.BackColor = Color.OrangeRed;
                }
                else if (col == 2)
                {
                    food.BackColor = Color.Yellow;
                }
                else if (col == 3)
                {
                    food.BackColor = Color.Violet;
                }
                else if (col == 4)
                {
                    food.BackColor = Color.Aquamarine;
                }
                else
                {
                    food.BackColor = Color.Red;
                }
                food.BorderStyle = BorderStyle.FixedSingle;
                food.Location = foodlocation;
                GamePanel.Controls.Add(food);
            }
        }

        private void drawwall()
        {
            Random rnd = new Random();
            int numwall = rnd.Next(3, 10);
            for (int a = 1; a < numwall; a++)
            {
                int ranX = rnd.Next(50) * 15;
                int ranY = rnd.Next(42) * 15;

                int wallrnd = rnd.Next(2, 7);
                wallparts = new PictureBox[wallrnd];
                int xy = rnd.Next(1, 3);
                if (xy == 1)
                {
                    for (int i = 0; i < wallrnd; i++)
                    {
                        wallparts[i] = new PictureBox();
                        wallparts[i].Size = new Size(15, 15);
                        wallparts[i].BackColor = Color.Brown;
                        wallparts[i].BorderStyle = BorderStyle.FixedSingle;
                        wallparts[i].Location = new Point(ranX - (15 * i), ranY);
                        GamePanel.Controls.Add(wallparts[i]);

                    }
                }
                else {
                    for (int i = 0; i < wallrnd; i++)
                    {
                        wallparts[i] = new PictureBox();
                        wallparts[i].Size = new Size(15, 15);
                        wallparts[i].BackColor = Color.Brown;
                        wallparts[i].BorderStyle = BorderStyle.FixedSingle;
                        wallparts[i].Location = new Point(ranX, ranY - (15 * i));
                        GamePanel.Controls.Add(wallparts[i]);

                    }
                }
            }
            
        }
        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            //change time interval
            timer1.Interval = 501 - (5 * trackBar1.Value);

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            move();

        }
        private void move()
        {
            Point point = new Point(0, 0);
            //moving each part of snake
            for (int i = 0; i < snakesize; i++)
            {
                if (i == 0)
                {
                    point = snakeParts[i].Location;
                    if (direction == "Left")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X - 15, snakeParts[i].Location.Y);
                    }
                    if (direction == "Right")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X + 15, snakeParts[i].Location.Y);
                    }
                    if (direction == "Top")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X, snakeParts[i].Location.Y - 15);
                    }
                    if (direction == "Down")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X, snakeParts[i].Location.Y + 15);
                    }
                }
                else
                {
                    Point newPoint = snakeParts[i].Location;
                    snakeParts[i].Location = point;
                    point = newPoint;
                }
            }

            //hit food
            if (snakeParts[0].Location == foodlocation)
            {
                eatfood();
                drawfood();
            }
            //if snake hits wall
            if (snakeParts[0].Location.X < 0 || snakeParts[0].Location.X >= 850 || snakeParts[0].Location.Y < 0 || snakeParts[0].Location.Y >= 480)
            {
                stopgame();
            }
            //snake hits drawwall
            if (snakeParts[0].Location.X ==wallparts[0].Location.X || snakeParts[0].Location.Y == wallparts[0].Location.Y)
            {
                stopgame();
            }
            // snake eat itself
            for (int i = 3; i < snakesize; i++)
            {
                if(snakeParts[0].Location==snakeParts[i].Location)
                {
                    stopgame();
                }
            }

            changingDirection = false;
        }
        //control snake
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Up) && direction != "Down" && changingDirection != true) 
            {
                direction = "Top";
                changingDirection = true;
            }
            if (keyData == (Keys.Down) && direction != "Top" && changingDirection != true)
            {
                direction = "Down";
                changingDirection = true;
            }
            if (keyData == (Keys.Left) && direction != "Right" && changingDirection != true)
            {
                direction = "Left";
                changingDirection = true;
            }
            if (keyData == (Keys.Right) && direction != "Left" && changingDirection != true)
            {
                direction = "Right";
                changingDirection = true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void eatfood()
        {
            Random rnd = new Random();
            int abrand = rnd.Next(1, 3);
            for (int ba = 1; ba <= abrand; ba++)
            {
                snakesize++;
                PictureBox[] oldsnake = snakeParts;
                GamePanel.Controls.Clear();
                snakeParts = new PictureBox[snakesize];
                for (int i = 0; i < snakesize; i++)
                {
                    snakeParts[i] = new PictureBox();
                    snakeParts[i].Size = new Size(15, 15);
                    snakeParts[i].BackColor = Color.LawnGreen;
                    snakeParts[i].BorderStyle = BorderStyle.FixedSingle;
                    if (i == 0)
                    {
                        snakeParts[i].Location = foodlocation;
                    }
                    else
                    {
                        snakeParts[i].Location = oldsnake[i - 1].Location;
                    }
                    GamePanel.Controls.Add(snakeParts[i]);
                }
            }

            int currentScores = Int32.Parse(Score_count.Text);
            int newScore = currentScores + 50;
            Score_count.Text = newScore+"";
            int currentfruits = Int32.Parse(fruit_count.Text);
            int newScorefr = currentfruits + 1;
            fruit_count.Text = newScorefr + "";
            int currentlong = Int32.Parse(longlabel.Text);
            int newScoreln = snakesize;
            longlabel.Text = newScoreln + "";

        }

        private void stopgame()
        {
            timer1.Stop();
            Start.Enabled = true;
            trackBar1.Enabled = true;
            Pause.Enabled = false;
            namebox.Enabled = true;
            myTimer.Stop();
            //game over text
            Label over = new Label();
            over.Text = "Game\nOver";
            over.ForeColor = Color.Maroon;
            over.Font = new Font("AgitProp", 100);
            over.Size = over.PreferredSize;
            over.TextAlign = ContentAlignment.MiddleCenter;
           
            int X = GamePanel.Width / 2 - over.Width / 2;
            int Y = GamePanel.Height / 2 - over.Height / 2;
            over.Location = new Point(X, Y);
            GamePanel.Controls.Add(over);
            over.BringToFront();
            //add current score update score board
            addCurrentScoresToDateBase();
            UpdateScoreBoard();

        }
        private void UpdateScoreBoard()
        {
            //data from datebase
            string query = "SELECT Date, Name, Score, Levels, Fruits FROM scores";
            using(SqlConnection con = new SqlConnection(connectionString))
            {
                SqlDataAdapter adapter = new SqlDataAdapter(query, con);
                var ds = new DataSet();
                adapter.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
                dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Sort(this.dataGridView1.Columns[2], ListSortDirection.Descending);


            }
        }
        private void addCurrentScoresToDateBase()
        {
            //insert score in database
            string query = "INSERT INTO scores(Date, Name, Score, Levels, Fruits);";
            using (SqlConnection con = new SqlConnection(connectionString))
                using (SqlCommand cmd = new SqlCommand(query,con))
            {
                cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = DateTime.Now;
                cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = namebox.Text;
                cmd.Parameters.Add("@Score", SqlDbType.Int).Value = Score_count.Text;
                cmd.Parameters.Add("@Levels", SqlDbType.Int).Value = level_count.Text;
                cmd.Parameters.Add("@Fruits", SqlDbType.Int).Value = fruit_count.Text;

                try
                {
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                catch(Exception)
                {
                    throw;
                }



            }
        }

        private void Snake_Load(object sender, EventArgs e)
        {
            UpdateScoreBoard();

            playmusic();
        }

        private void musicon_Click(object sender, EventArgs e)
        {
            playmusic();
        }

        private void musicoff_Click(object sender, EventArgs e)
        {
            stopmusic();
        }
        private void playmusic()
        {
            
            sp.SoundLocation = "Chill.wav";
            sp.PlayLooping();
            musicon.Enabled = false;
            musicoff.Enabled = true;
        }
        private void stopmusic()
        {
            sp.Stop();
            musicon.Enabled = true;
            musicoff.Enabled = false;
        }

     
    }
}



Was This Post Helpful? 0
  • +
  • -

#8 modi123_1   User is offline

  • Suitor #2
  • member icon



Reputation: 15781
  • View blog
  • Posts: 63,246
  • Joined: 12-June 08

Re: Snake game in Windows forms

Posted 18 May 2020 - 09:03 AM

A cursory look over seems to point if you are 'hitting food' at this line, and you are redrawing food/snake there then best to redraw the walls.

249            //hit food


Also it's a good idea to have one Random variable that is called through out and not instantiating random in a bunch of methods.
Was This Post Helpful? 0
  • +
  • -

#9 Skydiver   User is online

  • Code herder
  • member icon

Reputation: 7445
  • View blog
  • Posts: 25,082
  • Joined: 05-May 12

Re: Snake game in Windows forms

Posted 18 May 2020 - 10:17 AM

View Postbrean, on 18 May 2020 - 09:58 AM, said:

.3. When a snake dies (or click the stop button), data: date, player name, score, etc. should be saved, but an exception is thrown to me.
https://drive.google...iew?usp=sharing (picture with description)


Well according to that stack trace the error was on line 409. Unfortunately you just did a throw without detailing what failed:
        private void addCurrentScoresToDateBase()
        {
            //insert score in database
            string query = "INSERT INTO scores(Date, Name, Score, Levels, Fruits);";
            using (SqlConnection con = new SqlConnection(connectionString))
                using (SqlCommand cmd = new SqlCommand(query,con))
            {
                cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = DateTime.Now;
                cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = namebox.Text;
                cmd.Parameters.Add("@Score", SqlDbType.Int).Value = Score_count.Text;
                cmd.Parameters.Add("@Levels", SqlDbType.Int).Value = level_count.Text;
                cmd.Parameters.Add("@Fruits", SqlDbType.Int).Value = fruit_count.Text;

                try
                {
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                catch(Exception)
                {
                    throw;
                }



            }
        }



If you are not going to do anything about the exception, might as well just remove the try-catch so that the details of the exception are passed along. Chances are that the exception message would tell you exactly why you couldn't write to your database.
Was This Post Helpful? 0
  • +
  • -

#10 brean   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 18-May 20

Re: Snake game in Windows forms

Posted 19 May 2020 - 03:10 AM

I solved most of my problems, but I can't make normal draw walls. I don't need regeneration drawwalls.And I don't know how to make if snake touches drawwalls, game will be over.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Schema;


namespace Snake
{
    public partial class Snake : Form
    {
        SoundPlayer sp = new SoundPlayer();

        Timer myTimer = new Timer();
        Timer myTimer2 = new Timer();
        //Snake def
        PictureBox[] snakeParts;
        int snakesize = 3;
        Point location = new Point(120, 120);
        string direction = "Right";
        bool changingDirection = false;
        //fruit def
        PictureBox food = new PictureBox();
        Point foodlocation = new Point(0, 0);

        PictureBox[] wallparts;
        double a = 15;
        int level = 1;
        //database
        static String path = Path.GetFullPath(Environment.CurrentDirectory);
        static String dataBaseName = "date.mdf";
        string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + @"\" + dataBaseName + "; Integrated Security=True";
        public Snake()
        {
            InitializeComponent();
         
        }
            
        void myTimer_Tick(object sender, EventArgs e)
        {
            int currentScores = Int32.Parse(Score_count.Text);
            int newScore = currentScores + 1;
            Score_count.Text = newScore + "";
            int currenttime = Int32.Parse(timelabel.Text);
            int newtime = currenttime - 1;
            timelabel.Text = newtime + "";
        }
        void myTimer2_Tick(object sender, EventArgs e)
        {
            GamePanel.Controls.Remove(food);
            drawfood();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            stopgame();
        }

        private void Start_Click(object sender, EventArgs e)
        {
            //play again
            GamePanel.Controls.Clear();
            snakeParts = null;
            Score_count.Text = "0";
            level_count.Text = "1";
            fruit_count.Text = "0";
            snakesize = 3;
            direction = "Right";
            location = new Point(120, 120);
            //start game
            drawsnake();
            drawfood();
            drawwall();
            level_count.Text = "1";
            timer1.Start();
            //control
            trackBar1.Enabled = false;
            Start.Enabled = false;
            namebox.Enabled = false;
            //enable pause
            Pause.Enabled = true;
            // timer +1 on
            myTimer.Interval = 1000;
            myTimer.Enabled = true;
            myTimer.Tick += myTimer_Tick;
            myTimer.Start();

           

           
            //snake long label
            longlabel.Text = snakesize + "";


        }

        private void drawsnake()
        {
            snakeParts = new PictureBox[snakesize];

            //one part after another
            for (int i = 0; i < snakesize; i++)
            {
                snakeParts[i] = new PictureBox();
                snakeParts[i].Size = new Size(15, 15);
                snakeParts[i].BackColor = Color.LawnGreen;
                snakeParts[i].BorderStyle = BorderStyle.FixedSingle;
                snakeParts[i].Location = new Point(location.X - (15 * i), location.Y);
                GamePanel.Controls.Add(snakeParts[i]);

            }

        }
        private void drawfood()
        {
           
            Random rnd = new Random();
            int Xrand = rnd.Next(38) * 15;
            int Yrand = rnd.Next(30) * 15;

            bool isOnSnake = true;
            // chek food on snake
            while (isOnSnake)
            {
                for (int i = 0; i < snakesize; i++)
                {
                    if (snakeParts[i].Location == new Point(Xrand, Yrand))
                    {
                        Xrand = rnd.Next(38) * 15;
                        Yrand = rnd.Next(30) * 15;
                    }
                    else
                    {
                        isOnSnake = false;
                    }
                }
            }

            //draw food
            if (isOnSnake == false)
            {
                int col = rnd.Next(1, 6);
                foodlocation = new Point(Xrand, Yrand);
                food.Size = new Size(15, 15);
                if (col == 1)
                {
                    food.BackColor = Color.OrangeRed;
                }
                else if (col == 2)
                {
                    food.BackColor = Color.Yellow;
                }
                else if (col == 3)
                {
                    food.BackColor = Color.Violet;
                }
                else if (col == 4)
                {
                    food.BackColor = Color.Aquamarine;
                }
                else
                {
                    food.BackColor = Color.Red;
                }
                food.BorderStyle = BorderStyle.FixedSingle;
                food.Location = foodlocation;
                GamePanel.Controls.Add(food);
                myTimer2.Interval = 30000;
                myTimer2.Enabled = true;
                myTimer2.Tick += myTimer2_Tick;
                myTimer2.Start();

                timelabel.Text = "30";
            }
        }

        private void drawwall()
        {
            Random rnd = new Random();
            int numwall = rnd.Next(3, 10);
            for (int a = 1; a < numwall; a++)
            {
                int ranX = rnd.Next(50) * 15;
                int ranY = rnd.Next(42) * 15;

                int wallrnd = rnd.Next(2, 7);
                wallparts = new PictureBox[wallrnd];
                int xy = rnd.Next(1, 3);
                if (xy == 1)
                {
                    for (int i = 0; i < wallrnd; i++)
                    {
                        wallparts[i] = new PictureBox();
                        wallparts[i].Size = new Size(15, 15);
                        wallparts[i].BackColor = Color.Brown;
                        wallparts[i].BorderStyle = BorderStyle.FixedSingle;
                        wallparts[i].Location = new Point(ranX - (15 * i), ranY);
                        GamePanel.Controls.Add(wallparts[i]);

                    }
                }
                else {
                    for (int i = 0; i < wallrnd; i++)
                    {
                        wallparts[i] = new PictureBox();
                        wallparts[i].Size = new Size(15, 15);
                        wallparts[i].BackColor = Color.Brown;
                        wallparts[i].BorderStyle = BorderStyle.FixedSingle;
                        wallparts[i].Location = new Point(ranX, ranY - (15 * i));
                        GamePanel.Controls.Add(wallparts[i]);

                    }
                }
            }
            
        }
        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            //change time interval
            timer1.Interval = 501 - (5 * trackBar1.Value);

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            move();

        }
        private void move()
        {
            Point point = new Point(0, 0);
            //moving each part of snake
            for (int i = 0; i < snakesize; i++)
            {
                if (i == 0)
                {
                    point = snakeParts[i].Location;
                    if (direction == "Left")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X - 15, snakeParts[i].Location.Y);
                    }
                    if (direction == "Right")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X + 15, snakeParts[i].Location.Y);
                    }
                    if (direction == "Top")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X, snakeParts[i].Location.Y - 15);
                    }
                    if (direction == "Down")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X, snakeParts[i].Location.Y + 15);
                    }
                }
                else
                {
                    Point newPoint = snakeParts[i].Location;
                    snakeParts[i].Location = point;
                    point = newPoint;
                }
            }

            //hit food
            if (snakeParts[0].Location == foodlocation)
            {
                eatfood();
                drawfood();
                drawwall();
            }
            //if snake hits wall
            if (snakeParts[0].Location.X < 0 || snakeParts[0].Location.X >= 850 || snakeParts[0].Location.Y < 0 || snakeParts[0].Location.Y >= 480)
            {
                stopgame();
            }
            
            // snake eat itself
            for (int i = 3; i < snakesize; i++)
            {
                if(snakeParts[0].Location==snakeParts[i].Location)
                {
                    stopgame();
                }
            }

            changingDirection = false;
        }
        //control snake
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Up) && direction != "Down" && changingDirection != true) 
            {
                direction = "Top";
                changingDirection = true;
            }
            if (keyData == (Keys.Down) && direction != "Top" && changingDirection != true)
            {
                direction = "Down";
                changingDirection = true;
            }
            if (keyData == (Keys.Left) && direction != "Right" && changingDirection != true)
            {
                direction = "Left";
                changingDirection = true;
            }
            if (keyData == (Keys.Right) && direction != "Left" && changingDirection != true)
            {
                direction = "Right";
                changingDirection = true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void eatfood()
        {
            Random rnd = new Random();
            int abrand = rnd.Next(1, 3);
            for (int ba = 1; ba <= abrand; ba++)
            {
                snakesize++;
                PictureBox[] oldsnake = snakeParts;
                GamePanel.Controls.Clear();
                snakeParts = new PictureBox[snakesize];
                for (int i = 0; i < snakesize; i++)
                {
                    snakeParts[i] = new PictureBox();
                    snakeParts[i].Size = new Size(15, 15);
                    snakeParts[i].BackColor = Color.LawnGreen;
                    snakeParts[i].BorderStyle = BorderStyle.FixedSingle;
                    if (i == 0)
                    {
                        snakeParts[i].Location = foodlocation;
                    }
                    else
                    {
                        snakeParts[i].Location = oldsnake[i - 1].Location;
                    }
                    GamePanel.Controls.Add(snakeParts[i]);
                }
               
                myTimer2.Enabled = false;
                myTimer2.Stop();
                
                if (snakesize >= a)
                {
                    GamePanel.Controls.Clear();
                    snakeParts = null;

                    
                    level ++;
                    level_count.Text = level + "";
                    snakesize = 3;
                    direction = "Right";
                    location = new Point(120, 120);

                    drawsnake();
                    drawfood();
                    drawwall();
                    double a1 = a + a / 3;
                    a = a1;
                }
            }

            int currentScores = Int32.Parse(Score_count.Text);
            int newScore = currentScores + 50;
            Score_count.Text = newScore+"";
            int currentfruits = Int32.Parse(fruit_count.Text);
            int newScorefr = currentfruits + 1;
            fruit_count.Text = newScorefr + "";
            int currentlong = Int32.Parse(longlabel.Text);
            int newScoreln = snakesize;
            longlabel.Text = newScoreln + "";

        }

        private void stopgame()
        {
            timer1.Stop();
            Start.Enabled = true;
            trackBar1.Enabled = true;
            Pause.Enabled = false;
            namebox.Enabled = true;
            myTimer.Stop();
            //game over text
            Label over = new Label();
            over.Text = "Game\nOver";
            over.ForeColor = Color.Maroon;
            over.Font = new Font("AgitProp", 100);
            over.Size = over.PreferredSize;
            over.TextAlign = ContentAlignment.MiddleCenter;
           
            int X = GamePanel.Width / 2 - over.Width / 2;
            int Y = GamePanel.Height / 2 - over.Height / 2;
            over.Location = new Point(X, Y);
            GamePanel.Controls.Add(over);
            over.BringToFront();
            //add current score update score board
            addCurrentScoresToDateBase();
            UpdateScoreBoard();

        }
        private void UpdateScoreBoard()
        {
            //data from datebase
            string query = "SELECT Date, Name, Score, Levels, Fruits FROM scores";
            using(SqlConnection con = new SqlConnection(connectionString))
            {
                SqlDataAdapter adapter = new SqlDataAdapter(query, con);
                var ds = new DataSet();
                adapter.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
                dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Sort(this.dataGridView1.Columns[2], ListSortDirection.Descending);


            }
        }
        private void addCurrentScoresToDateBase()
        {
            //insert score in database
            string query = "INSERT INTO scores(Date, Name, Score, Levels, Fruits) VALUES(@Date,@Name,@Score,@Levels,@Fruits);";
            using (SqlConnection con = new SqlConnection(connectionString))
                using (SqlCommand cmd = new SqlCommand(query,con))
            {
                cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = DateTime.Now;
                cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = namebox.Text;
                cmd.Parameters.Add("@Score", SqlDbType.Int).Value = Score_count.Text;
                cmd.Parameters.Add("@Levels", SqlDbType.Int).Value = level_count.Text;
                cmd.Parameters.Add("@Fruits", SqlDbType.Int).Value = fruit_count.Text;
 
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
           
            }
        }

        private void Snake_Load(object sender, EventArgs e)
        {
            UpdateScoreBoard();

            playmusic();
        }

        private void musicon_Click(object sender, EventArgs e)
        {
            playmusic();
        }

        private void musicoff_Click(object sender, EventArgs e)
        {
            stopmusic();
        }
        private void playmusic()
        {
            
            sp.SoundLocation = "Chill.wav";
            sp.PlayLooping();
            musicon.Enabled = false;
            musicoff.Enabled = true;
        }
        private void stopmusic()
        {
            sp.Stop();
            musicon.Enabled = true;
            musicoff.Enabled = false;
        }
       
     
    }
}



Was This Post Helpful? 0
  • +
  • -

#11 brean   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 18-May 20

Re: Snake game in Windows forms

Posted 21 May 2020 - 06:19 AM

I wrote a snake game, but I have problems with drawwall, they disappear after eating first food, also I add drawwalls \\to hit food, but it draws new walls. I need them to regenerate to a new level (or not to regenerate at all). Also, I donít know how to make the game end when cutting into any wall. I would to make round food.
Sorry, if I I have mistakes, English isn't my native language.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Schema;
using System.Drawing.Drawing2D;


namespace Snake
{
    public partial class Snake : Form
    {
        SoundPlayer sp = new SoundPlayer();

        Timer myTimer = new Timer();
        Timer myTimer2 = new Timer();
        //Snake def
        PictureBox[] snakeParts;
        int snakesize = 3;
        Point location = new Point(120, 120);
        string direction = "Right";
        bool changingDirection = false;
        //fruit def
        PictureBox food = new PictureBox();
        Point foodlocation = new Point(0, 0);

        PictureBox[] wallparts;
        double a = 15;
        int level = 1;
        //database
        static String path = Path.GetFullPath(Environment.CurrentDirectory);
        static String dataBaseName = "date.mdf";
        string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + @"\" + dataBaseName + "; Integrated Security=True";
        public Snake()
        {
            InitializeComponent();
         
        }
            
        void myTimer_Tick(object sender, EventArgs e)
        {
            int currentScores = Int32.Parse(Score_count.Text);
            int newScore = currentScores + 1;
            Score_count.Text = newScore + "";
            int currenttime = Int32.Parse(timelabel.Text);
            int newtime = currenttime - 1;
            timelabel.Text = newtime + "";
        }
        void myTimer2_Tick(object sender, EventArgs e)
        {
            GamePanel.Controls.Remove(food);
            drawfood();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            stopgame();
        }

        private void Start_Click(object sender, EventArgs e)
        {
            //play again
            GamePanel.Controls.Clear();
            snakeParts = null;
            Score_count.Text = "0";
            level_count.Text = "1";
            fruit_count.Text = "0";
            snakesize = 3;
            direction = "Right";
            location = new Point(120, 120);
            //start game
            drawsnake();
            drawfood();
            drawwall();
            level_count.Text = "1";
            timer1.Start();
            //control
            trackBar1.Enabled = false;
            Start.Enabled = false;
            namebox.Enabled = false;
            //enable pause
            Pause.Enabled = true;
            // timer +1 on
            myTimer.Interval = 1000;
            myTimer.Enabled = true;
            myTimer.Tick += myTimer_Tick;
            myTimer.Start();

           

           
            //snake long label
            longlabel.Text = snakesize + "";


        }

        private void drawsnake()
        {
            snakeParts = new PictureBox[snakesize];

            //one part after another
            for (int i = 0; i < snakesize; i++)
            {
                snakeParts[i] = new PictureBox();
                snakeParts[i].Size = new Size(15, 15);
                snakeParts[i].BackColor = Color.LawnGreen;
                snakeParts[i].BorderStyle = BorderStyle.FixedSingle;
                snakeParts[i].Location = new Point(location.X - (15 * i), location.Y);
                GamePanel.Controls.Add(snakeParts[i]);

            }

        }
        private void drawfood()
        {
           
            Random rnd = new Random();
            int Xrand = rnd.Next(38) * 15;
            int Yrand = rnd.Next(30) * 15;

            bool isOnSnake = true;
            // chek food on snake
            while (isOnSnake)
            {
                for (int i = 0; i < snakesize; i++)
                {
                    if (snakeParts[i].Location == new Point(Xrand, Yrand))
                    {
                        Xrand = rnd.Next(38) * 15;
                        Yrand = rnd.Next(30) * 15;
                    }
                    else
                    {
                        isOnSnake = false;
                    }
                }
            }

            //draw food
            if (isOnSnake == false)
            {
                int col = rnd.Next(1, 6);
                foodlocation = new Point(Xrand, Yrand);
                food.Size = new Size(15, 15);
                if (col == 1)
                {
                    food.BackColor = Color.OrangeRed;
                }
                else if (col == 2)
                {
                    food.BackColor = Color.Yellow;
                }
                else if (col == 3)
                {
                    food.BackColor = Color.Violet;
                }
                else if (col == 4)
                {
                    food.BackColor = Color.Aquamarine;
                }
                else
                {
                    food.BackColor = Color.Red;
                }
                food.BorderStyle = BorderStyle.FixedSingle;
                food.Location = foodlocation;
                
            
        
        GamePanel.Controls.Add(food);
                myTimer2.Interval = 30000;
                myTimer2.Enabled = true;
                myTimer2.Tick += myTimer2_Tick;
                myTimer2.Start();

                timelabel.Text = "30";
            }
        }

        private void drawwall()
        {
            Random rnd = new Random();
            int numwall = rnd.Next(3, 10);
            for (int a = 1; a < numwall; a++)
            {
                int ranX = rnd.Next(50) * 15;
                int ranY = rnd.Next(42) * 15;

                int wallrnd = rnd.Next(2, 7);
                wallparts = new PictureBox[wallrnd];
                int xy = rnd.Next(1, 3);
                if (xy == 1)
                {
                    for (int i = 0; i < wallrnd; i++)
                    {
                        wallparts[i] = new PictureBox();
                        wallparts[i].Size = new Size(15, 15);
                        wallparts[i].BackColor = Color.Brown;
                        wallparts[i].BorderStyle = BorderStyle.FixedSingle;
                        wallparts[i].Location = new Point(ranX - (15 * i), ranY);
                        GamePanel.Controls.Add(wallparts[i]);

                    }
                }
                else
                {
                    for (int i = 0; i < wallrnd; i++)
                    {
                        wallparts[i] = new PictureBox();
                        wallparts[i].Size = new Size(15, 15);
                        wallparts[i].BackColor = Color.Brown;
                        wallparts[i].BorderStyle = BorderStyle.FixedSingle;
                        wallparts[i].Location = new Point(ranX, ranY - (15 * i));
                        GamePanel.Controls.Add(wallparts[i]);

                    }
                }
            }

        }
        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            //change time interval
            timer1.Interval = 501 - (5 * trackBar1.Value);

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            move();

        }
        private void move()
        {
            Point point = new Point(0, 0);
            //moving each part of snake
            for (int i = 0; i < snakesize; i++)
            {
                if (i == 0)
                {
                    point = snakeParts[i].Location;
                    if (direction == "Left")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X - 15, snakeParts[i].Location.Y);
                    }
                    if (direction == "Right")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X + 15, snakeParts[i].Location.Y);
                    }
                    if (direction == "Top")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X, snakeParts[i].Location.Y - 15);
                    }
                    if (direction == "Down")
                    {
                        snakeParts[i].Location = new Point(snakeParts[i].Location.X, snakeParts[i].Location.Y + 15);
                    }
                }
                else
                {
                    Point newPoint = snakeParts[i].Location;
                    snakeParts[i].Location = point;
                    point = newPoint;
                }
            }

            //hit food
            if (snakeParts[0].Location == foodlocation)
            {
                eatfood();
                drawfood();
                drawwall();
            }
            //if snake hits wall
            if (snakeParts[0].Location.X < 0 || snakeParts[0].Location.X >= 850 || snakeParts[0].Location.Y < 0 || snakeParts[0].Location.Y >= 480)
            {
                stopgame();
            }
            
            // snake eat itself
            for (int i = 3; i < snakesize; i++)
            {
                if(snakeParts[0].Location==snakeParts[i].Location)
                {
                    stopgame();
                }
            }

            changingDirection = false;
        }
        //control snake
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Up) && direction != "Down" && changingDirection != true) 
            {
                direction = "Top";
                changingDirection = true;
            }
            if (keyData == (Keys.Down) && direction != "Top" && changingDirection != true)
            {
                direction = "Down";
                changingDirection = true;
            }
            if (keyData == (Keys.Left) && direction != "Right" && changingDirection != true)
            {
                direction = "Left";
                changingDirection = true;
            }
            if (keyData == (Keys.Right) && direction != "Left" && changingDirection != true)
            {
                direction = "Right";
                changingDirection = true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void eatfood()
        {
            Random rnd = new Random();
            int abrand = rnd.Next(1, 3);
            for (int ba = 1; ba <= abrand; ba++)
            {
                snakesize++;
                PictureBox[] oldsnake = snakeParts;
                GamePanel.Controls.Clear();
                snakeParts = new PictureBox[snakesize];
                for (int i = 0; i < snakesize; i++)
                {
                    snakeParts[i] = new PictureBox();
                    snakeParts[i].Size = new Size(15, 15);
                    snakeParts[i].BackColor = Color.LawnGreen;
                    snakeParts[i].BorderStyle = BorderStyle.FixedSingle;
                    if (i == 0)
                    {
                        snakeParts[i].Location = foodlocation;
                    }
                    else
                    {
                        snakeParts[i].Location = oldsnake[i - 1].Location;
                    }
                    GamePanel.Controls.Add(snakeParts[i]);
                }
               
                myTimer2.Enabled = false;
                myTimer2.Stop();
                
                if (snakesize >= a)
                {
                    GamePanel.Controls.Clear();
                    snakeParts = null;

                    
                    level ++;
                    level_count.Text = level + "";
                    snakesize = 3;
                    direction = "Right";
                    location = new Point(120, 120);

                    drawsnake();
                    drawfood();
                    drawwall();
                    double a1 = a + a / 3;
                    a = a1;
                }
            }

            int currentScores = Int32.Parse(Score_count.Text);
            int newScore = currentScores + 50;
            Score_count.Text = newScore+"";
            int currentfruits = Int32.Parse(fruit_count.Text);
            int newScorefr = currentfruits + 1;
            fruit_count.Text = newScorefr + "";
            int currentlong = Int32.Parse(longlabel.Text);
            int newScoreln = snakesize;
            longlabel.Text = newScoreln + "";

        }

        private void stopgame()
        {
            timer1.Stop();
            Start.Enabled = true;
            trackBar1.Enabled = true;
            Pause.Enabled = false;
            namebox.Enabled = true;
            myTimer.Stop();
            //game over text
            Label over = new Label();
            over.Text = "Game\nOver";
            over.ForeColor = Color.Maroon;
            over.Font = new Font("AgitProp", 100);
            over.Size = over.PreferredSize;
            over.TextAlign = ContentAlignment.MiddleCenter;
           
            int X = GamePanel.Width / 2 - over.Width / 2;
            int Y = GamePanel.Height / 2 - over.Height / 2;
            over.Location = new Point(X, Y);
            GamePanel.Controls.Add(over);
            over.BringToFront();
            //add current score update score board
            addCurrentScoresToDateBase();
            UpdateScoreBoard();

        }
        private void UpdateScoreBoard()
        {
            //data from datebase
            string query = "SELECT Date, Name, Score, Levels, Fruits FROM scores";
            using(SqlConnection con = new SqlConnection(connectionString))
            {
                SqlDataAdapter adapter = new SqlDataAdapter(query, con);
                var ds = new DataSet();
                adapter.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
                dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Sort(this.dataGridView1.Columns[2], ListSortDirection.Descending);


            }
        }
        private void addCurrentScoresToDateBase()
        {
            //insert score in database
            string query = "INSERT INTO scores(Date, Name, Score, Levels, Fruits) VALUES(@Date,@Name,@Score,@Levels,@Fruits);";
            using (SqlConnection con = new SqlConnection(connectionString))
                using (SqlCommand cmd = new SqlCommand(query,con))
            {
                cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = DateTime.Now;
                cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = namebox.Text;
                cmd.Parameters.Add("@Score", SqlDbType.Int).Value = Score_count.Text;
                cmd.Parameters.Add("@Levels", SqlDbType.Int).Value = level_count.Text;
                cmd.Parameters.Add("@Fruits", SqlDbType.Int).Value = fruit_count.Text;
 
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
           
            }
        }

        private void Snake_Load(object sender, EventArgs e)
        {
            UpdateScoreBoard();

            playmusic();
        }

        private void musicon_Click(object sender, EventArgs e)
        {
            playmusic();
        }

        private void musicoff_Click(object sender, EventArgs e)
        {
            stopmusic();
        }
        private void playmusic()
        {
            
            sp.SoundLocation = "Chill.wav";
            sp.PlayLooping();
            musicon.Enabled = false;
            musicoff.Enabled = true;
        }
        private void stopmusic()
        {
            sp.Stop();
            musicon.Enabled = true;
            musicoff.Enabled = false;
        }

    }
}



Was This Post Helpful? 0
  • +
  • -

#12 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Snake game in Windows forms

Posted 21 May 2020 - 06:32 AM

@OP Do not open a new topic on the same subject and code. I have merged your topics.
Was This Post Helpful? 0
  • +
  • -

#13 modi123_1   User is offline

  • Suitor #2
  • member icon



Reputation: 15781
  • View blog
  • Posts: 63,246
  • Joined: 12-June 08

Re: Snake game in Windows forms

Posted 21 May 2020 - 06:42 AM

Quote

also I add drawwalls \\to hit food, but it draws new walls.

Then have a method that draws the class, or collection, containing the current walls.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1