c语言贪吃蛇最简单代码手机(c语言简易贪吃蛇代码)

http://www.itjxue.com  2023-02-02 14:14  来源:未知  点击次数: 

寻找贪吃蛇c++的代码

贪吃蛇游戏C语言源代码学习

源代码下载地址为:

阅读学习了源代码,并做了简单的注释和修改,里面只用了链表数据结构,非常适合C语言入门者学习阅读。

程序可在VS2013下编译运行。

1 #includestdio.h ?2 #includetime.h ?3 #includewindows.h ?4 #includestdlib.h ?5 ??6 #define U 1 ?7 #define D 2 ?8 #define L 3

9 #define R 4 ? ? ? //蛇的状态,U:上 ;D:下;L:左 R:右 10 ?11 typedef struct SNAKE //蛇身的一个节点 12 { 13 ? ? int x; 14 ? ? int y; 15 ? ? struct SNAKE *next; 16 }snake; 17 ?18 //全局变量// 19 int score = 0, add = 10;//总得分与每次吃食物得分。 20 int status, sleeptime = 200;//每次运行的时间间隔 21 snake *head, *food;//蛇头指针,食物指针 22 snake *q;//遍历蛇的时候用到的指针 23 int endGamestatus = 0; //游戏结束的情况,1:撞到墙;2:咬到自己;3:主动退出游戏。 24 ?25 //声明全部函数// 26 void Pos(); 27 void creatMap(); 28 void initSnake(); 29 int biteSelf(); 30 void createFood(); 31 void cantCrossWall(); 32 void snakeMove(); 33 void pause(); 34 void runGame(); 35 void initGame(); 36 void endGame(); 37 void gameStart(); 38 ?39 void Pos(int x, int y)//设置光标位置 40 { 41 ?? ?COORD pos; 42 ?? ?HANDLE hOutput; 43 ? ? pos.X = x; 44 ? ? pos.Y = y; 45 ? ? hOutput = GetStdHandle(STD_OUTPUT_HANDLE);//返回标准的输入、输出或错误的设备的句柄,也就是获得输入、输出/错误的屏幕缓冲区的句柄 46 ?? ?SetConsoleCursorPosition(hOutput, pos); 47 } 48 ?49 void creatMap()//创建地图 50 { 51 ? ? int i; 52 ? ? for (i = 0; i58; i += 2)//打印上下边框 53 ?? ?{ 54 ? ? ? ? Pos(i, 0); 55 ? ? ? ? printf("■");//一个方块占两个位置 56 ? ? ? ? Pos(i, 26); 57 ? ? ? ? printf("■"); 58 ?? ?} 59 ? ? for (i = 1; i26; i++)//打印左右边框 60 ?? ?{ 61 ? ? ? ? Pos(0, i); 62 ? ? ? ? printf("■"); 63 ? ? ? ? Pos(56, i); 64 ? ? ? ? printf("■"); 65 ?? ?} 66 } 67 ?68 void initSnake()//初始化蛇身 69 { 70 ? ? snake *tail; 71 ? ? int i; 72 ? ? tail = (snake*)malloc(sizeof(snake));//从蛇尾开始,头插法,以x,y设定开始的位置// 73 ? ? tail-x = 24; 74 ? ? tail-y = 5; 75 ? ? tail-next = NULL; 76 ? ? for (i = 1; i = 4; i++)//初始长度为4 77 ?? ?{ 78 ? ? ? ? head = (snake*)malloc(sizeof(snake)); 79 ? ? ? ? head-next = tail; 80 ? ? ? ? head-x = 24 + 2 * i; 81 ? ? ? ? head-y = 5; 82 ? ? ? ? tail = head; 83 ?? ?} 84 ? ? while (tail != NULL)//从头到为,输出蛇身 85 ?? ?{ 86 ? ? ? ? Pos(tail-x, tail-y); 87 ? ? ? ? printf("■"); 88 ? ? ? ? tail = tail-next; 89 ?? ?} 90 } 91 //?? 92 int biteSelf()//判断是否咬到了自己 93 { 94 ? ? snake *self; 95 ? ? self = head-next; 96 ? ? while (self != NULL) 97 ?? ?{ 98 ? ? ? ? if (self-x == head-x self-y == head-y) 99 ?? ? ? ?{100 ? ? ? ? ? ? return 1;101 ?? ? ? ?}

