-
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.
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.
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.
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; } } } }
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
1
branch
0
tags
Code
-
Use Git or checkout with SVN using the web URL.
-
Open with GitHub Desktop
-
Download ZIP
Latest commit
Files
Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
C# Tutorial — Create a Classic Snakes Game in Visual Studio UPDATED
The classic snake game project is now updated and added with some extra features to boost your game play and power up your C# programming skills using the Windows Form Framework in Visual Studio.
From the last project the following were added to the new and updated one
- You can go through the walls from up/down/left/right and appear on the other side with reversed speed
- You can Take keep the score and save a highscore from any game plays session
- You can take snap shot of the game and save it as JPG file with the Score and Highscore as a caption in the image
- Start and Restart game with a button on run time
Link to the Website —
C# Tutorial – How to make a Classic Snakes Game with Windows form and Visual Studio [Updated]
Full Video Tutorial on the official Channel —
About
Create the fun classic snakes game using C# in Windows Form. We will be using little elements of OOP programming to make this project, the code, project files and video tutorial is all presented with this project here
Topics
Resources
Readme
License
Apache-2.0 license
Activity
Stars
4
stars
Watchers
1
watching
Forks
7
forks
Запись от 8Observer8 размещена 10.02.2019 в 22:56
Обновил(-а) 8Observer8 11.05.2023 в 01:21
We will place OpenTK.GLControl on the Form to draw graphics with modern shader OpenGL 3.1.
This is a gif animation of the final result of our work:
Note. I take ideas from this tutorial: Python Snake Game
Please, download this empty project: Snake_WinFormsOpenGL31CSharp.zip. It includes OpenTK.dll and OpenTK.GLControl.dll
Or if you know how to add libraries from References and how to add Control to Toolbox you can download these two DLL’s: OpenTK.zip and OpenTK.GLControl.zip You can search in the Internet how to do it.
Current Form1.css file:
C# | ||
|
These commands just clear a render canvas (glControl) with a black color. RGB values (0f, 0f, 0f) mean the black color. If you write (1f, 0f, 0f) — it will be a red color or if you write (1f, 1f, 1f) — it will be a white color. You can choose your own value of normalized color using this color calculator.
I set «FormBorderStyle» to «FixedDialog». You cannot change size of the window with the mouse. And I set «MaximizeBox» to «False». You cannot maximize the window by click on «Maximize» button on the window.
Let’s draw a square. We need to write a pair of shaders: a vertex shader and a fragment shader. This pair will be associated with a shader program object that we will create too. The pair of shaders and the shader program will placed in a video card memory. We will create an array of vertices of our square and vertex buffer object (VBO) on the video card memory. We will move the array of coordinates of vertices to VBO. The vertex shader will be executed for every vertex when we will call the function: drawArrays(). The vertex shader just set coordinates for vertices. The fragment shader will be executed for every pixel of the square and set a color for every pixel.
This book is one of the best for start: WebGL Programming Guide
C# | ||
|
We need to set a coordinate system: [0, 20]. I want to have (0, 0) in top left corner. Y axis will have a direction from top to bottom. And I add ability to set a size and a position of square:
C# | ||
|
Each game must have a game loop that will be called by timer. I created the GameLoop method that just prints «Hello, World!» to the debug console every 500 ms:
C# | ||
|
Update() method will have updates for snake cell coordinates and etc. The Draw() method will have only draw methods for game entities. Method glControl.Invalidate() will provoke a call of Draw() method.
C# | ||
|
List data structure is ideal for keeping snake cells coordinates:
C# | ||
|
Point(1, 1) — it is position of the head.
Method for drawing the snake:
C# | ||
|
For moving the snake we need to create the «snakeDir» variable:
C# | ||
|
The snake moving is very simple. Please, read comments:
C# | ||
|
C# | ||
|
I will explain eating food later. But you can read comments in the code.
This is the result:
C# | ||
|
- Remove From My Forums
-
Question
-
Hi
I need help the make a classic snake game in windows form application. The most guides for the snake game are in console so they don’t really help. If you could post the basic code (or all of the code) i would be very thankfull.
-
Moved by
Tuesday, March 17, 2015 5:03 PM
Winforms related
-
Moved by
Answers
-
This is a very broad question. For that reason, I will provide a broad answer. If you need code specific help, please post code specific questions.
This is my way of thinking and it may not be the best solution:
1- You need to create a virtual grid on your form.
Let say you have a 800 x 800 form and you will divide this into 20 x 20 grids.
Each grid will be 40 px width and height.
Create a grid class to hold x, y values.
2- For your snake you need to create a snake class.
Snake class will hold the length of the snake.
3 — Game class:
This will be the main container class that holds snake, timer (if available), bates for the snake, game logic.
4- Game logic Class:
in your game logic class, define how your snake behaves for example when a user clicks up button while snakes direction is left.
5- Form elements:
Each grid will hold a picture box and your picture box will be filled with different elements such as:
— plain
— bate
— snake
6 — Collusion detection:
This will be a part of game logic but it will be better if you have separate collusion detection class.
-
Proposed as answer by
Carl Cai
Wednesday, March 18, 2015 4:28 AM -
Marked as answer by
Carl Cai
Wednesday, March 25, 2015 5:51 AM
-
Proposed as answer by
-
Hi,
Please try to follow
Val10’s ideas and write it by yourself.You also can put some keywords like «C# snake game » in the search engine.
It will shows many resluts about it. You could choose to refer someone to get some hints.
This project seems meet your requirements. Please take a look
#Snake Game in C#
http://www.c-sharpcorner.com/uploadfile/prink_mob/snake-game-in-C-Sharp/
If all of these are not what you want, please submit a sample request to
http://code.msdn.microsoft.com/windowsapps/site/requests.
If you encountered any issue when implementing it, you could open new thread
for each specific issue.Best regards,
Kristin
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.-
Edited by
Kristin Xie
Tuesday, March 17, 2015 8:17 AM -
Proposed as answer by
Carl Cai
Wednesday, March 18, 2015 4:28 AM -
Marked as answer by
Carl Cai
Wednesday, March 25, 2015 5:51 AM
-
Edited by
-
-
Proposed as answer by
Carl Cai
Wednesday, March 18, 2015 4:28 AM -
Marked as answer by
Carl Cai
Wednesday, March 25, 2015 5:51 AM
-
Proposed as answer by
-
-
Proposed as answer by
Carl Cai
Wednesday, March 18, 2015 4:28 AM -
Marked as answer by
Carl Cai
Wednesday, March 25, 2015 5:51 AM
-
Proposed as answer by
stuff and things
Menu
- Home
- His
- Hers
- Contact
Browse: Home
» 2014
» February
» Classic Snake Game using C# Windows Forms
Classic Snake Game using C# Windows Forms
February 21, 2014 · by admin · in His
Everybody likes the classic snake game. Here is a simple C# implementation built for funsies.
admin
Chris Grgich-Tran is a Development Manager from Brisbane, Australia. When he’s not dad-ing it up, he works with some very talented people.
More Posts
Follow Me:
Comments
Tags: .net, c#, code, games, windows forms
Comments are closed, but trackbacks and pingbacks are open.
← Subtle waiting effect for buttons
Unlocking the BRZ Sat Nav Unit – Eclipse AVN 827GA →
Google Ads
About
A blog about stuff as most blogs generally are.
Meta
- Log in
- Entries feed
- Comments feed
- WordPress.org
Copyright © 2023 grgichtran
Powered by WordPress and Origin