当前位置:网站首页>C realize Snake games

C realize Snake games

2022-07-04 06:05:00 Langyu 123

Snake game can be said to be the game enlightenment of many small partners , Today we'll use C Language reprints childhood classic game greedy snake , Before writing this game , Need to know something about easyx Knowledge of Graphic Library , Because this is how the game window is provided .

This article mainly introduces the functions of writing this game , In addition, I will write another article about some common things in this game BUG And the solutions , If you have been able to complete part of the preparation , And trapped in some BUG Your partner can move to another article , There may be some you encounter BUG.

Realize the snake game , First we need to set up a game window , utilize easyx Graphics library , Set a classic 640*480 A window the size of . The window is set , Then we can define snake , We use structure to define the type of snake , What data are needed to analyze snakes , We first need to know how long the snake is , Easy to set the length of the snake at the beginning of the game , And the statistics of snake length after the game , Then we use int n To indicate the length of the snake . Snakes have to have a moving direction in the process of moving , So we also need to set one int direction To indicate the direction in which the snake moves , Because there are only four directions , Let's just enumerate the four directions , Then the moving direction of the snake is expressed by enumerating variables

// Enumeration direction 
enum direction
{
	up = 72,
	down = 80,
	left = 75,
	right = 77
};

Secondly, we need to know the coordinates of each section of the snake's body , In this way, we use coordinates to make the snake move , And draw the snake on the window , Because the snake's body has many knots , The coordinates have x , y Two values . Let's define the coordinates separately as the structure , Then each section of the body corresponds to a coordinate , We use arrays to represent the body

// Define the coordinates of the snake 
struct coor
{
	int x;
	int y;
}coor;

The final definition of snake is as follows

// Define the data type of snake 
struct snake
{
	int n = 3;
	direction site;
	coor szb[NUM];
}snake;

// among NUM Is the maximum value of the array, that is, the longest length of the snake's body , Self defined 

Define the type of snake , Next, we initialize the snake as follows , Write an initialization function , initsnake() Suppose the length of the snake is 3, To the left , The coordinates are

    snake.n = 3;
	snake.site = left;
	snake.szb[0].x = 320;
	snake.szb[0].y = 240;
	snake.szb[1].x = 310;
	snake.szb[1].y = 240;
	snake.szb[2].x = 300;
	snake.szb[2].y = 240;	

Once the initialization is complete , We will draw the snake on the window , Write a Drawsnake() function , It's actually a cycle , Take the length of the snake as the judging condition , Start from the coordinates of the snake head and draw in turn , Draw a rectangle or a circle , Here I use a rectangle

void Drawsnake()
{	
	for (int i = 0; i < snake.n; i++)
	{
		rectangle(snake.szb[i].x, snake.szb[i].y, snake.szb[i].x+10, snake.szb[i].y+10);
	}
}

After the painting is finished , Next, let the snake move , That's key , How to make the snake move , Analysis can be seen , The principle of snake movement is to make the coordinates of the snake head constantly change in a certain direction , The body changes with the snake head , Every time the coordinates change, the snake's body is redrawn , Because this process is fast enough , We use the processing speed of Sleep() Delay a little longer , It can form the frame rate that our eyes can recognize , So I can see that the snake moves continuously . Since we need to constantly change the coordinates of the snake head , And repaint the snake's body , Then put these two functions into the loop , Snake's movement we write a Movesnake().

int main()
{
    initgraph(640, 480);
	initgame();

    while (ture)
   {
     cleardevice();
     Movesnake();
     Drawsnake();
     Sleep(100);
   }
 
}

So how to make the coordinates of the snake constantly change in a certain direction ? Next, we will solve it carefully Movesnake(), First of all, we need to determine which direction to move , Remember when defining snakes , Set a direction variable site Well , Now it comes in handy . When we initialize , Initialize this variable and move it to the left , Then the program converts the coordinates of the snake head x Reduce 10, That is, it changes to the left 10 Pixels , Because in the cycle , as long as site The value of does not change , The snake head moves all the way to the left , The coordinates of the second section of the body move to the original position of the snake head , The coordinates of the other body segments move to the coordinates of the previous body segment , This enables the snake to move , Don't forget to add one cleardevice() function , Clear the last drawing .

switch (snake.site)
	{
		case up:
			snake.szb[0].y-=10;
			break;
		case down:
			snake.szb[0].y+=10;
			break;
		case left:
			snake.szb[0].x-=10;
			break;
		case right:
			snake.szb[0].x+=10;
			break;
  	}