102 ? ? ? ? self = self-next;103 ?? ?}104 ? ? return 0;105 }106 107 void createFood()//随机出现食物108 {109 ? ? snake *food_1;110 ? ? srand((unsigned)time(NULL));//为了防止每次产生的随机数相同,种子设置为time111 ? ? food_1 = (snake*)malloc(sizeof(snake));112 ? ? while ((food_1-x % 2) != 0) ? ?//保证其为偶数,使得食物能与蛇头对其113 ?? ?{114 ? ? ? ? food_1-x = rand() % 52 + 2;115 ?? ?}116 ? ? food_1-y = rand() % 24 + 1;117 ? ? q = head;118 ? ? while (q-next == NULL)119 ?? ?{120 ? ? ? ? if (q-x == food_1-x q-y == food_1-y) //判断蛇身是否与食物重合121 ?? ? ? ?{122 ? ? ? ? ? ? free(food_1);123 ?? ? ? ? ? ?createFood();124 ?? ? ? ?}125 ? ? ? ? q = q-next;126 ?? ?}127 ? ? Pos(food_1-x, food_1-y);128 ? ? food = food_1;129 ? ? printf("■");130 }131 132 void cantCrossWall()//不能穿墙133 {134 ? ? if (head-x == 0 || head-x == 56 || head-y == 0 || head-y == 26)135 ?? ?{136 ? ? ? ? endGamestatus = 1;137 ?? ? ? ?endGame();138 ?? ?}139 }140 141 void snakeMove()//蛇前进,上U,下D,左L,右R142 {143 ? ? snake * nexthead;144 ?? ?cantCrossWall();145 146 ? ? nexthead = (snake*)malloc(sizeof(snake));147 ? ? if (status == U)148 ?? ?{149 ? ? ? ? nexthead-x = head-x;150 ? ? ? ? nexthead-y = head-y - 1;151 ? ? ? ? if (nexthead-x == food-x nexthead-y == food-y)//如果下一个有食物//152 ?? ? ? ?{153 ? ? ? ? ? ? nexthead-next = head;154 ? ? ? ? ? ? head = nexthead;155 ? ? ? ? ? ? q = head;156 ? ? ? ? ? ? while (q != NULL)157 ?? ? ? ? ? ?{158 ? ? ? ? ? ? ? ? Pos(q-x, q-y);159 ? ? ? ? ? ? ? ? printf("■");160 ? ? ? ? ? ? ? ? q = q-next;161 ?? ? ? ? ? ?}162 ? ? ? ? ? ? score = score + add;163 ?? ? ? ? ? ?createFood();164 ?? ? ? ?}165 ? ? ? ? else ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //如果没有食物//166 ?? ? ? ?{167 ? ? ? ? ? ? nexthead-next = head;168 ? ? ? ? ? ? head = nexthead;169 ? ? ? ? ? ? q = head;170 ? ? ? ? ? ? while (q-next-next != NULL)171 ?? ? ? ? ? ?{172 ? ? ? ? ? ? ? ? Pos(q-x, q-y);173 ? ? ? ? ? ? ? ? printf("■");174 ? ? ? ? ? ? ? ? q = q-next;175 ?? ? ? ? ? ?}176 ? ? ? ? ? ? Pos(q-next-x, q-next-y);177 ? ? ? ? ? ? printf(" ?");178 ? ? ? ? ? ? free(q-next);179 ? ? ? ? ? ? q-next = NULL;180 ?? ? ? ?}181 ?? ?}182 ? ? if (status == D)183 ?? ?{184 ? ? ? ? nexthead-x = head-x;185 ? ? ? ? nexthead-y = head-y + 1;186 ? ? ? ? if (nexthead-x == food-x nexthead-y == food-y) ?//有食物187 ?? ? ? ?{188 ? ? ? ? ? ? nexthead-next = head;189 ? ? ? ? ? ? head = nexthead;190 ? ? ? ? ? ? q = head;191 ? ? ? ? ? ? while (q != NULL)192 ?? ? ? ? ? ?{193 ? ? ? ? ? ? ? ? Pos(q-x, q-y);194 ? ? ? ? ? ? ? ? printf("■");195 ? ? ? ? ? ? ? ? q = q-next;196 ?? ? ? ? ? ?}197 ? ? ? ? ? ? score = score + add;198 ?? ? ? ? ? ?createFood();199 ?? ? ? ?}200 ? ? ? ? else ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //没有食物201 ?? ? ? ?{202 ? ? ? ? ? ? nexthead-next = head;203 ? ? ? ? ? ? head = nexthead;204 ? ? ? ? ? ? q = head;205 ? ? ? ? ? ? while (q-next-next != NULL)206 ?? ? ? ? ? ?{207 ? ? ? ? ? ? ? ? Pos(q-x, q-y);208 ? ? ? ? ? ? ? ? printf("■");209 ? ? ? ? ? ? ? ? q = q-next;210 ?? ? ? ? ? ?}211 ? ? ? ? ? ? Pos(q-next-x, q-next-y);212 ? ? ? ? ? ? printf(" ?");213 ? ? ? ? ? ? free(q-next);214 ? ? ? ? ? ? q-next = NULL;215 ?? ? ? ?}216 ?? ?}217 ? ? if (status == L)218 ?? ?{219 ? ? ? ? nexthead-x = head-x - 2;220 ? ? ? ? nexthead-y = head-y;221 ? ? ? ? if (nexthead-x == food-x nexthead-y == food-y)//有食物222 ?? ? ? ?{223 ? ? ? ? ? ? nexthead-next = head;224 ? ? ? ? ? ? head = nexthead;225 ? ? ? ? ? ? q = head;226 ? ? ? ? ? ? while (q != NULL)227 ?? ? ? ? ? ?{228 ? ? ? ? ? ? ? ? Pos(q-x, q-y);229 ? ? ? ? ? ? ? ? printf("■");230 ? ? ? ? ? ? ? ? q = q-next;231 ?? ? ? ? ? ?}232 ? ? ? ? ? ? score = score + add;233 ?? ? ? ? ? ?createFood();234 ?? ? ? ?}235 ? ? ? ? else ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//没有食物236 ?? ? ? ?{237 ? ? ? ? ? ? nexthead-next = head;238 ? ? ? ? ? ? head = nexthead;239 ? ? ? ? ? ? q = head;240 ? ? ? ? ? ? while (q-next-next != NULL)241 ?? ? ? ? ? ?{242 ? ? ? ? ? ? ? ? Pos(q-x, q-y);243 ? ? ? ? ? ? ? ? printf("■");244 ? ? ? ? ? ? ? ? q = q-next;245 ?? ? ? ? ? ?}246 ? ? ? ? ? ? Pos(q-next-x, q-next-y);247 ? ? ? ? ? ? printf(" ?");248 ? ? ? ? ? ? free(q-next);249 ? ? ? ? ? ? q-next = NULL;250 ?? ? ? ?}251 ?? ?}252 ? ? if (status == R)253 ?? ?{254 ? ? ? ? nexthead-x = head-x + 2;255 ? ? ? ? nexthead-y = head-y;256 ? ? ? ? if (nexthead-x == food-x nexthead-y == food-y)//有食物257 ?? ? ? ?{258 ? ? ? ? ? ? nexthead-next = head;259 ? ? ? ? ? ? head = nexthead;260 ? ? ? ? ? ? q = head;261 ? ? ? ? ? ? while (q != NULL)262 ?? ? ? ? ? ?{263 ? ? ? ? ? ? ? ? Pos(q-x, q-y);264 ? ? ? ? ? ? ? ? printf("■");265 ? ? ? ? ? ? ? ? q = q-next;266 ?? ? ? ? ? ?}267 ? ? ? ? ? ? score = score + add;268 ?? ? ? ? ? ?createFood();269 ?? ? ? ?}270 ? ? ? ? else ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //没有食物271 ?? ? ? ?{272 ? ? ? ? ? ? nexthead-next = head;273 ? ? ? ? ? ? head = nexthead;274 ? ? ? ? ? ? q = head;275 ? ? ? ? ? ? while (q-next-next != NULL)276 ?? ? ? ? ? ?{277 ? ? ? ? ? ? ? ? Pos(q-x, q-y);278 ? ? ? ? ? ? ? ? printf("■");279 ? ? ? ? ? ? ? ? q = q-next;280 ?? ? ? ? ? ?}281 ? ? ? ? ? ? Pos(q-next-x, q-next-y);282 ? ? ? ? ? ? printf(" ?");283 ? ? ? ? ? ? free(q-next);284 ? ? ? ? ? ? q-next = NULL;285 ?? ? ? ?}286 ?? ?}287 ? ? if (biteSelf() == 1) ? ? ? //判断是否会咬到自己288 ?? ?{289 ? ? ? ? endGamestatus = 2;290 ?? ? ? ?endGame();291 ?? ?}292 }293 294 void pause()//暂停295 {296 ? ? while (1)297 ?? ?{298 ? ? ? ? Sleep(300);299 ? ? ? ? if (GetAsyncKeyState(VK_SPACE))300 ?? ? ? ?{301 ? ? ? ? ? ? break;302 ?? ? ? ?}303 304 ?? ?}305 }306 307 void runGame()//控制游戏 ? ? ? ?308 {309 310 ? ? Pos(64, 15);311 ? ? printf("不能穿墙,不能咬到自己\n");312 ? ? Pos(64, 16);313 ? ? printf("用↑.↓.←.→分别控制蛇的移动.");314 ? ? Pos(64, 17);315 ? ? printf("F1 为加速,F2 为减速\n");316 ? ? Pos(64, 18);317 ? ? printf("ESC :退出游戏.space:暂停游戏.");318 ? ? Pos(64, 20);319 ? ? printf("C语言研究中心 ");320 ? ? status = R;321 ? ? while (1)322 ?? ?{323 ? ? ? ? Pos(64, 10);324 ? ? ? ? printf("得分:%d ?", score);325 ? ? ? ? Pos(64, 11);326 ? ? ? ? printf("每个食物得分:%d分", add);327 ? ? ? ? if (GetAsyncKeyState(VK_UP) status != D)328 ?? ? ? ?{329 ? ? ? ? ? ? status = U;330 ?? ? ? ?}331 ? ? ? ? else if (GetAsyncKeyState(VK_DOWN) status != U)332 ?? ? ? ?{333 ? ? ? ? ? ? status = D;334 ?? ? ? ?}335 ? ? ? ? else if (GetAsyncKeyState(VK_LEFT) status != R)336 ?? ? ? ?{337 ? ? ? ? ? ? status = L;338 ?? ? ? ?}339 ? ? ? ? else if (GetAsyncKeyState(VK_RIGHT) status != L)340 ?? ? ? ?{341 ? ? ? ? ? ? status = R;342 ?? ? ? ?}343 ? ? ? ? else if (GetAsyncKeyState(VK_SPACE))344 ?? ? ? ?{345 ?? ? ? ? ? ?pause();346 ?? ? ? ?}347 ? ? ? ? else if (GetAsyncKeyState(VK_ESCAPE))348 ?? ? ? ?{349 ? ? ? ? ? ? endGamestatus = 3;350 ? ? ? ? ? ? break;351 ?? ? ? ?}352 ? ? ? ? else if (GetAsyncKeyState(VK_F1))353 ?? ? ? ?{354 ? ? ? ? ? ? if (sleeptime = 50)355 ?? ? ? ? ? ?{356 ? ? ? ? ? ? ? ? sleeptime = sleeptime - 30;357 ? ? ? ? ? ? ? ? add = add + 2;358 ? ? ? ? ? ? ? ? if (sleeptime == 320)359 ?? ? ? ? ? ? ? ?{360 ? ? ? ? ? ? ? ? ? ? add = 2;//防止减到1之后再加回来有错361 ?? ? ? ? ? ? ? ?}362 ?? ? ? ? ? ?}363 ?? ? ? ?}364 ? ? ? ? else if (GetAsyncKeyState(VK_F2))365 ?? ? ? ?{366 ? ? ? ? ? ? if (sleeptime350)367 ?? ? ? ? ? ?{368 ? ? ? ? ? ? ? ? sleeptime = sleeptime + 30;369 ? ? ? ? ? ? ? ? add = add - 2;370 ? ? ? ? ? ? ? ? if (sleeptime == 350)371 ?? ? ? ? ? ? ? ?{372 ? ? ? ? ? ? ? ? ? ? add = 1; ?//保证最低分为1373 ?? ? ? ? ? ? ? ?}374 ?? ? ? ? ? ?}375 ?? ? ? ?}376 ?? ? ? ?Sleep(sleeptime);377 ?? ? ? ?snakeMove();378 ?? ?}379 }380 381 void initGame()//开始界面382 {383 ? ? Pos(40, 12);384 385 ? ? system("title C语言研究中心 ? ");386 ? ? printf("欢迎来到贪食蛇游戏!");387 ? ? Pos(40, 25);388 ? ? printf(" ? ? ? ? ? ? ?C语言研究中心 ?.\n");389 ? ? system("pause");390 ? ? system("cls");391 ? ? Pos(25, 12);392 ? ? printf("用↑.↓.←.→分别控制蛇的移动, F1 为加速,2 为减速\n");393 ? ? Pos(25, 13);394 ? ? printf("加速将能得到更高的分数。\n");395 ? ? system("pause");396 ? ? system("cls");397 }398 399 void endGame()//结束游戏400 {401 402 ? ? system("cls");403 ? ? Pos(24, 12);404 ? ? if (endGamestatus == 1)405 ?? ?{406 ? ? ? ? printf("对不起,您撞到墙了。游戏结束.");407 ?? ?}408 ? ? else if (endGamestatus == 2)409 ?? ?{410 ? ? ? ? printf("对不起,您咬到自己了。游戏结束.");411 ?? ?}412 ? ? else if (endGamestatus == 3)413 ?? ?{414 ? ? ? ? printf("您的已经结束了游戏。");415 ?? ?}416 ? ? Pos(24, 13);417 ? ? printf("您的得分是%d\n", score);418 ? ? while (getchar() != 'y')419 ?? ?{ ? ?

