C# Tutorial – How to make a Classic Snakes Game with Windows form and Visual Studio [Updated]
- Subject: C# Tutorials
- Learning Time: 2 hours
Hi Welcome to this tutorial. This tutorial is an updated version of the C# Snakes game tutorial we have done before on the website. This video tutorial will explain all of the core components needed to make this classic game in windows form in visual studio with C# programming language. We wont be using any oher game frameworks to make this work however we will be using some OOP programming practices in this tutorial. Everything you need to know and how to use them inside of the game effectively is explained in the tutorial.
Lesson objectives –
- Make a full snakes game in visual studio
- Using custom classes to load and reload default settings
- Using custom classes to draw the snake and food to the game
- Working with Keyboard controls
- Keeping score and high score in the current game session
- Able to take snap of the game when it ends
- Starting and Restarting the game to replay
Full Video Tutorial on How to make the classic snake game in Visual Studio with C#
Download Snake Game Project Tutorial on MOOICT GitHub
Source Code –
Circle Class –
This class will help us draw circles to the form, we will use this one to determine the X and Y position of the circles in the screen. This will be used for both the SNAKE and the Food objects inside of the game.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Classic_Snakes_Game_Tutorial___MOO_ICT { class Circle { public int X { get; set; } public int Y { get; set; } public Circle() { X = 0; Y = 0; } } } |
Settings Class
This is the settings class for the game. This class will be used to load up the default settings for the game objects only. It will load the size in height and width of the circles that will be drawn to the project also the direction the snake should be moving when the game initially loads.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Classic_Snakes_Game_Tutorial___MOO_ICT { class Settings { public static int Width { get; set; } public static int Height { get; set; } public static string directions; public Settings() { Width = 16; Height = 16; directions = "left"; } } } |
Main Form C# Scripts
This is the main form1.cs code. In this script we have given all of the instructions necessary for the game and how it will behave when the game loads up. We have several events in the code below for example the Key Down, Key Up, Timer, 2 Click Events and a Paint Event. Also we have 3 custom functions such as Restart Game, Game Over and Eat Food function for the snake.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing.Imaging; // add this for the JPG compressor namespace Classic_Snakes_Game_Tutorial___MOO_ICT { public partial class Form1 : Form { private List<Circle> Snake = new List<Circle>(); private Circle food = new Circle(); int maxWidth; int maxHeight; int score; int highScore; Random rand = new Random(); bool goLeft, goRight, goDown, goUp; public Form1() { InitializeComponent(); new Settings(); } private void KeyIsDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left && Settings.directions != "right") { goLeft = true; } if (e.KeyCode == Keys.Right && Settings.directions != "left") { goRight = true; } if (e.KeyCode == Keys.Up && Settings.directions != "down") { goUp = true; } if (e.KeyCode == Keys.Down && Settings.directions != "up") { goDown = true; } } private void KeyIsUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) { goLeft = false; } if (e.KeyCode == Keys.Right) { goRight = false; } if (e.KeyCode == Keys.Up) { goUp = false; } if (e.KeyCode == Keys.Down) { goDown = false; } } private void StartGame(object sender, EventArgs e) { RestartGame(); } private void TakeSnapShot(object sender, EventArgs e) { Label caption = new Label(); caption.Text = "I scored: " + score + " and my Highscore is " + highScore + " on the Snake Game from MOO ICT"; caption.Font = new Font("Ariel", 12, FontStyle.Bold); caption.ForeColor = Color.Purple; caption.AutoSize = false; caption.Width = picCanvas.Width; caption.Height = 30; caption.TextAlign = ContentAlignment.MiddleCenter; picCanvas.Controls.Add(caption); SaveFileDialog dialog = new SaveFileDialog(); dialog.FileName = "Snake Game SnapShot MOO ICT"; dialog.DefaultExt = "jpg"; dialog.Filter = "JPG Image File | *.jpg"; dialog.ValidateNames = true; if (dialog.ShowDialog() == DialogResult.OK) { int width = Convert.ToInt32(picCanvas.Width); int height = Convert.ToInt32(picCanvas.Height); Bitmap bmp = new Bitmap(width, height); picCanvas.DrawToBitmap(bmp, new Rectangle(0,0, width, height)); bmp.Save(dialog.FileName, ImageFormat.Jpeg); picCanvas.Controls.Remove(caption); } } private void GameTimerEvent(object sender, EventArgs e) { // setting the directions if (goLeft) { Settings.directions = "left"; } if (goRight) { Settings.directions = "right"; } if (goDown) { Settings.directions = "down"; } if (goUp) { Settings.directions = "up"; } // end of directions for (int i = Snake.Count - 1; i >= 0; i--) { if (i == 0) { switch (Settings.directions) { case "left": Snake[i].X--; break; case "right": Snake[i].X++; break; case "down": Snake[i].Y++; break; case "up": Snake[i].Y--; break; } if (Snake[i].X < 0) { Snake[i].X = maxWidth; } if (Snake[i].X > maxWidth) { Snake[i].X = 0; } if (Snake[i].Y < 0) { Snake[i].Y = maxHeight; } if (Snake[i].Y > maxHeight) { Snake[i].Y = 0; } if (Snake[i].X == food.X && Snake[i].Y == food.Y) { EatFood(); } for (int j = 1; j < Snake.Count; j++) { if (Snake[i].X == Snake[j].X && Snake[i].Y == Snake[j].Y) { GameOver(); } } } else { Snake[i].X = Snake[i - 1].X; Snake[i].Y = Snake[i - 1].Y; } } picCanvas.Invalidate(); } private void UpdatePictureBoxGraphics(object sender, PaintEventArgs e) { Graphics canvas = e.Graphics; Brush snakeColour; for (int i = 0; i < Snake.Count; i++) { if (i == 0) { snakeColour = Brushes.Black; } else { snakeColour = Brushes.DarkGreen; } canvas.FillEllipse(snakeColour, new Rectangle ( Snake[i].X * Settings.Width, Snake[i].Y * Settings.Height, Settings.Width, Settings.Height )); } canvas.FillEllipse(Brushes.DarkRed, new Rectangle ( food.X * Settings.Width, food.Y * Settings.Height, Settings.Width, Settings.Height )); } private void RestartGame() { maxWidth = picCanvas.Width / Settings.Width - 1; maxHeight = picCanvas.Height / Settings.Height - 1; Snake.Clear(); startButton.Enabled = false; snapButton.Enabled = false; score = 0; txtScore.Text = "Score: " + score; Circle head = new Circle { X = 10, Y = 5 }; Snake.Add(head); // adding the head part of the snake to the list for (int i = 0; i < 100; i++) { Circle body = new Circle(); Snake.Add(body); } food = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight)}; gameTimer.Start(); } private void EatFood() { score += 1; txtScore.Text = "Score: " + score; Circle body = new Circle { X = Snake[Snake.Count - 1].X, Y = Snake[Snake.Count - 1].Y }; Snake.Add(body); food = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight) }; } private void GameOver() { gameTimer.Stop(); startButton.Enabled = true; snapButton.Enabled = true; if (score > highScore) { highScore = score; txtHighScore.Text = "High Score: " + Environment.NewLine + highScore; txtHighScore.ForeColor = Color.Maroon; txtHighScore.TextAlign = ContentAlignment.MiddleCenter; } } } } |
is there any reason you have flags to indicate left,right,up & down?
Also, is the KeyIsUp function needed ?
I refactored your code to :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
static class Constants
{
public const int headPos = 0;
public const int gameTimerInterval = 500;
}
namespace snake
{
public partial class Form1 : Form
{
private List Snake = new List();
private Circle food = new Circle();
int maxWidth;
int maxHeight;
Random rand = new Random();
public Form1()
{
InitializeComponent();
new setting();
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left && setting.direction != “RIGHT”)
{
setting.direction = “LEFT”;
}
if (e.KeyCode == Keys.Right && setting.direction != “LEFT”)
{
setting.direction = “RIGHT”;
}
if (e.KeyCode == Keys.Up && setting.direction != “DOWN”)
{
setting.direction = “UP”;
}
if (e.KeyCode == Keys.Down && setting.direction != “UP”)
{
setting.direction = “DOWN”;
}
}
private void StartGame(object sender, EventArgs e)
{
RestartGame();
}
private void GameTimerEvent(object sender, EventArgs e)
{
checkFood();
for (int bodyIndex = Snake.Count – 1; bodyIndex >= 0; bodyIndex–)
{
if (bodyIndex == Constants.headPos)
{
updateSnakePos();
}
else
{
Snake[bodyIndex].X = Snake[bodyIndex – 1].X;
Snake[bodyIndex].Y = Snake[bodyIndex – 1].Y;
}
}
checkSnakeCollision();
picCanvas.Invalidate();
}
private void updateSnakePos()
{
switch (setting.direction)
{
case “LEFT”:
Snake[Constants.headPos].X–;
if (Snake[Constants.headPos].X maxWidth)
{
gameOver();
}
break;
case “DOWN”:
Snake[Constants.headPos].Y++;
if (Snake[Constants.headPos].Y > maxHeight)
{
gameOver();
}
break;
case “UP”:
Snake[Constants.headPos].Y–;
if (Snake[Constants.headPos].Y < 0)
{
gameOver();
}
break;
default:
break;
}
}
private void drawSnake(object sender, PaintEventArgs e)
{
Graphics canvas = e.Graphics;
for (int i = 0; i < Snake.Count; i++)
{
canvas.FillEllipse((i == Constants.headPos) ? Brushes.Black : Brushes.DarkGreen, new Rectangle(Snake[i].X * setting.Width, Snake[i].Y * setting.Height, setting.Width, setting.Height));
}
canvas.FillEllipse(Brushes.DarkRed, new Rectangle(food.X * setting.Width, food.Y * setting.Height, setting.Width, setting.Height));
}
private void RestartGame()
{
maxWidth = picCanvas.Width / setting.Width – 1;
maxHeight = picCanvas.Height / setting.Height – 1;
Snake.Clear();
startButton.Enabled = false;
Circle head = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight)};
Snake.Add(head); // adding the head part of the snake to the list
for (int i = 0; i < 3; i++)
{
Circle body = new Circle();
Snake.Add(body);
}
food = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight) };
gameTimer.Start();
}
private void checkSnakeCollision()
{
for (int j = 1; j < Snake.Count; j++)
{
if (Snake[Constants.headPos].X == Snake[j].X && Snake[Constants.headPos].Y == Snake[j].Y)
{
gameOver();
}
}
}
private void gameOver()
{
gameTimer.Interval = Constants.gameTimerInterval;
gameTimer.Stop();
startButton.Enabled = true;
}
private void checkFood()
{
if (Snake[Constants.headPos].X == food.X && Snake[Constants.headPos].Y == food.Y)
{
Circle body = new Circle
{
X = Snake[Snake.Count – 1].X,
Y = Snake[Snake.Count – 1].Y
};
if(gameTimer.Interval / 2 == 0)
{
gameTimer.Interval = 5;
}
else
{
gameTimer.Interval = gameTimer.Interval / 2;
}
Snake.Add(body);
food = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight) };
}
}
}
}