Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize gluttonous Snake Mini Game with C#

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail "how to use C# to achieve gluttonous Snake Mini Game". The content is detailed, the steps are clear, and the details are handled properly. I hope this "how to use C# to achieve gluttonous Snake Mini Game" article can help you solve your doubts. Let's follow the editor's train of thought to slowly deepen, together to learn new knowledge.

Interface

The interface is relatively simple, consisting of a button and an integrator.

Basic logic: there is a big food for every five foods, a small food for 1, and a big food for 5.

Control: when hitting the wall and winding, the game is suspended.

Code detailed explanation

Introduce the code in detail

1. Detailed explanation of the code

1. The interface is on pc, so move to the next key to control the movement, in order to respond in time, so add the following code

Protected override bool ProcessDialogKey (Keys keyData) {/ / Custom processing if (keyData = = Keys.Up | | keyData = = Keys.Down | | keyData = = Keys.Left | | keyData = = Keys.Right) return false; else return base.ProcessDialogKey (keyData);}

two。 Make an enumeration to mark the direction of movement of the snake in a certain state of time, with keyboard keys

/ Direction enumeration / public enum SnakeDirection {Left, Right, Down, Up} / Keyboard and mouse are pressed but must have controls / private void SnakeForm_KeyDown (object sender KeyEventArgs e) {if (e.KeyCode = = Keys.Up) {Snake.Sd = SnakeDirection.Up } else if (e.KeyCode = = Keys.Down) {Snake.Sd = SnakeDirection.Down;} else if (e.KeyCode = = Keys.Left) {Snake.Sd = SnakeDirection.Left } else if (e.KeyCode = = Keys.Right) {Snake.Sd = SnakeDirection.Right;}}

3. Declare a class of snakes and store information about all snakes, such as the node locations of all snakes

Public class Snake

The main variables are as follows

The direction of the public static SnakeDirection Sd;// snake is up, down, left, right, public int Location_X;//0 is XMag1, the initial position of the snake is public int Location_Y;public static List Snakebody = new List (); / / the specific position of the snake body, each displacement is refreshed once all the positions of the whole snake body, and the last position is the snake head public static int width = 10, height = 10 × public static int CurScore = 1 / / the score of the current food public static int AllScore =-1 / total score public static int MaxScore = 5 / frequency of occurrence of the big score

4. Declare a class of food and add a method to randomly display the food at a location on the interface

Public class Food {public int Food_Location_X; public int Food_Location_Y; public Food () {Random x = new Random (); Random y = new Random (); Food_Location_X = x.Next (0,49) * 10bump / random spot food Food_Location_Y = y.Next (0,49) * 10 / / Food appears at random points}}

5. Click the start button to trigger the start-related method, mainly to start the refresh timer, initialize the food position, initialize the points, etc.

Public void refreshScore () {Snake.AllScore = Snake.AllScore+ Snake.CurScore; this.SnakeScore.Text = Convert.ToString (Snake.AllScore);} private int FoodX = 0 EventArgs CreateNewFood / food X axis private int FoodY = 0 object sender / food Y axis private void BeginBtn_Click (object sender, food e) {Snake.Start (); / / create snake CreateNewFood () StartTimer.Start (); StartTimer.Interval = 100ram / millisecond refresh}

6. After the timer starts, refresh regularly. What I set here is 100 milliseconds. I can also make a front-end setting button to increase the interest of the game. At the same time, it can also be set to handle this setting according to different points.

In the timer, there are ways to draw the snake's body, to randomly locate a food, to move the snake, to see if the snake eats the food, and to end the game.

/ start timer / private void StartTimer_Tick (object sender, EventArgs e) {DrawSnake (); DrawFood (); Snake.Move (Snake.Sd); / / the direction of snake movement is controlled by keyboard control EatFood (); IsOrNotGameOver ();}

7. The way to draw a snake is as follows

/ draw snake / public void DrawSnake () {RectangleF [] rectangles = new RectangleF [Snake.Snakebody.Count]; int num; for (num = 0; num < Snake.Snakebody.Count) Num++) {rectangles [num] = new RectangleF (Snake.Snakebody.location _ X, Snake.Snakebody.location _ Y, Snake.width, Snake.height);} this.Refresh (); Graphics g = this.Snake_Panel.CreateGraphics (); SolidBrush myBrush = new SolidBrush (Color.Black) G.FillRectangles (myBrush, rectangles);}