420 ? ? ? ? printf("close?[y]");421 ?? ?}422 ? ? exit(0);423 }424 425 void gameStart()//游戏初始化426 {427 ? ? system("mode con cols=100 lines=30");428 ?? ?initGame();429 ?? ?creatMap();430 ?? ?initSnake();431 ?? ?createFood();432 }433 434 int main()435 {436 ?? ?gameStart();437 ?? ?runGame();438 ?? ?endGame();439 ? ? return 0;440 }

贪吃蛇c语言代码

#includestdio.h

#includestdlib.h

#includeWindows.h

#includeconio.h

#includetime.h

char gamemap[20][40];//游戏地图大小 20*40

int score=0;//当前分数

//记录蛇的结点

int x[800];//每个结点的行编号

int y[800];//每个结点的列编号

int len = 0;//蛇的长度

//记录水果信息

int fx=0;//食物的横坐标

int fy=0;//食物的纵坐标

int fcount=0;//食物的数目

//主要函数操作

void createfood();//生成食物

void PrintgameMap(int x[],int y[]);//画游戏地图

void move(int x[],int y[]);//移动蛇

int main()

{

srand(time(NULL));

//初始化蛇头和身体的位置,默认刚开始蛇长为2

x[len] = 9;

y[len] = 9;

len++;

x[len] = 9;

y[len] = 8;

len++;

createfood();

PrintgameMap(x,y);

move(x,y);

return 0;

}