for (int i = snake.n - 1; i > 0; i--)  // Replace the coordinates of each section of the snake's body with the coordinates of the previous section 
	{
		snake.szb[i].x = snake.szb[i - 1].x;
		snake.szb[i].y = snake.szb[i - 1].y;
	}

After the snake moves , Next is when the snake is moving , Change of direction , If you don't let the snake change its direction , There's no way to play , First of all, the direction of the snake head will change only when we press the direction key , Then first set a variable to receive the direction keys we press , Then assign this direction key to the direction variable of snake head , Let's write a Chdirection() Function to implement

void Chdirection()
{
	char key;
	key = _getch();
	
	switch(key)
	{
	case up:
		if (snake.site != down)
		{
			snake.site = up;
		}
		break;
	case down:
		if (snake.site != up)
		{
			snake.site = down;
		}
		break;
	case left:
		if (snake.site != right)
		{
			snake.site = left;
		}
		break;
	case right:
		if (snake.site != left)
		{
			snake.site = right;
		}
		break;
	}
}

Why should we add if Judgment sentence , In fact, it is to prevent the snake from turning around directly , This is inconsistent with reality , The U-turn in the display should be in circles .

  Actually , It is also possible to turn around directly , It's quite interesting , Drive at both ends like a train , ha-ha , If you are interested, you can try .

The problem of steering is solved , But how does the program know when to turn ? Because this program is placed in a loop , We might as well add a judgment sentence , use kbhit() Function to detect whether the player pressed the key , Return to true value if pressed , Enter the steering function , And determine where to turn inside , It is false without pressing , Do not enter the steering function .

int main()
{
    initgraph(640, 480);
	initgame();

    while (ture)
   {
     cleardevice();
     Movesnake();
     Drawsnake();
     Sleep(100);

     if ( kbhit() )
      {
        Chdirection();     
      }
    
   }
 
}

The little snake can run , Next is to eat food , How to achieve the effect of eating food ? Again , We need to define a data type for food , The first is the coordinates of food , The second is the state of the food at the moment , Was it eaten or not , Status we use bool Variable

// Define the data type of food 
struct food
{
	int x;
	int y;
	bool state;
}food;

Then we return to the initialization function , Set the state of the first food , Defined as true, It means being eaten , Why is it set to be eaten , I'll explain later , We then write Createfood(), To create food , Is to attach random values to the coordinates of food , Random values are used to generate seeds , Once we create a food , The moment of creation , The state of food needs to be changed to false, It means not being eaten .

void Creatfood()
{
	while (1)
	{
		food.x = rand() % 62 * 10;
		food.y = rand() % 46 * 10;
		if (food.x >= 20 && food.y >= 20)
		{
			food.state = false;
			break;
		}
	}
}
  
// I don't want food to be generated to the boundary point 

So when will food be produced , Of course, the state of food is true It means being eaten , This is why we should set the state of food at the beginning to true, Just to make a food for the start . Also use a judgment statement

int main()
{
	initgraph(LENGTH, WIDTH);
	initgame();

	while (1)
	{
		if (food.state)
		{
		Creatfood();
		}  
		cleardevice();
		Movesnake();
		Drawsnake();
		Drawfood();
		Sleep(100);	
		EndBatchDraw();
		if (_kbhit())
		{
		Chdirection();
		}
	}

The food is created , Now there is only one last step left , That is the process of eating , Just write one Eatfood(), When the coordinates of the snake head coincide with the coordinates of the food, you can eat , Then the state of the food changes to true, The length of the snake increases 1.

void Eatfood()
{
	if (snake.szb[0].x == food.x  &&  snake.szb[0].y == food.y)
	{
		snake.n++;
		food.state = true;
	}
}

That's it , Simple snake eating is done , There is also a drawing of food , This is quite simple , All partners, please realize it by yourself .

int main()
{
	initgraph(LENGTH, WIDTH);
	initgame();

	while (1)
	{
		if (food.state)
		{
		Creatfood();
		}  
		
        cleardevice();
		Movesnake();
		Drawsnake();
		Drawfood();
		Eatfood();
		Sleep(100);	
		
        if (_kbhit())
		{
		Chdirection();
		}
	}

	getchar();	
}

原网站

版权声明
本文为[Langyu 123]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207040602236436.html