Home>Article>Backend Development> What is the c++ snake code?
c The snake code is [snake_position position[(N-2)*(N-2) 1], void snake_position::initialize(int &j), {x = 1;y = j;} char s[N][N]].
【Related learning recommendations:C video tutorial】
Analysis ideas
Let’s talk about the entire design idea of Snake:
1.
The characteristic of Snake is that after randomly generating food, it can be controlled by the up, down, left, and right direction keys. The movement of the greedy snake:
When it encounters food, it eats it, thereby increasing its body length by one. Here, "#" is used as the snake head, and "*" is used as the snake body and food.
So I thought, how can the food produced be random? By consulting the information, we learned that in the time.h header file, the rand() function is defined to generate random numbers. The following is relevant knowledge:
Overview
rand() function is a random function that generates random numbers. There are also srand() functions in C language.
Details
(1) To use this function, you should first include the header file stdlib.h at the beginning
#include8e359799bdf1a571032ba13cc96acda9(C It is recommended to use #included8f7f322a34e54ad4f8b20b7844867c9, the same below)
(2) In the standard C library, the function rand() can generate a random number between 0~RAND_MAX, where RAND_MAX is an integer defined in stdlib.h, which related to the system.
(3) The rand() function has no input parameters and is directly referenced through the expression rand(); for example, you can use the following statement to print two random numbers:
printf("Random numbers are: %i %i\n",rand(),rand());
(4) Because the rand() function generates integers in a specified order, the same two values will be printed every time the above statement is executed. Therefore, the randomness in C language is not truly random, and is sometimes called pseudo-random number. .
(5) In order to enable the program to generate a new sequence of random values every time it is executed, we usually provide a new random seed to the random number generator. The function srand() (from stdlib.h) can seed a random number generator. As long as the seeds are different, therand()
function will generate different random number sequences. srand() is called the initializer of the random number generator.
Since the srand() function was not used at the beginning, after running it multiple times, it was found that the food positions generated after each run were consistent, and the purpose of randomness was not truly achieved. Therefore, the srand() function is used, and the time() function is used to call a system time each time as the seed of srand(). Since the system time of each call is different, the seed is different each time, so that the rand() function achieves the purpose of random numbers. The following is relevant knowledge about the time() function:
The time() function returns the number of seconds of the current time since the Unix epoch (January 1 1970 00:00:00 GMT).
is mainly used to obtain the current system time. The returned result is atime_t
type, and its value represents the time since UTC (Coordinated Universal Time) January 1, 1970 00:00: The number of seconds from 00 (called the Epoch time in UNIX systems) to the current moment. Then call the localtime function to convert the UTC time represented by time_t to local time (we are in zone 8, which is 8 hours longer than UTC) and convert it into a struct tm type. Each data member of this type represents the year, month, day, hour, minute and second respectively. The header filefaa9dcf97695d0b6f494e040242d8d0c
needs to be included.
C standard library function
time_t time(time_t *t);
If t is a null pointer, return the current time directly. If t is not a null pointer, while returning the current time, the return value is assigned to the memory space pointed to by t.
In this way, random numbers are generated through the rand() function, and after moduloing them, random numbers within a certain range are obtained.
2.
Then there is the problem of eating. When the snake head encounters a food (the food is in the direction of the greedy snake), it turns the food into a snake head, and then The original snake head is changed into a snake body, thereby achieving the purpose of eating.
What if there is no food? Just keep going in the original direction or the direction you pressed the keyboard.
3.
The following is the problem of implementation. How to display each dynamic? That is to say, the greedy snake moves forward step by step. How is this achieved?
Here I used theclock()
function. The following is the relevant knowledge:
clock() is a timing function in C/C, and its related data types It’sclock_t
. In MSDN, the clock function is defined as follows:
clock_t clock(void) ;
Simply put, it is the time the program takes up the CPU from startup to function call. This function returns the number of CPU clock timing units (clock ticks) from "starting this program process" to "calling the clock() function in the program", which is called wall clock time (wal-clock) in MSDN; if the wall clock If the time is not available, -1 is returned. Among them, clock_t is the data type used to save time.
Therefore, by definition
int start = clock();while(clock()-start<=gamespeed);
这样一个方式来达到了延时的目的,延时的时间则根据gamespeed的值来确定,当gamespeed值越小时,延时时间越短。经过延时后,再执行下一步代码,从而实现了贪吃蛇自动前进的功能和控制其前进的速度啦。
然而,仅仅有这些还是不行的,还需要解决输出问题。
通过查阅资料得知,system(“cls”);
具有清屏的功能,清除当前屏幕上的内容,进行下一步的输出,因此我便使用了每动一下都要进行清屏,然后将贪吃蛇棋盘整个画面进行输出。
四、
为了增加游戏的娱乐性,我又从中加入了等级选择功能,通过输入数字来选择等级,等级越高,贪吃蛇移动速度越快,而且得分越高。得分规则:score += grade*20;
考虑到游戏的功能性,在游戏结束后输出得分情况,并提示是否继续游戏,而不是直接退出游戏,这样用户就不必每次游戏失败后重新打开程序进行游戏,而是通过选择的方式决定继续游戏或者退出游戏。
而且加入暂停功能,当玩家玩累了,需要暂停的时候,按下空格(space)键实现暂停,
但由于我的原因,无法解决需要按两下空格才能继续游戏的bug,就暂定为按两下空格键继续游戏吧。
#include#include #include #include #include #include #include #define N 22 using namespace std; int gameover; int x1, y1; // 随机出米 int x,y; long start; //======================================= //类的实现与应用initialize //======================================= //下面定义贪吃蛇的坐标类 class snake_position { public: int x,y; //x表示行,y表示列 snake_position(){}; void initialize(int &);//坐标初始化 }; snake_position position[(N-2)*(N-2)+1]; //定义贪吃蛇坐标类数组,有(N-2)*(N-2)个坐标 void snake_position::initialize(int &j) { x = 1; y = j; } //下面定义贪吃蛇的棋盘图 class snake_map { private: char s[N][N];//定义贪吃蛇棋盘,包括墙壁。 int grade, length; int gamespeed; //前进时间间隔 char direction; // 初始情况下,向右运动 int head,tail; int score; bool gameauto; public: snake_map(int h=4,int t=1,int l=4,char d=77,int s=0):length(l),direction(d),head(h),tail(t),score(s){} void initialize(); //初始化函数 void show_game(); int updata_game(); void setpoint(); void getgrade(); void display(); }; //定义初始化函数,将贪吃蛇的棋盘图进行初始化 void snake_map::initialize() { int i,j; for(i=1;i<=3;i++) s[1][i] = '*'; s[1][4] = '#'; for(i=1;i<=N-2;i++) for(j=1;j<=N-2;j++) s[i][j]=' '; // 初始化贪吃蛇棋盘中间空白部分 for(i=0;i<=N-1;i++) s[0][i] = s[N-1][i] = '-'; //初始化贪吃蛇棋盘上下墙壁 for(i=1;i<=N-2;i++) s[i][0] = s[i][N-1] = '|'; //初始化贪吃蛇棋盘左右墙壁 } //============================================ //输出贪吃蛇棋盘信息 void snake_map::show_game() { system("cls"); // 清屏 int i,j; cout << endl; for(i=0;i >grade; while( grade>7 || grade<1 ) { cout << "请输入数字1-7选择等级,输入其他数字无效" << endl; cin >> grade; } switch(grade) { case 1: gamespeed = 1000;gameauto = 0;break; case 2: gamespeed = 800;gameauto = 0;break; case 3: gamespeed = 600;gameauto = 0;break; case 4: gamespeed = 400;gameauto = 0;break; case 5: gamespeed = 200;gameauto = 0;break; case 6: gamespeed = 100;gameauto = 0;break; case 7: grade = 1;gamespeed = 1000;gameauto = 1;break; } } //输出等级,得分情况以及称号 void snake_map::display() { cout << "\n\t\t\t\t等级:" << grade; cout << "\n\n\n\t\t\t\t速度:" << gamespeed; cout << "\n\n\n\t\t\t\t得分:" << score << "分" ; } //随机产生米 void snake_map::setpoint() { srand(time(0)); do { x1 = rand() % (N-2) + 1; y1 = rand() % (N-2) + 1; }while(s[x1][y1]!=' '); s[x1][y1]='*'; } char key; int snake_map::updata_game() { gameover = 1; key = direction; start = clock(); while((gameover=(clock()-start<=gamespeed))&&!kbhit()); //如果有键按下或时间超过自动前进时间间隔则终止循环 if(gameover) { getch(); key = getch(); } if(key == ' ') { while(getch()!=' '){};//这里实现的是按空格键暂停,按空格键继续的功能,但不知为何原因,需要按两下空格才能继续。这是个bug。 } else direction = key; switch(direction) { case 72: x= position[head].x-1; y= position[head].y;break; // 向上 case 80: x= position[head].x+1; y= position[head].y;break; // 向下 case 75: x= position[head].x; y= position[head].y-1;break; // 向左 case 77: x= position[head].x; y= position[head].y+1; // 向右 } if(!(direction==72||direction==80||direction==75 ||direction==77)) // 按键非方向键 gameover = 0; else if(x==0 || x==N-1 ||y==0 || y==N-1) // 碰到墙壁 gameover = 0; else if(s[x][y]!=' '&&!(x==x1&&y==y1)) // 蛇头碰到蛇身 gameover = 0; else if(x==x1 && y==y1) { // 吃米,长度加1 length ++; if(length>=8 && gameauto) { length -= 8; grade ++; if(gamespeed>=200) gamespeed -= 200; // 改变贪吃蛇前进速度 else gamespeed = 100; } s[x][y]= '#'; //更新蛇头 s[position[head].x][position[head].y] = '*'; //吃米后将原先蛇头变为蛇身 head = (head+1) % ( (N-2)*(N-2) ); //取蛇头坐标 position[head].x = x; position[head].y = y; show_game(); gameover = 1; score += grade*20; //加分 setpoint(); //产生米 } else { // 不吃米 s[position[tail].x][position[tail].y]=' ';//将蛇尾置空 tail= (tail+1) % ( (N-2) * (N-2) );//更新蛇尾坐标 s[position[head].x][position[head].y]='*'; //将蛇头更为蛇身 head= (head+1) % ( (N-2) * (N-2) ); position[head].x = x; position[head].y = y; s[position[head].x][position[head].y]='#'; //更新蛇头 gameover = 1; } return gameover; } //==================================== //主函数部分 //==================================== int main() { char ctn = 'y'; int nodead; cout<<"\n\n\n\n\n\t\t\t 欢迎进入贪吃蛇游戏!"< > ctn; } return 0; }
The above is the detailed content of What is the c++ snake code?. For more information, please follow other related articles on the PHP Chinese website!