void createfood()

{

if(0==fcount)

{

int tfx=rand()%18+1;

int tfy=rand()%38+1;

int i,j;

int have=0;//为0表示食物不是食物的一部分

for(i=0;ilen;i++)

{

for(j=0;jlen;j++)

{

if(x[i]==fxy[j]==fy)

{

have=1;

break;

}

else

{

have=0;

}

}

if(1==have)//若为蛇的一部分,执行下一次循环

{

continue;

}

else//否则生成新的水果

{

fcount++;

fx=tfx;

fy=tfy;

break;

}

}

}

}

//游戏地图

void PrintgameMap(int x[],int y[])

{

int snake = 0,food=0;

int i, j;

//画游戏地图,并画出蛇的初始位置

for (i = 0; i 20; i++)

{

for (j = 0; j 40; j++)

{

if (i == 0 j = 1 j = 38)

{

gamemap[i][j] = '=';

}

else if (i == 19 j = 1 j = 38)

{

gamemap[i][j] = '=';

}

else if (j == 0 || j == 39)

{

gamemap[i][j] = '#';

}

else

{

gamemap[i][j] = ' ';

}

//判断蛇是否在当前位置

int k;

for ( k = 0; k len; k++)

{

if (i == x[k]j == y[k])

{

snake = 1;

break;

}

else

{

snake = 0;

}

}

{

if(fcountfx==ify==j)

{

food=1;

}

else

{

food=0;

}

}

//若蛇在当前位置

if (1==snake )

{

printf("*");

}

else if(1==food)

{

printf("f");

}

//若蛇不在当前位置并且当前位置没有水果

else

{

printf("%c", gamemap[i][j]);

}

}

printf("\n");

}

printf("score:%d",score);

}

//移动

void move(int x[],int y[])

{

char s;

s=getch();

int move=0,beat=0;

while (1)

{

int cx[800];

int cy[800];

memcpy(cx, x, sizeof(int)*len);

memcpy(cy, y, sizeof(int)*len);

//头

if (s=='w')

{

x[0]--;

move=1;

if(x[0]=0)

{

printf("Game over\n");

break;

}

}

else if (s=='s')

{

x[0]++;

move=1;

if(x[0]=19)

{

printf("Game over\n");

break;

}

}

else if (s=='a')

{

y[0] --;

move=1;

if(y[0]=0)

{

printf("Game over\n");

break;

}

}

else if (s=='d')

{

y[0]++;

move=1;

if(y[0]=39)

{

printf("Game over\n");

break;

}

}

//身体

int i;

for ( i = 1; i len; i++)

{

x[i] = cx[i - 1];

y[i] = cy[i - 1];

}

for(i=1;ilen;i++)//要是咬到了自己

{

if(x[0]==x[i]y[0]==y[i])

{

beat=1;

}

else

{

beat=0;

}

}

if(1==beat)

{

printf("Game over\n");

break;

}

if(1==move)

{

if(fcountx[0]==fxy[0]==fy)//如果吃到了果子

{

//拷贝当前蛇头地址到第二个结点

memcpy(x+1,cx,sizeof(int)*len);

memcpy(y+1,cy,sizeof(int)*len);

len++;

fcount--;

fx=0;

fy=0;

score++;

createfood();

}

Sleep(70);

system("cls");

PrintgameMap( x, y);

}

else

continue;

if(kbhit())//判断是否按下按键

{

s=getch();

}

}

}

