这个代码大部分是抄的,我负责解释一下
原作者视频地址:
https://www.bilibili.com/video/av85378627?p=1
下面看源码
#include <stdio.h>
#include <conio.h>
#include <Windows.h>
#include <time.h>
void main(){
int hx = 7, hy = 7, map[900] = {0}, i = 1, len = 4;
//hx,hy为头坐标 map[900]为地图(30*30) len为蛇长
char c = 'd',ch = 'd',tr[1801] = {0};
//c为输入缓存,tr[1801]是要打印的字符串(防闪烁)
srand((unsigned)time(NULL));//随机数种子
system("mode con cols=60 lines=30");
//设置窗口大小,cols为宽度,lines为长度
for(map[rand()%900] = -1 ; 1 ; Sleep(200)){
//死循环 食物赋初值 延迟200毫秒 -1为食物 大于0的为蛇身 0为空气
if(_kbhit()&&(c = _getch()))//检测按键
if(c == 'a'&&ch != 'd' || c == 'd'&&ch != 'a' ||
c == 'w'&&ch != 's' || c == 's'&&ch != 'w')ch = c;
//检测按键是否冲突并赋值给ch
if(ch == 'a'&&hx-- < 0||ch == 'd'&&hx++ > 29||
ch == 'w'&&--hy < 0||ch == 's'&&++hy > 29)exit(0);
//检测蛇头是否越界,如果是就退出,并进行移动
if(map[hy * 30 + hx] && (map[ hy * 30 + hx] > 0 ? exit(0),1 : len++))
/*'&&'左边检测是否为0或非0,0为假,非0为真,如果为真,
并且大于0的话就退出(检测是否撞到自己),否则(剩下的情况就是-1),加蛇的身长,此时吃到食物*/
for(i = rand()%900; map[i] < 1 ? map[i] = -1,0 : 1; i = rand()%900);
//随机数赋初值给i ;如果map[i]不是蛇(是空地)就生成一个食物并退出循环,否则继续循环
else for(i=0; i < 900; i++)map[i] > 0 ? map[i]-- : 0;
for(system("cls"),map[hy * 30 +hx] = len,i = 0;i<1800;i++){
if(map[i/2]==0)tr[i]=' ';
else if(map[i/2] > 0)tr[i] = (i % 2) ? ')' : '(';
//提示一下 i为整形,所以i/2为整数(去尾法)
else tr[i] = '0';
//剩下的情况为-1
}
printf(tr);//打印字符串
}
}
效果如下
最后撞自己死了,可以看到他没有闪烁,基本功能也差不多做出来了
原作者视频地址:
https://www.bilibili.com/video/av85378627?p=1