C++ preparation of the entry version of snake, as long as you want to learn can learn
Same old rule, renderings first
The code is written with a native c++ console program. The algorithm is worth learning.
First we need to write a snake structure.
struct body
{
int x,y;
body *last,*next;
body(){last=next=NULL; } }*head;Copy the code
In the body of the snake, there is next to connect the snake with the snake, and last to mark the tail of the snake.
int Rand(int l,int r)
{
return rand()%(r-l+1)+l;
}
Copy the code
Because the food the snake eats needs to be randomly generated, the position and direction of the snake at the beginning are all random, so we encapsulate a random function.
You need to simulate true randomness
srand((unsigned)time(NULL));
Copy the code
The map plus the snake, all the data is written in a two-dimensional array
char map[23] [53];
Copy the code
The walls need to be written in the beginning
/ / map
for( i=0; i<22; i++)for(int j=0; j<52; j++) map[i][j]=' ';
for( i=0; i<52; i++) map[0][i]=map[21][i]=The '#';
for( i=0; i<22; i++) map[i][0]=map[i][51] =The '#';
Copy the code
The position and direction of the snake need to be generated
// Generate the position of the snake
srand((unsigned)time(NULL));
head=new body;
head->x=Rand(5.15),head->y=Rand(10.40);
// Generate the direction of the snake
d=Rand(0.3);
switch(d)
{
case 0:map[head->x][head->y]='|'; map[head->x+1][head->y]='|';break;
case 1:map[head->x][head->y]=The '-'; map[head->x][head->y+1] =The '-';break;
case 2:map[head->x][head->y]='|'; map[head->x- 1][head->y]='|';break;
case 3:map[head->x][head->y]=The '-'; map[head->x][head->y- 1] =The '-';break;
}
Copy the code
Finally, we need to control the movement of the snake body, and here we need to write our own joystick.
for(int i=0; i<=10; i++) {if(GetKeyState('S') <0&&d! =2)
x=0;
if(GetKeyState('D') <0&&d! =3)
x=1;
if(GetKeyState('W') <0&&d! =0)
x=2;
if(GetKeyState('A') <0&&d! =1)
x=3;
Sleep(10);
}
d=x;
eat=(map[head->x+dd[d][0]][head->y+dd[d][1= =]]The '*');
Update(head,head->x+dd[d][0],head->y+dd[d][1]);
Copy the code
Eat is to judge whether food is eaten or not. Update is to draw each step of the snake.
If you need the source code, you can find me in the background.