求 贪吃蛇C语言代码

#include windows.h

#include stdlib.h

#include time.h

#include stdio.h

#include string.h

#include conio.h

#define N 21

int apple[3],num;

char score[3];

char tail[3];

void gotoxy(int x, int y) //输出坐标

{

COORD pos;

pos.X = x;

pos.Y = y;

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);

}

void color(int b) //颜色函数

{

HANDLE hConsole = GetStdHandle((STD_OUTPUT_HANDLE)) ;

SetConsoleTextAttribute(hConsole,b) ;

}

int Block(char head[2]) //判断出界

{

if ((head[0] 1) || (head[0] N) || (head[1] 1) || (head[1] N))

return 1;

return 0;

}

int Eat(char snake[2]) //吃了苹果

{

if ((snake[0] == apple[0]) (snake[1] == apple[1]))

{

apple[0] = apple[1] = apple[2] = 0;

gotoxy(N+44,10);

color(13);

printf("%d",score[0]*10);

color(11);

return 1;

}

return 0;

}

void Draw(char **snake, int len) //蛇移动

{

if (apple[2])

{

gotoxy(apple[1] * 2, apple[0]);

color(12);

printf("●");

color(11);

}

gotoxy(tail[1] * 2, tail[0]);

if (tail[2])

{

color(num);

printf("★");

color(num);

}

else

printf("■");

gotoxy(snake[0][1] * 2, snake[0][0]);

color(num);

printf("★");

color(num);

putchar('\n');

}

char** Move(char **snake, char dirx, int *len) //控制方向

{

int i, full = Eat(snake[0]);

memcpy(tail, snake[(*len)-1], 2);

for (i = (*len) - 1; i 0; --i)

memcpy(snake[i], snake[i-1], 2);

switch (dirx)

{

case 'w': case 'W': --snake[0][0]; break;

case 's': case 'S': ++snake[0][0]; break;

case 'a': case 'A': --snake[0][1]; break;

case 'd': case 'D': ++snake[0][1]; break;

default: ;

}

if (full)

{

snake = (char **)realloc(snake, sizeof(char *) * ((*len) + 1));

snake[(*len)] = (char *)malloc(sizeof(char) * 2);

memcpy(snake[(*len)], tail, 2);

++(*len);

++score[0];

if(score[3] 16)

++score[3];

tail[2] = 1;

}

else

tail[2] = 0;

return snake;

}

void init(char plate[N+2][N+2], char ***snake_x, int *len) //初始化

{

int i, j;

char **snake = NULL;

*len = 3;

score[0] = score[3] =3;

snake = (char **)realloc(snake, sizeof(char *) * (*len));

for (i = 0; i *len; ++i)

snake[i] = (char *)malloc(sizeof(char) * 2);

for (i = 0; i 3; ++i)

{

snake[i][0] = N/2 + 1;

snake[i][1] = N/2 + 1 + i;

}

for (i = 1; i = N; ++i)

for (j = 1; j = N; ++j)

plate[i][j] = 1;

apple[0] = rand()%N + 1; apple[1] = rand()%N + 1;

apple[2] = 1;

for (i = 0; i N + 2; ++i)

{

gotoxy(0, i);

for (j = 0; j N + 2; ++j)

{

switch (plate[i][j])

{

case 0:

color(12);printf("□");color(11); continue;

case 1: printf("■"); continue;

default: ;

}

}

putchar('\n');

}

for (i = 0; i (*len); ++i)

{

gotoxy(snake[i][1] * 2, snake[i][0]);

printf("★");

}

putchar('\n');

*snake_x = snake;

}

void Manual()

{

gotoxy(N+30,2);

color(10);

printf("按 W S A D 移动方向");

gotoxy(N+30,4);

printf("按 space 键暂停");

gotoxy(N+30,8);

color(11);

printf("历史最高分为: ");

color(12);

gotoxy(N+44,8);

printf("%d",score[1]*10);

color(11);

gotoxy(N+30,12);

printf("你现在得分为: 0");

}

int File_in() //取记录的分数

{

FILE *fp;

if((fp = fopen("C:\\tcs.txt","a+")) == NULL)

{

gotoxy(N+18, N+2);

printf("文件不能打开\n");

exit(0);

}

if((score[1] = fgetc(fp)) != EOF);

else

score[1] = 0;

return 0;

}

int File_out() //存数据

{

FILE *fp;

if(score[1] score[0])

{gotoxy(10,10);

color(12);

puts("闯关失败 加油耶");

gotoxy(0,N+2);

return 0;

}

if((fp = fopen("C:\\tcs.txt","w+")) == NULL)

{

printf("文件不能打开\n");

exit(0);

}

if(fputc(--score[0],fp)==EOF)

printf("输出失败\n");

gotoxy(10,10);

color(12);

puts("恭喜您打破记录");

gotoxy(0,N+2);

return 0;

}

void Free(char **snake, int len) //释放空间

{

int i;

for (i = 0; i len; ++i)

free(snake[i]);

free(snake);

}

int main(void)

{

int len;

char ch = 'g';

char a[N+2][N+2] = {{0}};

char **snake;

srand((unsigned)time(NULL));

color(11);

File_in();

init(a, snake, len);

Manual();

while (ch != 0x1B) // 按 ESC 结束

{

Draw(snake, len);

if (!apple[2]) {

apple[0] = rand()%N + 1;

apple[1] = rand()%N + 1;

apple[2] = 1;

num++;

if(num8)

num=0;

}

Sleep(200-score[3]*10);

setbuf(stdin, NULL);

if (kbhit())

{

gotoxy(0, N+2);

ch = getche();

}

snake = Move(snake, ch, len);

if (Block(snake[0])==1)

{

gotoxy(N+2, N+2);

puts("你输了");

File_out();

Free(snake, len);

getche();

exit(0);

}

}

Free(snake, len);

exit(0);

}

