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
#include
(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, the rand()
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 a time_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 file <time.h></time.h>
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 the clock()
function. The following is the relevant knowledge:
clock() is a timing function in C/C, and its related data types It’s clock_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 <windows.h> #include <stdlib.h> #include <conio.h> #include <time.h> #include <cstring> #include <cstdio> #include <iostream> #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<N;i++) { cout << '\t'; for(j=0;j<N;j++) cout<<s[i][j]<<' '; // 输出贪吃蛇棋盘 if(i==2) cout << "\t等级:" << grade; if(i==6) cout << "\t速度:" << gamespeed; if(i==10) cout << "\t得分:" << score << "分" ; if(i==14) cout << "\t暂停:按一下空格键" ; if(i==18) cout << "\t继续:按两下空格键" ; cout<<endl; } } //输入选择等级 void snake_map::getgrade() { cin>>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 欢迎进入贪吃蛇游戏!"<<endl;//欢迎界面; cout<<"\n\n\n\t\t\t 按任意键马上开始。。。"<<endl;//准备开始;; getch(); while( ctn=='y' ) { system("cls"); // 清屏 snake_map snake; snake.initialize(); cout << "\n\n请输入数字选择游戏等级:" << endl; cout << "\n\n\n\t\t\t1.等级一:速度 1000 \n\n\t\t\t2.等级二:速度 800 \n\n\t\t\t3.等级三:速度 600 "; cout << "\n\n\t\t\t4.等级四:速度 400 \n\n\t\t\t5.等级五:速度 200 \n\n\t\t\t6.等级六:速度 100 \n\n\t\t\t7.自动升级模式" << endl; snake.getgrade();//获取等级 for(int i=1;i<=4;i++) { position[i].initialize(i);//初始化坐标 } snake.setpoint(); // 产生第一个米 do { snake.show_game(); nodead = snake.updata_game(); }while(nodead); system("cls"); //清屏 cout << "\n\n\n\t\t\t\tGameover!\n\n"<<endl; snake.display();//输出等级/得分情况 cout << "\n\n\n\t\t 是否选择继续游戏?输入 y 继续,n 退出" << endl; cin >> 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!

C++是一种广泛使用的面向对象的计算机编程语言,它支持您与之交互的大多数应用程序和网站。你需要编译器和集成开发环境来开发C++应用程序,既然你在这里,我猜你正在寻找一个。我们将在本文中介绍一些适用于Windows11的C++编译器的主要推荐。许多审查的编译器将主要用于C++,但也有许多通用编译器您可能想尝试。MinGW可以在Windows11上运行吗?在本文中,我们没有将MinGW作为独立编译器进行讨论,但如果讨论了某些IDE中的功能,并且是DevC++编译器的首选

在C++程序开发中,当我们声明了一个变量但是没有对其进行初始化,就会出现“变量未初始化”的报错。这种报错经常会让人感到很困惑和无从下手,因为这种错误并不像其他常见的语法错误那样具体,也不会给出特定的代码行数或者错误类型。因此,下面我们将详细介绍变量未初始化的问题,以及如何解决这个报错。一、什么是变量未初始化错误?变量未初始化是指在程序中声明了一个变量但是没有

C++是一门广受欢迎的编程语言,但是在使用过程中,经常会出现“未定义的引用”这个编译错误,给程序的开发带来了诸多麻烦。本篇文章将从出错原因和解决方法两个方面,探讨“未定义的引用”错误的解决方法。一、出错原因C++编译器在编译一个源文件时,会将它分为两个阶段:编译阶段和链接阶段。编译阶段将源文件中的源码转换为汇编代码,而链接阶段将不同的源文件合并为一个可执行文

如何优化C++开发中的文件读写性能在C++开发过程中,文件的读写操作是常见的任务之一。然而,由于文件读写是磁盘IO操作,相对于内存IO操作来说会更为耗时。为了提高程序的性能,我们需要优化文件读写操作。本文将介绍一些常见的优化技巧和建议,帮助开发者在C++文件读写过程中提高性能。使用合适的文件读写方式在C++中,文件读写可以通过多种方式实现,如C风格的文件IO

C++是一门强大的编程语言,它支持使用类模板来实现代码的复用,提高开发效率。但是在使用类模板时,可能会遭遇编译错误,其中一个比较常见的错误是“无法为类模板找到实例化”(error:cannotfindinstantiationofclasstemplate)。本文将介绍这个问题的原因以及如何解决。问题描述在使用类模板时,有时会遇到以下错误信息:e

iostream头文件包含了操作输入输出流的方法,比如读取一个文件,以流的方式读取;其作用是:让初学者有一个方便的命令行输入输出试验环境。iostream的设计初衷是提供一个可扩展的类型安全的IO机制。

c++初始化数组的方法:1、先定义数组再给数组赋值,语法“数据类型 数组名[length];数组名[下标]=值;”;2、定义数组时初始化数组,语法“数据类型 数组名[length]=[值列表]”。

C++是一种流行的编程语言,它强大而灵活,适用于各种应用程序开发。在使用C++开发应用程序时,经常需要处理各种信号。本文将介绍C++中的信号处理技巧,以帮助开发人员更好地掌握这一方面。一、信号处理的基本概念信号是一种软件中断,用于通知应用程序内部或外部事件。当特定事件发生时,操作系统会向应用程序发送信号,应用程序可以选择忽略或响应此信号。在C++中,信号可以


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