8. Food is displayed in the following way, where MaxScore represents the number of small foods, each time this value is minus one, when 0, the food becomes a big food.

/ public void DrawFood () {Graphics f = this.Snake_Panel.CreateGraphics (); SolidBrush mybrush = new SolidBrush (Color.Red); if (Snake.MaxScore==0) {f.FillRectangle (mybrush, FoodX, FoodY, 20, 20) / / Random the location of the food} else {f.FillRectangle (mybrush, FoodX, FoodY, 10,10); / / randomly the location of the food}}

9. When each refresh, the snake will move, and the corresponding overall position of the snake will change, but the snake body has traces, so use the following ways to change the snake body.

/ / the snake's movement operation needs to change the snake's body public static void Move (SnakeDirection Sd) {int I = Snakebody.Count-1 every time it moves. / / change the relative position according to the moving direction. This operation ensures that the snake body runs switch (Sd) {case SnakeDirection.Up: ChangeSnakeLine (); Snakebody.location _ Y-= 10; Snakebody.location _ Y-= 10; according to the trajectory of the snakehead. Case SnakeDirection.Left: ChangeSnakeLine (); Snakebody [I] .location _ X-= 10; break; case SnakeDirection.Down: ChangeSnakeLine (); Snakebody.location _ Y + = 10 Break; case SnakeDirection.Right: ChangeSnakeLine (); Snakebody [I] .location _ X + = 10; break } / change the relative position of the snake's body every time you move / public static void ChangeSnakeLine () {int j = 0; int x, y; int i = Snakebody.Count-1 The position of snake 1 becomes snake 0 2 = "1 3 =" 2 {x = Snakebody [j + 1] .location _ X; y = Snakebody [j + 1] .location _ Y; Snakebody.location _ Y = y Snakebody.Location _ X = x;}}

10. After refreshing the snake's body, it is necessary to judge whether the food position collides with the snake's head. when there is a collision, the snake eats the food, the food is refreshed, and the snake's body grows.

/ when eating the food and judging that the position of the snakehead is the same as that of the food, the food refreshes / public void EatFood () {if (Snake.Snakebody [Snake.Snakebody.Count-1] .location _ X = = FoodX & & Snake.Snakebody [Snake.Snakebody.Count-1] .location _ Y = = FoodY) {Snake.AddBody () / / add snake body add / / randomly create a new food CreateNewFood () after eating the food;}} / / eat a node into a new snakehead public static void AddBody () {Snake S_eat = new Snake () Int xx = Snakebody [Snakebody.Count-1] .location _ X; int yy = Snakebody [Snakebody.Count-1] .location _ Y; switch (Sd) {case SnakeDirection.Up: S_eat.Location_Y = yy-10; S_eat.Location_X = xx Snakebody.Add (S_eat); break; case SnakeDirection.Left: S_eat.Location_X = xx-10; S_eat.Location_Y = yy; Snakebody.Add (S_eat); break Case SnakeDirection.Down: S_eat.Location_Y = yy + 10; S_eat.Location_X = xx; Snakebody.Add (S_eat); break Case SnakeDirection.Right: S_eat.Location_Y = yy; S_eat.Location_X = xx + 10; Snakebody.Add (S_eat); break;}}

11. After the food is eaten, the food is refreshed and the number of snacks is judged.

/ / public void CreateNewFood () {refreshScore (); bool IsCreate = false; while (! IsCreate) / / whether it is created successfully {Food NewFood = new Food (); FoodX = NewFood.Food_Location_X; FoodY = NewFood.Food_Location_Y / / judge that this will not occur in snakes IsCreate = true;// successfully created for (int I = 0; I < Snake.Snakebody.Count) FoodY +) {if (Snake.Snakebody [I] .location _ X = = FoodX & & Snake.Snakebody [I] .location _ Y = = FoodY) / / for is not created successfully when the coordinates are the same {Snakebody.Snakebody [I] .location _ Y = = false; break }} if (IsCreate) {if (! (FoodX = 10 & & FoodY = 10)) / / Food is not in the range to refresh {IsCreate = false }} if (IsCreate) {if (Snake.Snakebody.Count! = 4) {Snake.MaxScore--;// is not the first time a food is created} Snake.CurScore = 1 / / the score of the current minor node if (Snake.MaxScore = = 0) {Snake.CurScore = 5 Snake.CurScore / the score of the current minor node} else if (Snake.MaxScore

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report