c语言 贪吃蛇 程序

基本思路:

蛇每吃一个食物蛇身子就增加一格,用UP, DOWN, LEFT, RIGHT控制蛇头的运动,而蛇身子跟着蛇头走,每后一格蛇身子下一步走到上一格蛇身子的位置,以此类推。

#include stdio.h

#include conio.h

#include windows.h

#define BEG_X 2

#define BEG_Y 1

#define WID 20

#define HEI 20

HANDLE hout;

typedef enum {UP, DOWN, LEFT, RIGHT} DIR;

typedef struct Snake_body

{

COORD pos;//蛇身的位置

struct Snake_body *next;//下一个蛇身

struct Snake_body *prev;//前一个蛇身

}SNAKE, *PSNAKE;

PSNAKE head = NULL;//蛇头

PSNAKE tail = NULL;//蛇尾

//画游戏边框的函数

void DrawBorder()

{

int i, j;

COORD pos = {BEG_X, BEG_Y};

for(i = 0; i HEI; ++i)

{

SetConsoleCursorPosition(hout, pos);

for(j = 0; j WID; ++j)

{

if(i == 0)//第一行

{

if(j == 0)

printf("┏");

else if(j == WID - 1)

printf("┓");

else

printf("━");

}

else if(i == HEI - 1)//最后一行

{

if(j == 0)

printf("┗");

else if(j == WID - 1)

printf("┛");

else

printf("━");

}

else if(j == 0 || j == WID - 1)//第一列或最后一列

printf("┃");

else

printf(" ?");

}

++pos.Y;

}

}

//添加蛇身的函数

void AddBody(COORD pos)

{

PSNAKE pnew = (PSNAKE)calloc(1, sizeof(SNAKE));

pnew-pos = pos;

if(!head)

{

head = tail = pnew;

}

else

{

pnew-next = head;//新创建蛇身的next指向原先的蛇头

head-prev = pnew;//原先的蛇头的prev指向新创建的蛇身

head = pnew;//把新创建的蛇身作为新的蛇头

}

SetConsoleCursorPosition(hout, head-pos);

printf("◎");

}

//蛇身移动的函数

void MoveBody(DIR dir)

{

PSNAKE ptmp;

COORD pos = head-pos;

switch(dir)

{

case UP:

if(head-pos.Y BEG_Y + 1)

--pos.Y;

else

return;

break;

case DOWN:

if(head-pos.Y BEG_Y + HEI - 2)

++pos.Y;

else

return;

break;

case LEFT:

if(head-pos.X BEG_X + 2)

pos.X -= 2;

else

return;

break;

case RIGHT:

if(head-pos.X BEG_X + (WID - 2) * 2)

pos.X += 2;

else

return;

break;

}

AddBody(pos);//添加了一个新的蛇头

ptmp = tail;//保存当前的蛇尾

tail = tail-prev;

if(tail)

tail-next = NULL;

SetConsoleCursorPosition(hout, ptmp-pos);

printf(" ?");

free(ptmp);

}

int main()

{

int ctrl;

DIR dir = RIGHT;//初始蛇的方向是向右的

COORD pos = {BEG_X + 2, BEG_Y + HEI / 2};

system("color 0E");

system("mode con cols=90 lines=30");

hout = GetStdHandle(STD_OUTPUT_HANDLE);

printf(" ? ?------------贪吃蛇的移动------------");

DrawBorder();

//自定义几个蛇的身体

AddBody(pos);

pos.X += 2;

AddBody(pos);

pos.X += 2;

AddBody(pos);

pos.X += 2;

AddBody(pos);

pos.X += 2;

AddBody(pos);

pos.X += 2;

AddBody(pos);

pos.X += 2;

AddBody(pos);

//控制蛇的移动

while(ctrl = getch())

{

switch(ctrl)

{

case 'w':

if(dir == DOWN)

continue;

dir = UP;

break;

case 's':

if(dir == UP)

continue;

dir = DOWN;

break;

case 'a':

if(dir == RIGHT)

continue;

dir = LEFT;

break;

case 'd':

if(dir == LEFT)

continue;

dir = RIGHT;

break;

case 'q':

return 0;

}

MoveBody(dir);

}

return 0;

}

扩展资料:

实现逻辑

1,可以设置光标,就能实现制定位置打印制定符号。

2,涉及一个结构体,包含两个元素坐标元素和一个结构体指针。

3,结构体串联形成链表,遍历获取成员坐标,打印符号得到蛇身。

4,不断的加头,去尾,重新遍历坐标,再打印形成蛇的移动。

5,食物产生的位置判定,不能越界,也不能与蛇身体重合。

6,蛇的转向判定,一条规则,不允许倒退。

7,转向的实现,跟行进方向决定新的关节坐标(当前头的上下左右)

8,死亡检测,是否头节点坐标是否与墙壁重合,是否与身体其他关节重合。

9,加速减速,设置刷新休眠时间实现。

参考资料来源:百度百科-C语言

如何用C语言写贪吃蛇

#includeconio.h #includegraphics.h #includetime.h #includestring.h #includemalloc.h #includestdio.h int grade=5,point=0,life=3; void set(),menu(),move_head(),move_body(),move(),init_insect(),left(),upon(),right(),down(),init_graph(),food_f(),ahead(),crate(); struct bug { int x; int y; struct bug *last; struct bug *next; }; struct fd { int x; int y; int judge; }food={0,0,0}; struct bug *head_f=NULL,*head_l,*p1=NULL,*p2=NULL; void main() { char ch; initgraph(800,600); set(); init_insect(); while(1) { food_f(); Sleep(grade*10); setcolor(BLACK); circle(head_l-x,head_l-y,2); setcolor(WHITE); move_body(); if(kbhit()) { ch=getch(); if(ch==27) { ahead(); set(); } else if(ch==-32) { switch(getch()) { case 72:upon();break; case 80:down();break; case 75:left();break; case 77:right();break; } } else ahead(); } else { ahead(); } if(head_f-x==food.xhead_f-y==food.y) { Sleep(100); crate(); food.judge=0; point=point+(6-grade)*10; if(food.x30||food.y30||food.x570||food.y570) life++; menu(); } if(head_f-x5||head_f-x595||head_f-y5||head_f-y595) { Sleep(1000); life--; food.judge=0; init_graph(); init_insect(); menu(); } for(p1=head_f-next;p1!=NULL;p1=p1-next) { if(head_f-x==p1-xhead_f-y==p1-y) { Sleep(1000); life--; food.judge=0; init_graph(); init_insect(); menu(); break; } } if(life==0) { outtextxy(280,300,"游戏结束!"); getch(); return; } move(); }; } void init_graph() { clearviewport(); setlinestyle(PS_SOLID,1,5); rectangle(2,2,600,598); setlinestyle(PS_SOLID,1,1); } void set() { init_graph(); outtextxy(640,50,"1、开始 / 返回"); outtextxy(640,70,"2、退出"); outtextxy(640,90,"3、难度"); outtextxy(640,110,"4、重新开始"); switch(getch()) { case '1': menu();setcolor(GREEN);circle(food.x,food.y,2);setcolor(WHITE);return; case '2': exit(0);break; case '3': outtextxy(700,90,":1 2 3 4 5");grade=getch()-48;set();break; case '4': food.judge=0,grade=5;point=0;life=3;init_insect();menu();break; default: outtextxy(250,300,"输入错误!"); set();break; } } void menu() { char str[20],str1[]={"分数:"},str2[]={"难度:"},str3[]={"生命值:"}; init_graph(); sprintf(str,"%d",point); strcat(str1,str); outtextxy(640,50,str1); sprintf(str,"%d",grade); strcat(str2,str); outtextxy(640,70,str2); sprintf(str,"%d",life); strcat(str3,str); outtextxy(640,90,str3); outtextxy(640,110,"设置:ESC"); } void init_insect() { head_f=(struct bug *)malloc(sizeof(struct bug)); head_f-last=NULL; head_f-x=300; head_f-y=300; p2=head_f-next=p1=(struct bug *)malloc(sizeof(struct bug)); p1-last=head_f; p1-x=295; p1-y=300; p1=p1-next=(struct bug *)malloc(sizeof(struct bug)); p1-next=NULL; p1-x=290; p1-y=300; p1-last=p2; head_l=p1; } void move() { for(p1=head_f;p1!=NULL;p1=p1-next) { circle(p1-x,p1-y,2); } } void move_head() { } void move_body() { for(p1=head_l,p2=p1-last;p2!=NULL;p1=p2,p2=p2-last) { p1-x=p2-x; p1-y=p2-y; } } void ahead() { p1=head_f; p2=p1-next; p2=p2-next; if(p1-x==p2-x) { if(p1-yp2-y) head_f-y+=5; else head_f-y-=5; } else { if(p1-xp2-x) { head_f-x+=5; } else head_f-x-=5; } } void upon() { p1=head_f-next; p1=p1-next; head_f-y-=5; if(p1-x==head_f-xp1-y==head_f-y) { head_f-y+=5; ahead(); } } void down() { p1=head_f-next; p1=p1-next; head_f-y+=5; if(p1-x==head_f-xp1-y==head_f-y) { head_f-y-=5; ahead(); } } void left() { p1=head_f-next; p1=p1-next; head_f-x-=5; if(p1-x==head_f-xp1-y==head_f-y) { head_f-x+=5; ahead(); } } void right() { p1=head_f-next; p1=p1-next; head_f-x+=5; if(p1-x==head_f-xp1-y==head_f-y) { head_f-x-=5; ahead(); } } void food_f() { if(!food.judge) { food.x=(rand()%117+1)*5; food.y=(rand()%117+1)*5; food.judge=1; if(food.x30||food.y30||food.x570||food.y570) { setcolor(RED); circle(f

C语言的贪吃蛇源代码

?

//******友情提示:如想速度快点,请改小_sleep(500)函数中参数*****??

#include?stdio.h??

#include?stdlib.h??

#include?conio.h??

#include?string.h??

#include?time.h??

const?int?H?=?8;???//地图的高??

const?int?L?=?16;??//地图的长??

char?GameMap[H][L];???//游戏地图??

int??key;??//按键保存??

int??sum?=?1,?over?=?0;??//蛇的长度,?游戏结束(自吃或碰墙)??

int??dx[4]?=?{0,?0,?-1,?1};??//左、右、上、下的方向??

int??dy[4]?=?{-1,?1,?0,?0};??

struct?Snake???//蛇的每个节点的数据类型??

{??

?int?x,?y;??//左边位置??

?int?now;???//保存当前节点的方向,?0,1,2,3分别为左右上下??

}Snake[H*L];??

const?char?Shead?=?'@';??//蛇头??

const?char?Sbody?=?'#';??//蛇身??

const?char?Sfood?=?'*';??//食物??

const?char?Snode?=?'.';??//'.'在地图上标示为空??

void?Initial();??//地图的初始化??

void?Create_Food();?//在地图上随机产生食物??

void?Show();???//刷新显示地图??

void?Button();??//取出按键,并判断方向??

void?Move();???//蛇的移动??

void?Check_Border();??//检查蛇头是否越界??

void?Check_Head(int?x,?int?y);???//检查蛇头移动后的位置情况??

int?main()???

{??

?Initial();??

?Show();??

?return?0;??

}??

void?Initial()??//地图的初始化??

{??

?int?i,?j;??

?int?hx,?hy;??

?system("title?贪吃蛇");??//控制台的标题??

?memset(GameMap,?'.',?sizeof(GameMap));??//初始化地图全部为空'.'??

?system("cls");??

?srand(time(0));???//随机种子??

?hx?=?rand()%H;????//产生蛇头??

?hy?=?rand()%L;??

?GameMap[hx][hy]?=?Shead;??

?Snake[0].x?=?hx;??Snake[0].y?=?hy;??

?Snake[0].now?=?-1;??

?Create_Food();???//随机产生食物??

?for(i?=?0;?i??H;?i++)???//地图显示??

?{???

??for(j?=?0;?j??L;?j++)??

???printf("%c",?GameMap[i][j]);??

??printf("\n");??

?}??

?????

?printf("\n小小C语言贪吃蛇\n");??

?printf("按任意方向键开始游戏\n");??

????

?getch();???//先接受一个按键,使蛇开始往该方向走??

?Button();??//取出按键,并判断方向??

}??

void?Create_Food()??//在地图上随机产生食物??

{??

?int?fx,?fy;??

?while(1)??

?{??

??fx?=?rand()%H;??

?????fy?=?rand()%L;??

?????

??if(GameMap[fx][fy]?==?'.')??//不能出现在蛇所占有的位置??

??{???

???GameMap[fx][fy]?=?Sfood;??

??????break;??

??}??

?}??

}??

void?Show()??//刷新显示地图??

{??

?int?i,?j;??

?while(1)??

?{????

??_sleep(500);?//延迟半秒(1000为1s),即每半秒刷新一次地图??

??Button();???//先判断按键在移动??

??Move();??

??if(over)??//自吃或碰墙即游戏结束??

??{???

???printf("\n**游戏结束**\n");??

???printf("?????_\n");??

???getchar();??

??????break;??

??}??

??system("cls");???//清空地图再显示刷新吼的地图??

??for(i?=?0;?i??H;?i++)???

??{???

???for(j?=?0;?j??L;?j++)??

????printf("%c",?GameMap[i][j]);??

???printf("\n");??

??}??

?????

??printf("\n小小C语言贪吃蛇\n");??

??printf("按任意方向键开始游戏\n");??

?}??

}??

void?Button()??//取出按键,并判断方向??

{??

?if(kbhit()?!=?0)?//检查当前是否有键盘输入,若有则返回一个非0值,否则返回0??

?{???

??while(kbhit()?!=?0)??//可能存在多个按键,要全部取完,以最后一个为主??

??????key?=?getch();?//将按键从控制台中取出并保存到key中??

??switch(key)??

??{???//左??

???case?75:??Snake[0].now?=?0;??

??????????break;??

????????????//右??

????????????case?77:??Snake[0].now?=?1;???????

??????????break;??

????????????//上??

???case?72:??Snake[0].now?=?2;??

??????????break;??

????????????//下??

???case?80:??Snake[0].now?=?3;??

??????????break;??

??}??

?}??

}??

void?Move()???//蛇的移动??

{??

?int?i,?x,?y;??

????int?t?=?sum;??//保存当前蛇的长度??

?//记录当前蛇头的位置,并设置为空,蛇头先移动??

?x?=?Snake[0].x;??y?=?Snake[0].y;??GameMap[x][y]?=?'.';??

?Snake[0].x?=?Snake[0].x?+?dx[?Snake[0].now?];??

?Snake[0].y?=?Snake[0].y?+?dy[?Snake[0].now?];??

?Check_Border();???//蛇头是否越界??

?Check_Head(x,?y);??//蛇头移动后的位置情况,参数为:?蛇头的开始位置??

?if(sum?==?t)??//未吃到食物即蛇身移动哦??

????for(i?=?1;?i??sum;?i++)??//要从蛇尾节点向前移动哦,前一个节点作为参照??

?{??

??if(i?==?1)???//尾节点设置为空再移动??

???GameMap[?Snake[i].x?][?Snake[i].y?]?=?'.';??

?????

??if(i?==?sum-1)??//为蛇头后面的蛇身节点,特殊处理??

??{??

???Snake[i].x?=?x;??

?????????Snake[i].y?=?y;??

??????Snake[i].now?=?Snake[0].now;??

??}??

??else???//其他蛇身即走到前一个蛇身位置??

??{??

???Snake[i].x?=?Snake[i+1].x;??

?????????Snake[i].y?=?Snake[i+1].y;??

??????Snake[i].now?=?Snake[i+1].now;??

??}??

??????

??GameMap[?Snake[i].x?][?Snake[i].y?]?=?'#';?//移动后要置为'#'蛇身???

?}??

}??

void?Check_Border()??//检查蛇头是否越界??

{??

?if(Snake[0].x??0?||?Snake[0].x?=?H??

?||?Snake[0].y??0?||?Snake[0].y?=?L)??

?????over?=?1;??

}??

void?Check_Head(int?x,?int?y)??//检查蛇头移动后的位置情况??

{??

????

?if(GameMap[?Snake[0].x?][?Snake[0].y?]?==?'.')??//为空??

??GameMap[?Snake[0].x?][?Snake[0].y?]?=?'@';??

?else?

??if(GameMap[?Snake[0].x?][?Snake[0].y?]?==?'*')??//为食物??

??{??

???GameMap[?Snake[0].x?][?Snake[0].y?]?=?'@';????

???Snake[sum].x?=?x;???//新增加的蛇身为蛇头后面的那个??

??????Snake[sum].y?=?y;??

??????Snake[sum].now?=?Snake[0].now;??

?????????GameMap[?Snake[sum].x?][?Snake[sum].y?]?=?'#';???

???sum++;??

???Create_Food();??//食物吃完了马上再产生一个食物??

??}??

??else?

???over?=?1;??

}

(责任编辑:IT教学网)

更多

推荐Mail服务器文章