c语言贪吃蛇UI界面版
C语言实现贪吃蛇游戏
C语言实现贪吃蛇游戏.txt每天早上起床都要看一遍“福布斯”富翁排行榜,如果上面没有我的名字,我就去上班。
谈钱不伤感情,谈感情最他妈伤钱。
我诅咒你一辈子买方便面没有调料包。
/*===========================================================*程序名:贪吃蛇/*===========================================================*调用库:*----------------------*图形库graphics.h,随机库stdlib.h*===========================================================*/#include <graphics.h>#include <stdlib.h>/*===========================================================*宏定义:*----------------------*上、下、左、右、退出(ESC),暂停(PAUSE),确定(ENTER)*alive---蛇活着,dead---蛇死亡*no---食物不存在,yes---食物存在*N---蛇最大长度,达到200时游戏完成*===========================================================*/#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011b#define SPACE 0x3920#define ENTER 0x1c0d#define alive 1#define dead 0#define yes 1#define no 0#define N 200/*===========================================================*自定义函数以及全局变量声明*---------------------------*Score---统计吃的食物个数;Speed_degree:控制蛇速度变量*===========================================================*/void make_full_screen();void start_screen();void menu();void wall_note();void play_game();void score();void game_over();void close_full_screen();void victory();void forum();void leave_or_again();void victory();int Score,Speed_degree;/*=========================================================== *自定义函数:make_full_screen()*---------------------------------*初始化图形界面*===========================================================*/ void make_full_screen(){int driver=DETECT,mode;registerbgidriver(EGAVGA_driver);initgraph(&driver,&mode,"");cleardevice();}/*=========================================================== *自定义函数:start_screen()*------------------------------*贪吃蛇游戏的欢迎界面*===========================================================*/ void start_screen(){int i,p,color=9;settextstyle(0,0,2);setcolor(GREEN);outtextxy(150,400,"Press any key to loading...");setcolor(YELLOW);outtextxy(200,450,"Deviser:caolvchong");forum();while(bioskey(1)==0) /*当没有按键时显示snake*/{settextstyle(0,0,6);for(i=9;i<15;i++){color++;if(color>=14) color=9;setcolor(color);outtextxy(200,200,"SNAKE");for(p=1;p<3;p++)delay(50000);}}bioskey(0);/*返回键盘值,不然按下的扫描码将被后面检测按键函数接收*/ cleardevice();/*清屏*/}/*===========================================================*自定义函数:menu()*------------------------------*贪吃蛇游戏的菜单界面*===========================================================*/void menu(){int j=100,k=j,n,key,tag=1;char *char_up=NULL,*char_down=NULL;/*----------------------------------------------*参数说明:*j:作为显示选择条(bar)的位置参数*k: 作为清除选择条的位置参数*key:接收按键参数*tag:跳出menu()函数的标签,触发条件按下enter**char_up,*char_down接收ASCII码的24(↑)和25(↓)*----------------------------------------------*/setcolor(RED);settextstyle(0,0,2);outtextxy(15,15,"choose a level");setcolor(LIGHTBLUE);settextstyle(0,0,3);outtextxy(15,100,"Easy");outtextxy(15,150,"Normal");outtextxy(15,200,"Hard");setcolor(GREEN);settextstyle(0,0,2);sprintf(char_up,"%c",24);outtextxy(150,350,char_up);sprintf(char_down,"%c",25);outtextxy(210,350,char_down);outtextxy(170,350,"or ");outtextxy(230,350,"to select");outtextxy(150,380,"ENTER to play");outtextxy(150,410,"ESC to exit");setfillstyle(2,YELLOW);bar(190,j,215,j+25);forum();while(tag!=0){setfillstyle(1,BLACK);bar(190,k,215,k+25);setfillstyle(2,YELLOW);bar(190,j,215,j+25);key=bioskey(0);switch(key){case DOWN: k=j;if(j<200) j+=50;break;case UP: k=j;if(j>100) j-=50;break;case ENTER: tag=0;break;case ESC: close_full_screen(); /*退出*/}switch(j){case 100:Speed_degree=12;break;case 150:Speed_degree=8;break;case 200:Speed_degree=4;break; /*对应各等级的速度延迟循环次数*/ }}}/*===========================================================*自定义函数:wall_note()*------------------------------*贪吃蛇游戏的围墙,就是蛇的活动范围*以及游戏中提示按键:ESC--退出;SPACE--暂停*===========================================================*/void wall_note(){cleardevice();setlinestyle(0,0,3);setcolor(LIGHTRED);rectangle(47,57,603,453);setfillstyle(1,LIGHTGREEN);bar(55,10,600,40);settextstyle(0,0,3);setcolor(RED);outtextxy(58,15,"ESC:exit");outtextxy(305,15,"SPACE:pause");forum();}/*=========================================================== *自定义函数:play_game()*------------------------------*具体的游戏过程*===========================================================*/ void play_game(){struct{int x[N];int y[N];int block;int life;int direction;}snake;struct{int x;int y;int exist;}food;int i,key;/*---------------------------------*参数说明:*结构体snake.[x],snake.[y]为蛇身体坐标*snake.block蛇的节数;snake.life蛇生命参数*snake.direction蛇的运动方向*--------------*结构体food.x,food.y为食物坐标*food.exist食物存在参数*-------------*i:一些循环控制参量*key:接收键盘按键参量*----------------------------------*/randomize();/*初始化随机库*/snake.x[0]=100;snake.y[0]=100;snake.direction=RIGHT;snake.life=alive;snake.block=3;food.exist=no;score();/*初始分数*//*-----------------------------------*初始化:*蛇的头部位置,运动方向向右,生命活着*节数为3,食物开始不存在,初始化分数显示为0*-----------------------------------*/for(;;)/* 循环,作用于下面while(!kbhit),按键后重新开始* while(!hkbit)循环,并对按键分析,实现上下左右*以及退出暂停的检测*/{while(!kbhit())/*没有按键时,实现对食物是否存在的判断,对于不存*在时产生食物,并画出;*对蛇移动的处理:自动向前移动,对接收来的上下左*右的处理,对蛇运动过程是否导致死亡判断,对蛇身*体变长以及画出蛇的处理*对分数的处理:显示分数,对是否完全200个进行判断*/{if(food.exist==no)/*没有食物时,随机出现食物*/{food.x=random(531)+60;food.y=random(381)+60;/*随机出现食物,确保食物在蛇的活动范围内*/while(food.x%10!=0) food.x++;while(food.y%10!=0) food.y++;/*确保食物在屏幕坐标10的正数倍,这样才能被蛇吃到*/ food.exist=yes;/*食物存在了*/for(i=0;i<snake.block;i++)if(food.x==snake.x&&food.y==snake.y){food.exist=no;break;}/*如果食物在蛇的身体内,重新产生食物*/}setlinestyle(0,0,1);setcolor(RED);rectangle(food.x,food.y,food.x+10,food.y+10);/*画出食物*/for(i=snake.block-1;i>0;i--){snake.x=snake.x[i-1];snake.y=snake.y[i-1];}/*蛇身体后面一格变前面一格,实现蛇移动的原理*/switch(snake.direction){case RIGHT: snake.x[0]+=10;break;case LEFT: snake.x[0]-=10;break;case UP: snake.y[0]-=10;break;case DOWN: snake.y[0]+=10;break;}/*蛇上下左右移动的处理*/for(i=4;i<snake.block;i++)if(snake.x==snake.x[0]&&snake.y==snake.y[0]){snake.life=dead;break;}/*对蛇是否碰到自己的判断,碰到自己,蛇死*/if(snake.x[0]<48||snake.x[0]>597||snake.y[0]<53||snake.y[0]>447) snake.life=dead; /*碰到墙,蛇死*/if(snake.life==dead){game_over();break;}/*如果蛇死的话,显示游戏结束,退出while(!hkbit())循环*/if(food.x==snake.x[0]&&food.y==snake.y[0])/*食物被吃*/{setcolor(BLACK);rectangle(food.x,food.y,food.x+10,food.y+10);/*把食物去掉*/ snake.block++;/*蛇身增加*/Score++; /*分数增加*/score();/*统计显示分数*/victory();/*吃到食物200个显示完成游戏*/food.exist=no;/*食物被吃,食物就不存在了*/}setcolor(LIGHTBLUE);for(i=1;i<snake.block;i++){setlinestyle(0,0,1);rectangle(snake.x,snake.y,snake.x+10,snake.y+10);}/*画蛇*/setcolor(YELLOW);rectangle(snake.x[0],snake.y[0],snake.x[0]+10,snake.y[0]+10);/*设置蛇的头部*/snake.x[snake.block]=-100;snake.y[snake.block]=-100;for(i=0;i<Speed_degree;i++)delay(10000);setcolor(BLACK);rectangle(snake.x[snake.block-1],snake.y[snake.block-1],snake.x[snake.block-1]+10,snake.y[snake.block-1]+10);/*去掉蛇的最后一节*/}key=bioskey(0);/*等待按键*/if(key==SPACE) bioskey(0);/*暂停*/else if(key==ESC) closegraph();/*结束游戏*/else if(key==RIGHT&&snake.direction!=LEFT) snake.direction=RIGHT; else if(key==UP&&snake.direction!=DOWN) snake.direction=UP;else if(key==LEFT&&snake.direction!=RIGHT) snake.direction=LEFT; else if(key==DOWN&&snake.direction!=UP) snake.direction=DOWN; if(snake.life==dead) break;}}/*===========================================================*自定义函数:score()*------------------------------*统计显示分数*===========================================================*/void score(){char *str=NULL;setfillstyle(0,BLACK);bar(250,460,405,490);setcolor(LIGHTGREEN);settextstyle(0,0,2);sprintf(str,"Score:%d",Score);outtextxy(255,460,str);}/*=========================================================== *自定义函数:victory()*------------------------------*吃到食物200个,完成游戏*===========================================================*/ void victory(){if(Score==200){cleardevice();setcolor(YELLOW);settextstyle(0,0,6);outtextxy(100,200,"Victory!");forum();leave_or_again();}}/*=========================================================== *自定义函数:game_over()*------------------------------*显示游戏结束,选择继续游戏还是离开*===========================================================*/ void game_over(){cleardevice();score();setcolor(RED);settextstyle(0,0,6);outtextxy(100,200,"Game Over");forum();leave_or_again();}/*=========================================================== *自定义函数:leave_or_again()*------------------------------*离开还是重新游戏选择*至于菜单条的设计与前面menu()类似*===========================================================*/void leave_or_again(){int j=300,k,key,tag=1;while(tag!=0){setcolor(BLUE);settextstyle(0,0,3);outtextxy(150,300,"Leave");outtextxy(150,350,"Again");setfillstyle(1,BLACK);bar(330,k,355,k+25);setfillstyle(2,YELLOW);bar(330,j,355,j+25);key=bioskey(0);switch(key){case DOWN: k=j;if(j<350) j+=50;break;case UP: k=j;if(j>300) j-=50;break;case ENTER: tag=0;break;}}switch(j){case 300:close_full_screen();case 350:cleardevice();Score=0;menu();wall_note();play_game();break;}}*===========================================================*自定义函数:close_full_screen()*------------------------------*关闭图形界面*===========================================================*/ void close_full_screen(){cleardevice();closegraph();}/*=========================================================== *主函数:*------------------------------*调用图形界面--->开始欢迎界面--->菜单界面*--->画围墙--->游戏过程--->结束图形界面*===========================================================*/ main(){make_full_screen();start_screen();menu();wall_note();play_game();close_full_screen();}/*============================END============================*/。
超简单贪吃蛇c语言代码编写
超简单贪吃蛇c语言代码编写贪吃蛇其实就是实现以下几步——1:蛇的运动(通过“画头擦尾”来达到蛇移动的视觉效果)2:生成食物3:蛇吃食物(实现“画头不擦尾”)4:游戏结束判断(也就是蛇除了食物,其余东西都不能碰)#include<stdio.h>#include<stdlib.h>#include<windows.h>#include<conio.h>#include<time.h>#define width 60#define hight 25#define SNAKESIZE 200//蛇身的最长长度int key=72;//初始化蛇的运动方向,向上int changeflag=1;//用来标识是否生成食物,1表示蛇还没吃到食物,0表示吃到食物int speed=0;//时间延迟struct {int len;//用来记录蛇身每个方块的坐标int x[SNAKESIZE];int y[SNAKESIZE];int speed;}snake;struct{int x;int y;}food;void gotoxy(int x,int y)//调用Windows的API函数,可以在控制台的指定位置直接操作,这里可暂时不用深究{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }//■○void drawmap(){//打印图框for (int _y = 0; _y < hight; _y++){for (int x = 0; x < width; x+=2){if (x == 0 || _y == 0 || _y == hight - 1 || x == width - 2){gotoxy(x, _y);printf("■");}}}//打印蛇头snake.len=3;snake.x[0]=width/2;snake.y[0]=hight/2;gotoxy(snake.x[0],snake.y[0]);printf("■");//打印蛇身for(int i=1;i<snake.len;i++){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1]+1;gotoxy(snake.x[i],snake.y[i]);printf("■");}//初始化食物的位置food.x=20;food.y=20;gotoxy(food.x,food.y);printf("○");}/**控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*/void snake_move()//按键处理函数{int history_key=key;if (_kbhit()){fflush(stdin);key = _getch();key = _getch();}if(changeflag==1)//还没吃到食物,把尾巴擦掉{gotoxy(snake.x[snake.len-1],snake.y[snake.len-1]);printf(" ");}for(int i=snake.len-1;i>0;i--){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}if(history_key==72&&key==80)key=72;if(history_key==80&&key==72)key=80;if(history_key==75&&key==77)key=75;if(history_key==77&&key==75)key=77;switch(key){case 72:snake.y[0]--;break;case 75:snake.x[0]-= 2;break;case 77:snake.x[0]+= 2;break;case 80:snake.y[0]++;break;}gotoxy(snake.x[0],snake.y[0]);printf("■");gotoxy(0,0);changeflag=1;}void creatfood(){if(snake.x[0] == food.x && snake.y[0] == food.y)//只有蛇吃到食物,才能生成新食物{changeflag=0;snake.len++;if(speed<=100)speed+=10;while(1){srand((unsigned int) time(NULL));food.x=rand()%(width-6)+2;//限定食物的x范围不超出围墙,但不能保证food.x 为偶数food.y=rand()%(hight-2)+1;for(int i=0;i<snake.len;i++){if(food.x==snake.x[i]&&food.y==snake.y[i])//如果产生的食物与蛇身重合则退出break;}if(food.x%2==0)break;//符合要求,退出循环}gotoxy(food.x,food.y);printf("○");}}bool Gameover(){//碰到围墙,OVERif(snake.x[0]==0||snake.x[0]==width-2)return false;if(snake.y[0]==0||snake.y[0]==hight-1) return false;//蛇身达到最长,被迫OVERif(snake.len==SNAKESIZE)return false;//头碰到蛇身,OVERfor(int i=1;i<snake.len;i++){if(snake.x[0]==snake.x[i]&&snake.y[0]==snake.y[i])return false;}return true;}int main(){system("mode con cols=60 lines=27");drawmap();while(Gameover()){snake_move();creatfood();Sleep(350-speed);//蛇的移动速度}return 0;}。
(完整word版)C语言最简洁的贪吃蛇源代码
C语言最简洁的贪吃蛇源代码.txt每天早上起床都要看一遍“福布斯”富翁排行榜,如果上面没有我的名字,我就去上班。
谈钱不伤感情,谈感情最他妈伤钱。
我诅咒你一辈子买方便面没有调料包。
#include〈graphics.h>#include<conio。
h〉#include〈dos.h〉#include<bios。
h>#include<stdlib。
h〉#define STATIC 0#define TRUE 1#define FALSE 0#define UP 1#define RIGHT 2#define DOWN 3#define LEFT 4#define VK_LEFT 0x4b00 /*上下左右键的值*/#define VK_RIGHT 0x4d00#define VK_DOWN 0x5000#define VK_UP 0x4800#define VK_ESC 0x011bint board[22][22];int snakelength=0;struct snake{public:int x=0;int y=0;int direction;}body[20];snake food;void makefood();/*产生一个食物*/int eatfood(); /*蛇吃掉食物*/void right(); /*上下左右的函数了*/void down();void left();void up();void getdirection(); /*判断蛇的方向*/move(snake *body)/*让蛇动起来*/{int x=body[0].x,y=body[0].y;if(body—>direction==RIGHT&&board[y][x+1]!=1)right();else if(body—>direction==DOWN&&board[y+1][x]!=1)down(); else if(body->direction==LEFT&&board[y][x—1]!=1)left(); else if(body—>direction==UP&&board[y-1][x]!=1)up();return 0;}void print() /*在屏幕上显示蛇*/{int i,j,x=0,y=0;for(i=1;i〈21;i++)for(j=1;j<21;j++)board[i][j]=0;for(i=0;i〈20;i++){x=body[i]。
C语言贪吃蛇
C语⾔贪吃蛇/*亲测DEVC++编译器完美执⾏*/#define _CRT_SECURE_NO_WARNINGS#include<windows.h>#include<time.h>#include<conio.h>#include<stdio.h>void readini(FILE **fphead, int *score, char *argv[]) //创建或打开⼀个和运⾏⽂件对应的ini⽂件,读取最⾼纪录{char filename[200], *pfilename;int flag = -1, i;strcpy(filename, argv[0]);for (i = 0; filename[i] != '\0'; i++){if ('.' == filename[i])flag = 1;}if (1 == flag){filename[i - 1] = 'i';filename[i - 2] = 'n';filename[i - 3] = 'i';}else{filename[i] = '.';filename[i + 1] = 'i';filename[i + 2] = 'n';filename[i + 3] = 'i';filename[i + 4] = '\0';}for (; filename[i] != '\\'&&i >= 0; i--)pfilename = &filename[i];if ((*fphead = fopen(pfilename, "rb+")) == NULL){if ((*fphead = fopen(pfilename, "wb+")) == NULL){printf("⽆法创建或打开\"%s\"⽂件\n", pfilename);system("pause");exit(0);}}else{fread(score, sizeof(int), 1, *fphead);}}void writeini(FILE **fphead, int *score, char *argv[]) //打开⼀个和运⾏⽂件对应的ini⽂件,写⼊最⾼纪录{char filename[200], *pfilename;int flag = -1, i;strcpy(filename, argv[0]);for (i = 0; filename[i] != '\0'; i++){if ('.' == filename[i])flag = 1;}if (1 == flag){filename[i - 1] = 'i';filename[i - 2] = 'n';filename[i - 3] = 'i';}else{filename[i] = '.';filename[i + 1] = 'i';filename[i + 2] = 'n';filename[i + 3] = 'i';filename[i + 4] = '\0';}for (; filename[i] != '\\'&&i >= 0; i--)pfilename = &filename[i];if ((*fphead = fopen(pfilename, "wb+")) == NULL){printf("⽆法写⼊\"%s\"⽂件,磁盘写保护!\n", pfilename);system("pause");exit(0);}else{rewind(*fphead);fwrite(score, sizeof(int), 1, *fphead);fclose(*fphead);}}void gotoxy(int x, int y)//光标定位,光标定位函数SetConsoleCursorPosition是左上⾓位置是0,0然后向左向下延伸{COORD pos;pos.X = 2 * y;pos.Y = x;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);}void color(int a)//颜⾊函数{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), a);}void Refresh(int q[][22], int grade, int gamespeed, int length, int score) // 输出贪吃蛇棋盘{int i, j;for (i = 0; i<22; i++){for (j = 0; j<22; j++){if (q[i][j] == 0)//输出棋盘空⽩{gotoxy(i, j);color(11);printf("■");}if (q[i][j] == 1 || q[i][j] == 2)//输出棋盘墙壁{gotoxy(i, j);color(11);printf("□");}if (q[i][j] == 3)//输出蛇头{gotoxy(i, j);printf("★");}if (q[i][j] == 4)//输出蛇⾝{gotoxy(i, j);color(12);printf("◆");}if (q[i][j] == 5)//输出果⼦{gotoxy(i, j);color(12);printf("●");}}if (i == 0) printf("\t***********************");if (i == 1) printf("\t等级为:%d", grade);//显⽰等级if (i == 3) printf("\t⾃动前进时间");if (i == 4) printf("\t间隔为:%dms", gamespeed);//显⽰时间if (i == 6) printf("\t历史最⾼分为:%d分", score);if (i == 7) printf("\t你现在得分为:%d分", (length + (grade - 1) * 8) * 10);if (i == 8) printf("\t**********************");if (i == 9) printf("\t游戏说明:");if (i == 10) printf("\t(1)⽤⼩键盘⽅向键控制");if (i == 11) printf("\t蛇头运动⽅向;");if (i == 12) printf("\t(2)蛇每吃⼀个果⼦蛇⾝");if (i == 13) printf("\t增加⼀节;");if (i == 14) printf("\t(3)蛇咬到⾃⼰或碰到墙");if (i == 15) printf("\t壁游戏结束。
c语言课程设计贪吃蛇设计
Part Three
C语言基础知识
数据类型和变量
基本数据类型:int、float、char、double等 复合数据类型:数组、结构体、指针等 变量声明:使用关键字"int"、"float"等声明变量 变量赋值:使用"="为变量赋值 变量作用域:局部变量、全局变量等 变量生命周期:从声明到释放的过程
结构体和联合体:包括结构 体定义、结构体初始化、结 构体访问、联合体定义、联 合体初始化、联合体访问等
函数和数组
函数:C语言中的基本单元,用于实现特定功能
数组:C语言中的基本数据类型,用于存储一组相同类型 的数据
数组函数:如strlen()、strcpy()等,用于操作字符串
指针:C语言中的重要概念,用于指向内存地址
Part Four
贪吃蛇游戏设计
游戏逻辑设计
游戏结束:当蛇碰到边界或 自己时结束
游戏循环:不断更新蛇的位 置和方向
游戏开始:初始化蛇的位置 和方向
得分计算:根据吃到的食物 数量计算得分
游戏难度:根据得分调整游 戏难度,如增加蛇的速度或
改变食物的位置
游戏界面:设计游戏界面, 包括蛇、食物、边界等元素
Part Seven
总结和展望
课程设计收获和体会
掌握了C语言的基本语法和编 程技巧
学会了如何设计并实现一个完 整的游戏项目
提高了解决问题的能力和团队 协作能力
对游戏开发有了更深入的了解 和兴趣
C语言在游戏开发中的应用前景
游戏开发中,C语言具有高效、稳定的特点,适合开发大型游戏。 C语言具有广泛的应用领域,可以开发各种类型的游戏,如动作、冒险、策略等。 C语言具有强大的社区支持,可以找到大量的游戏开发资源和教程。 C语言在游戏开发中具有广泛的应用前景,可以开发出更多优秀的游戏作品。
C语言实现贪吃蛇代码
C语⾔实现贪吃蛇代码本⽂实例为⼤家分享了C语⾔实现贪吃蛇代码的具体代码,供⼤家参考,具体内容如下#include"stdafx.h"#include<stdio.h>#include<time.h>#include<windows.h>#include<stdlib.h>#include<conio.h>#define U 1#define D 2#define L 3#define R 4 //蛇的状态 U:上 D:下 L:左 R:右typedef struct snake //蛇⾝的⼀个节点{int x; //节点的x坐标int y; //节点的y坐标struct snake *next; //蛇⾝的下⼀个节点}snake;int score=0,add=10; //总得分和每吃⼀次⾷物的得分int highscore=0; //最⾼分int status,sleeptime=200; //蛇前进状态,每次运⾏的时间间隔snake *head,*food; //蛇头指针,⾷物指针snake *q; //遍历蛇时⽤的指针int endgamestatus=0; //游戏结束时的状态HANDLE hOut; //控制台句柄void gotoxy(int x,int y);int color(int c);void printsnake();void wlcome();void createmap();void scoreandtips();void initsnake();void createfood();int biteself();void cantcrosswall();void speedup();void speeddown();void snakemove();void keyboardcontrol();void lostdraw();void endgame();void choose();void file_out();void file_in();void explation();main(){system("mode con cols=100 lines=30");printsnake();wlcome();file_out();keyboardcontrol();endgame();}void gotoxy(int x,int y)//设置光标位置{COORD c;c.X=x;c.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c); //定位光标的位置}int color(int c)//设置颜⾊{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),c);return 0;}void printsnake()//打印字符蛇{color(3);printf("学号:1910101099"); gotoxy(35,1);color(6);printf("/^\\/^\\");gotoxy(34,2);printf("|_| o|");gotoxy(33,2);color(2);printf("_");gotoxy(25,3);color(12);printf("\\/");gotoxy(31,3);color(2);printf("/");gotoxy(37,3);color(6);printf("\\_/");gotoxy(41,3);color(10);printf(" \\");gotoxy(26,4);color(12);printf("\\____");gotoxy(32,4);printf("_________");gotoxy(31,4);color(2);printf("|");gotoxy(43,4);color(10);printf("\\");gotoxy(32,5);color(2);printf("\\_______");gotoxy(44,5);color(10);printf("\\");gotoxy(39,6);printf("| | \\");gotoxy(38,7);printf("/ / \\");gotoxy(37,8);printf("/ / \\ \\");gotoxy(35,9);printf("/ / \\ \\");gotoxy(34,10);printf(" / / \\ \\");gotoxy(33,11);printf("/ / _----_ \\ \\");gotoxy(32,12);gotoxy(32,14);printf("\\ ~-____-~ _-~ ~-_ ~-_-~ /"); gotoxy(33,15);printf("~-_ _-~ ~-_ _-~");gotoxy(35,16);printf("~--____-~ ~-___-~");}void wlcome()//欢迎界⾯{int n;int i,j=1;gotoxy(43,18);color(11);printf("贪吃蛇⼤作战");color(14);for(i=20;i<=26;i++){for(j=27;j<=74;j++){gotoxy(j,i);if(i==20||i==26){printf("-");}else if(j==27||j==74){printf("|");}}}color(12);gotoxy(35,22);printf("1.开始游戏");gotoxy(55,22);printf("2.游戏说明");gotoxy(35,24);printf("3.退出游戏");gotoxy(29,27);color(3);printf("请选择1 2 3\n");color(14);scanf("%d",&n);switch(n){case 1:system("cls");//清屏createmap();initsnake();createfood();keyboardcontrol();break;case 2:explation();break;break;case 3:exit(0);break;}}void createmap()//创建地图{int i,j;for(i=0;i<58;i+=2){gotoxy(i,0);color(5);printf("□");gotoxy(i,26);gotoxy(0,i);printf("□");gotoxy(56,i);printf("□");}for(i=2;i<56;i+=2){for(j=1;j<26;j++){gotoxy(i,j);color(3);printf("■\n\n");}}}void scoreandtips()//游戏界⾯右侧的得分和⼩提⽰ {file_out();gotoxy(64,4);color(11);printf("*最⾼纪录*: %d",highscore);gotoxy(64,8);color(14);printf("得分: %d ",score);color(13);gotoxy(73,11);printf("⼩提⽰");gotoxy(60,13);color(6);printf("+---------------------+");gotoxy(60,25);printf("+---------------------+");color(3);gotoxy(64,14);printf("每个⾷物得分:%d分",add);gotoxy(64,16);printf("不能穿墙,不能咬到⾃⼰");gotoxy(64,18);printf("⽤↑↓←→分别控制蛇的移动");gotoxy(64,20);printf("F1为加速,F2为减速");gotoxy(64,22);printf("space: 暂停游戏");gotoxy(64,24);printf("ESC:退出游戏");}void file_out()//打开⽂件记录最⾼分{FILE *fp;fp=fopen("save.txt","a+");fscanf(fp,"%d",&highscore);fclose(fp);}void initsnake(){snake *tail;int i;tail=(snake*)malloc(sizeof(snake));tail->x=24;tail->y=5;tail->next=NULL;for(i=1;i<=4;i++){head=(snake*)malloc(sizeof(snake));head->next=tail;head->x=24+2*i;head->y=5;tail=head;}while(tail!=NULL){gotoxy(tail->x,tail->y);}void createfood()//随机出现⾷物{snake *food_1;srand((unsigned)time(NULL));food_1=(snake*)malloc(sizeof(snake));while((food_1->x%2!=0)){food_1->x=rand()%52+2;}food_1->y=rand()%24+1;q=head;while(q->next==NULL){if(q->x==food_1->x&&q->y==food_1->y){free(food_1);createfood();}q=q->next;}gotoxy(food_1->x,food_1->y);food=food_1;color(12);printf("@");}int biteself(){snake *self; //定义self为蛇⾝上除蛇头以外的节点self=head->next;while(self!=NULL){if(self->x==head->x&&self->y==head->y){return 1;}self=self->next;}return 0;}void cantcrosswall(){if(head->x==0||head->x==56||head->y==0||head->y==26) {endgamestatus=1;endgame();}}void speedup()//加速{if(sleeptime>=50){sleeptime=sleeptime-10;add=add+2;}}void speeddown()//减速{if(sleeptime<350){sleeptime=sleeptime+30;add=add-2;if(sleeptime==350){add=1;}}}void snakemove()//控制⽅向if(status==U)//上{nexthead->x=head->x; //向上前进时,x不变,y-1nexthead->y=head->y-1;nexthead->next=head;head=nexthead;q=head;//如果下⼀个位置上有⾷物,下⼀个位置的坐标和⾷物坐标相同if(nexthead->x==food->x&&nexthead->y==food->y){while(q!=NULL){gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}score=score+add;speedup();createfood();}else{while(q->next->next!=NULL)//如果没有遇见⾷物{gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}//经过上⾯的循环,q指向蛇尾,蛇尾的下⼀步就是蛇⾛过去的位置 gotoxy(q->next->x,q->next->y);color(3);printf("■");//恢复⾛过的位置free(q->next);q->next=NULL;}}if(status==D){nexthead->x=head->x; //向下前进时,x不变,y+1nexthead->y=head->y+1;nexthead->next=head;head=nexthead;q=head;//如果下⼀个位置上有⾷物,下⼀个位置的坐标和⾷物坐标相同if(nexthead->x==food->x&&nexthead->y==food->y){while(q!=NULL){gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}score=score+add;speedup();createfood();}else{while(q->next->next!=NULL)//如果没有遇见⾷物{gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}//经过上⾯的循环,q指向蛇尾,蛇尾的下⼀步就是蛇⾛过去的位置 gotoxy(q->next->x,q->next->y);color(3);if(status==L)//左{nexthead->x=head->x-2; //向左前进时,x不变,y+1nexthead->y=head->y;nexthead->next=head;head=nexthead;q=head;//如果下⼀个位置上有⾷物,下⼀个位置的坐标和⾷物坐标相同if(nexthead->x==food->x&&nexthead->y==food->y){while(q!=NULL){gotoxy(q->x,q->y); //⾷物变成蛇⾝上的⼀部分color(14);printf("★");q=q->next;}score=score+add;speedup();createfood();}else{while(q->next->next!=NULL)//如果没有遇见⾷物{gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}//经过上⾯的循环,q指向蛇尾,蛇尾的下⼀步就是蛇⾛过去的位置 gotoxy(q->next->x,q->next->y);color(3);printf("■");//恢复⾛过的位置free(q->next);q->next=NULL;}}if(status==R){nexthead->x=head->x+2; //向上前进时,x不变,y-1nexthead->y=head->y;nexthead->next=head;head=nexthead;q=head;//如果下⼀个位置上有⾷物,下⼀个位置的坐标和⾷物坐标相同if(nexthead->x==food->x&&nexthead->y==food->y){while(q!=NULL){gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}score=score+add;speedup();createfood();}else{while(q->next->next!=NULL)//如果没有遇见⾷物{gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}//经过上⾯的循环,q指向蛇尾,蛇尾的下⼀步就是蛇⾛过去的位置 gotoxy(q->next->x,q->next->y);color(3);if(biteself()==1){endgamestatus=2;endgame();}}void keyboardcontrol(){status=R;while(1){scoreandtips();//GetAsyncKeyState函数⽤来判断函数调⽤指定虚拟键的状态 if(GetAsyncKeyState(VK_UP)&&status!=D){status=U;}else if(GetAsyncKeyState(VK_DOWN)&&status!=U){status=D;}else if(GetAsyncKeyState(VK_LEFT)&&status!=R){status=L;}else if(GetAsyncKeyState(VK_RIGHT)&&status!=L){status=R;}if(GetAsyncKeyState(VK_SPACE)){while(1){//调⽤sleep函数,令进程停⽌,直到达到其中设定的参数时间 Sleep(300);if(GetAsyncKeyState(VK_SPACE)){break;}}}else if(GetAsyncKeyState(VK_ESCAPE)){endgamestatus=3;break;}else if(GetAsyncKeyState(VK_F1)){speedup();}else if(GetAsyncKeyState(VK_F2)){if(sleeptime<350){sleeptime=sleeptime+30;add=add-2;if(sleeptime==350){add=1;}}}Sleep(sleeptime);snakemove();}}void lostdraw(){system("cls");int i,j;gotoxy(35,5);color(14);printf("o00o");gotoxy(39,5);color(11);printf("----------");gotoxy(48,5);color(14);printf("---");gotoxy(51,5);color(11);printf("----------");gotoxy(61,5);color(14);printf("o00o");gotoxy(65,5);color(11);printf("-----------------+");for(i=6;i<=19;i++){gotoxy(17,i);printf("|");gotoxy(82,i);printf("|");}gotoxy(17,20);printf("+----------------------------------");gotoxy(52,20);color(11);printf("-----------------------------+");}void endgame(){system("cls");if(endgamestatus==1){lostdraw();gotoxy(35,9);color(12);printf("对不起,您撞到墙了。
C语言控制台版贪吃蛇
头文件#ifndef _SNAKE_H_#define _SNAKE_H_/**--------------------------------------------------------------------------*** TYPE AND STRUCT * **--------------------------------------------------------------------------*/enum SNAKE_DIR {U, D, L, R};typedef enum SNAKE_DIR Dir;typedef struct COORDINA TE{int x;int y;}Coordinate;typedef struct SNAKE{Coordinate coord;struct SNAKE * next;}Snake;typedef Snake * Psnake;/**--------------------------------------------------------------------------*** MACRO DEFINITION ***--------------------------------------------------------------------------*/#define min_x 0#define max_x 60#define max_y 24#define min_y 0#define QUIT 0#ifndef FALSE#define FALSE 0#endif#ifndef TRUE#define TRUE 1#endif#define OVER 2/*按键定义*/#define J_FUNC_KEY0x00#define J_CTRL_KEY0xE0#define J_ESC 0x001B#define J_ENTER 0x000D#define J_SPACE 0x0020#define J_BKSPACE 0x0008#define J_LEFT 0xE04B#define J_RIGHT 0xE04D#define J_UP 0xE048#define J_DOWN 0xE050#define J_PGUP 0xE049#define J_DELETE 0xE053#define J_END 0xE04F#define J_PGDW 0xE051#define S_TIME 230#define CALTIME(x) (S_TIME-(x)*22)/*---------------------------------------------------------------------------*//* LOCAL FUNCTION DECLARE *//*---------------------------------------------------------------------------*/void ShowBye (void);void ShowPause (void);void print_explian (void);void gotoxy (int x, int y);void draw_map (Psnake *head);void draw_snake (Psnake *head);void EmptySnake (Psnake *head);void draw_food (Coordinate *food);void HasKey (Dir *direction, int * pause);void IniHead (Psnake * head, Psnake *tail);void IniCoord (Psnake * head, int x, int y);void IniSnake (Psnake * head, Psnake *tail, int n);void DelTail (Psnake *head, Psnake * tail, int x, int y);int Menu();int SetDifficulty(int *diff);int jkGetKey(void);int setCursorV isible(int b);int IniFood (Psnake *head, Coordinate *food);int InSnake (Psnake *head, int x, int y);int MoveSnake (Psnake *head, Psnake *tail, Dir * direction, Coordinate *food, int *leng);int IsOver (Psnake *head, int x, int y);int HitSelf (Psnake *head, int x, int y);int ShowOver (int *score);#endif函数接口实现#include <stdio.h>#include <stdlib.h>#include <windows.h>#include <conio.h>#include <assert.h>#include <time.h>#include "snake.h"//直接移动光标到X,Y坐标上。
C语言 贪吃蛇游戏
#define LEFT 0x4b00/*向左键*/ #define RIGHT 0x4d00/*向右键*/ #define DOWN 0x5000/*向下键*/ #define UP 0x4800/*向上键*/ #define ESC 0x011b/*〈ESC〉退出键*/ #define N 100/*贪吃蛇的最大长度*/
setfillstyle(1,12);/*用淡红色填充砖的中间部分*/ bar(x+2,y+2,x+sizx-2,y+sizy-2); }
这个函数可以让用户按下任意键而不需要回车键就可以接收到用户的输入。可以用来作为 “press anykey to continue”的实现。
实现过程
(1)预处理模块 在本游戏系统中需要引用一些头文件,以便程序更好的运行。引用头文件需要使用#include命令,
下面即是要引用的文件和引用代码,实现代码如下:
表19.2 cmd参数的设置值
参数值
含义
cmd = 0
cmd = 1
cmd = 2
当cmd是0,bioskey()返回下一个在键盘键入的值(它将等待到按下一个键)。 它返回一个16位的二进制数,包括两个不同的值。当按下一个普通键时,它的低8 位数存放该字符的ASCII码,高8位存放该键的扫描码;对于特殊键(如方向键、 F1~F12等等),低8位为0,高8位字节存放该键的扫描码
声明结构体,food是表示食物基本信息的结构体,snake是定义贪吃蛇基本信息的结构体,代码如下:
struct FOOD int x; /*食物的横坐标*/
贪吃蛇(C语言)
贪吃蛇(C语言)#include#include#include#include#include//蛇头移动方向#define UP 1#define DOWN 2#define LEFT 3#define RIGHT 4〃死亡判定(葱墙或葱自己)#define KISSASS 1#define KISSWALL 2//坐标转化#define POINT(x,y) ((y)*80+(x)+1)// 将(x,y)坐标转化为一个int 类数值#define GETX(x) (((x)-1)%80)// 将int 类数值提取出原先的x#define GETY(y) (((y)-1)/80)// 同理,提取出yHANDLE Console;void Position(int x, int y); // 移动光标到(x,y) //Windows.hvoid DrawMap();// 画墙void ShowText(char *text);//根据字符串的长短智能打印出包围字符串的笑脸void ResetSnake();// 初始化贪吃蛇int RefreshSnake();// 更新蛇的移动void CreatFood();// 生成食物void Draw();//画出蛇身和食物void RefreshScreen();// 屏幕刷新void GameOver(int Type);// 游戏结束条件int Gaming();//代码跑起来char play = 0; ////值为1则继续游戏,值为0游戏退出char pause = 0; //值为1则暂停,值为0游戏继续char direction; // 蛇头方向int snake[500]; //snake[0]为蛇头int body; //蛇身体长度int newbody;//吃完食物新长的蛇身int addHead,deleteTail;//增加蛇头擦去蛇尾,使贪吃蛇动起来int food = 0; // 食物void main()(CONSOLE_CURSOR_INFO CurrInfo = { sizeof(CONSOLE_CURSOR_INFO), 0 };Console = GetStdHandle(STD_OUTPUT_HANDLE);DrawMap();ShowT ext("Copyright reserve by 博元");while(Gaming()){if (play)DrawMap();};return 0;}void Position(int x, int y)// 移动光标到(x,y) //Windows.h{COORD coors = { x, y };SetConsoleCursorPosition(Console, coors);}void DrawMap() // 画墙{int i;for (i = 3; i < 70; i = i + 12){Position(i, 0);printf("===我是墙===");}for (i = 0; i < 25; i = i + 1){Position(0, i);printf("|| ");}for (i = 3; i < 70; i = i + 12){Position(i, 24);printf("============");}for (i = 0; i < 25; i = i + 1){Position(76, i); printf("|| ");void ShowText(char *text) //根据字符串的长短智能打印出包围字符串的笑脸(int i;int strLength = strlen(text); // 得到字符串长度Position(40 - (strLength / 2)-1, 11);printf("%c”, 1);for (i = 0; i < strLength + 2; i++)(printf("%c", 1);}printf("%c", 1);Position(40 - (strLength / 2)-1, 12);printf("%c ", 1);printf(text);printf(" %c", 1);Position(40 - (strLength / 2)-1, 13);printf("%c", 1);for (i = 0; i < strLength + 2; i++)(printf("%c", 1);}printf("%c", 1);}void ResetSnake() //初始化贪吃蛇(int x, y;for (x = 39, y = 0; y < 2; y++)(snake[y] = POINT(x, 7 - y);}body = 2; //设定蛇身初始长度为2newbody = 6;addHead = 0;deleteTail = 0;direction = LEFT;}int RefreshSnake() 〃更新蛇的移动〃返回值为1游戏结束( int x, y;memcpy(snake + 1, snake, sizeof(int)*body);if (!newbody){deleteTail = snake[body];snake[body] = 0;}else{body++;newbody--;}x = GETX(snake[0]);y = GETY(snake[0]);switch (direction) //控制蛇头移动方向{case UP:y -= 1; //蛇头向上移动一格(对应坐标y-1 ) snake[0] = POINT(x, y);break;case DOWN:y += 1;snake[0] = POINT(x, y); break;case LEFT:x -= 1;snake[0] = POINT(x, y); break;case RIGHT:x += 1;snake[0] = POINT(x, y); break;}addHead = snake[0];if (x > 75 || x < 3 ||y > 23 || y < 1) // 检测是否撞墙(GameOver(KISSWALL);return 1;}int i;for (i = 1; i < body; i++)if (snake[0] == snake[i]) // 检测是否撞到自己身体(GameOver(KISSASS);return 1;}if (snake[0] == food)(while (1) //食物的位置不与蛇身重合(food = (rand() % (75 * 23));for (i = 0; snake[i]; i++)if (food == snake[i])// 检测是否吃到食物,吃到则reset食物food = 0;if (food) 〃如果food==0 则重新建立一个食物坐标break;}CreatFood(); // 吃了?再来一个!newbody = (rand() % 6) + 1; // 吃完食物蛇身增长一节}return 0;}void CreatFood() // 生成食物(if (GETX(food) > 75 || GETX(food) < 3 || GETY(food) > 23 || GETY(food) < 1) CreatFood;elsePosition(GETX(food), GETY(food));printf("%c”,4);}void Draw() //画出蛇身和食物(system("cls");int i;for (i = 0; snake[i]; i++)(Position(GETX(snake[i]), GETY(snake[i])); printf("%c”,1);}CreatFood();}void RefreshScreen() // 屏幕刷新(if (deleteTail)(Position(GETX(deleteTail), GETY(deleteTail)); printf("");}if (addHead)(Position(GETX(addHead), GETY(addHead)); printf("%c",1);}addHead = deleteTail = 0;}void GameOver(int Type) // 游戏结束条件(switch (Type)(case KISSASS://? 至ij 自己身体ShowT ext("NOOB !当你以光速绕着一棵树奔跑就会发现自己在葱自己!");break;case KISSWALL://撞墙ShowT ext("NOOB !你有考虑过墙的感受吗");}food = 0;play = 0;memset(snake, 0, sizeof(int) * 500); // 存初始化} int Gaming() // 执行int Keyboardinput;Sleep(60);// 速度if (kbhit())(Keyboardinput = getch();if (Keyboardi nput == 0 || Keyboardinput == 0xE0) (Keyboardinput = getch();switch (Keyboardi nput) // 方向控制(case 72:if (direction != DOWN) direction = UP;break;case 80:if (direction != UP)direction = DOWN;break;case 75:if (direction != RiGHT)direction = LEFT;break;case 77:if (direction != LEFT)direction = RiGHT;break;}}if (Keyboardi nput == '\r') // 暂停(if (!play)(play = 1;if (pause)(Draw();pause = 0;}}else(ShowT ext("不许暂停,继续葱!!");play = 0;pause =1;}}else if (KeyboardI nput == 0x1B) // 退出return 0; } if (play)(if (!food)(srand(clock());food = (rand() % (75 * 23)); ResetSnake();Draw();}else(if (!RefreshSnake())(RefreshScreen();}}}。
C语言实现贪吃蛇游戏代码
C语⾔实现贪吃蛇游戏代码本⽂实例为⼤家分享了C语⾔实现贪吃蛇游戏的具体代码,供⼤家参考,具体内容如下//------------------------------------------problm区------------------------------//①思考typedef 定义的变量如何利⽤fwrite进⾏存储//②典型可利⽤sleep()语句类实现控制移动速度//③BOOL PlaySoundW(LPCWSTR, HMODULE, DWORD)”: ⽆法将参数 1 从“const char[8]”转换为“LPCWSTR -->导致原因-->即原因vc2010开发环境中可能找不到字符串的⾳乐导致//④思考怎么消去不是这四个键的情况#include<stdio.h>#include<stdlib.h>#include<Windows.h>#include<conio.h>#include<string.h>#include<time.h>#include <MMSystem.h>//导⼊声⾳头⽂件-->即联合形成#pragma warning(disable:4996)//可以利⽤该代码消去警告类#pragma comment(lib, "Winmm.lib")//链接库//------------------------------------------变量区---------------------------------//---------------------------------------宏定义变量定义----------------------------#define H 24//定义⾼为24#define W 78//定义宽为78#define false 0#define true 1//-------------------------------------⾮宏定义变量定义----------------------------int n=0;//全局变量定⽤于写界⾯的状况int zpalyer=0;//记录总玩家的个数int fs;//⽤于记录玩家的分数int key=72;//⽤于控制玩家的移动⽅向的变量,且赋予初始化值为上int changeFlag = 0;//判断是否吃到了果实,⽤于确定是否需要擦除蛇尾int i;//⽤于函数中控制循环的变量char name[20];char name1[20];struct palyerinfo//定义玩家的名称与分数的结构体{char name[20];int palyefs;}player[100];struct //定义贪吃蛇的⾷物产⽣的坐标类{int x;int y;}food;struct //利⽤链表实现贪吃蛇的长度{int x[100];int y[100];int len;int zfs;int speed;}snake1;//------------------------------------------声明区---------------------------------void xj();void dq();void save();void ck();void xuanz();void jm();void phb();void fs1();int begin();void creatfood();void keyDown();bool sfjs();void getoxy(int x,int y);void ex();int yy();//------------------------------------------函数区---------------------------------//-----------------------------------------界⾯函数区------------------------------void menu1()//进⼊游戏后选择读取⽤户还是新建⽤户{int n;system("color 3e");//即加⼀个语句即可控制颜⾊,即与cmd中类似进⾏控制颜⾊-->控制的是控制台的颜⾊printf("====================================================\n");printf("# #\n");printf("# #\n");printf("# 1. 建⽴新玩家 #\n");printf("# 2. 读取存档 #\n");printf("# #\n");printf("# #\n");printf("====================================================\n");printf(" 选项:");scanf("%d", &n);if (n == 1){xj();}elseif (n == 2){dq();}else{printf("输⼊错误,请重新选择:\n");menu1();}}void menu2()//游戏⾥⾯的主菜单{int n;printf("====================================================\n");printf("# #\n");printf("# 贪吃蛇 Version goddemon #\n");printf("# #\n");printf("# 1. 开始游戏 #\n");printf("# 2. 查看排⾏榜 #\n");printf("# 3. 查看我的分数 #\n");printf("# 4. 退出游戏 #\n");printf("# #\n");printf("# #\n");printf("====================================================\n");printf(" 选项:\n");while (1){scanf_s("%d", &n);switch (n)//选择功能{case 1: begin(); break;case 2: phb(); break;case 3: fs1(); break;case 4: ex(); break;default: printf("输出错误,请重新输⼊:\n"); break;}}}void xj()//新建⽤户的名字{ck();++zpalyer; //注意如果是在退出的时候赋予的值,会出现只能读出两个值的状况特点-->即在⼦函数中赋予值,必须在读取值后进⾏赋予值加减才可,否则可能出现乱码状况 printf("\t\t输⼊⽤户名:\n");//注意利⽤\t\t进⾏控制界⾯-->很nicescanf("%s", name);strcpy(player[zpalyer].name,name);//注意赋值的先后menu2();}void dq()//读取存档⾥⾯的⽤户且进⾏选择{ck();printf("请输⼊读取的姓名:\n");scanf("%s", name1);for (i = 0; i <= zpalyer; i++){if ((strcmp(player[i].name, name1) == 0)){menu2();}elseif(i==zpalyer){printf("未找到该⽤户,请在次选择读取与创建功能\n");menu1();}}}//-----------------------------功能函数区---------------------------------int begin()//开始游戏{system("cls");jm();while (1){keyDown();if (!sfjs())break;creatfood();Sleep(snake1.speed);}player[zpalyer].palyefs = snake1.zfs;getoxy(W / 2, H / 2);printf("本次得分:%d\n",snake1.zfs);Sleep(3000);system("cls");menu2();Sleep(5000);return 0;}void phb()//排⾏榜{int i;printf("====================== 排⾏榜 ====================\n");for (i = 0; i <zpalyer; i++){printf("%s\t%d\n", player[i].name, player[i].palyefs);}printf("====================================================\n");}void fs1()//查看⾃⼰的分数{printf("你的分数为:\n");printf("%d", player[zpalyer].palyefs);}void ex()//退出功能{save();exit(0);}void save(){FILE *fp;fp = fopen("tcs.txt", "w+");fwrite(&zpalyer, 4, 1, fp);for (i = 0; i <= zpalyer; i++){fwrite(&player[i], sizeof(struct palyerinfo), 1, fp);}fclose(fp);}void ck()//读取⽂档中的数据状况{FILE *fp;int i;fp = fopen("tcs.txt", "r+");fread(&zpalyer, 4, 1, fp);for (i = 0; i <=zpalyer; i++){fread(&player[i], sizeof(struct palyerinfo), 1, fp);}fclose(fp);}void xuanz(){int j = 0, x = 1;menu2();}void getoxy(int x,int y)//定位坐标位置的函数{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);}void jm()//贪吃蛇初始化界⾯{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY); system("color 3e");//打印上下边界的循环for (i = 0; i <= W; i+=2){getoxy(i, 0);printf("++");getoxy(i,H);//打印下边界printf("++");}for (i = 0; i < H; i++){getoxy(0, i);printf("++");getoxy(W, i);printf("++");//打印下边界}while (1)//⽣成初始化的⾷物{srand((unsigned int)time(NULL));food.x = rand() % (W - 4) + 2;food.y = rand() % (H - 2) + 1;if (food.x % 2 == 0){break;}}getoxy(food.x, food.y);printf("*");snake1.len = 3;snake1.speed = 200;snake1.x[0] = W / 2 + 1;//即在中间区域打印蛇头snake1.y[0] = H / 2;getoxy(snake1.x[0], snake1.y[0]);printf("★");for (i = 1; i < snake1.len; i++)//打印蛇头的状况特点-->利⽤getoxy(光标移动)+printf语句联合打印出蛇 {snake1.x[i] = snake1.x[i - 1] + 2;//即将坐标赋值加2的状况理解snake1.y[i] = snake1.y[i - 1];getoxy(snake1.x[i], snake1.y[i]);printf("★");}getoxy(W - 2,0);return;}void creatfood()//创建⾷物的函数{if (snake1.x[0] == food.x&&snake1.y[0] == food.y)//即蛇会吃掉这个⾷物{while (1){int flag = 1;srand((unsigned int)time(NULL));food.x = rand() % (W - 4) + 2;food.y = rand() % (H - 2) + 1;for (i = 0; i < snake1.len; i++){if (snake1.x[i] == food.x&&snake1.y[i] == food.y){flag = 0;break;}}if (flag&&food.x % 2 == 0)//⽤该语句进⾏判断是否该结束坐标赋值{break;}}getoxy(food.x, food.y);//即创建⾷物,每⼀次都进⾏创造printf("*");snake1.len++;//即蛇的长度加1,因为吃到了⾷物导致snake1.speed -= 5;snake1.zfs += 10;//即⼀个果实的分数等于10分changeFlag = 1;//即意味着吃到了⾷物,不需要擦除蛇尾的含义}return;//即return可以为空}void keyDown()//控制移动的函数{int pre_key = key;//记录前⼀个按键的⽅向if (_kbhit()){fflush(stdin);//getch()读取⽅向键的时候,会返回两次,第⼀次调⽤返回0或者224,第⼆次调⽤返回的才是实际值 key = _getch();//第⼀次调⽤返回的不是实际值key = _getch();//第⼆次调⽤返回实际值}if (changeFlag == 0){getoxy(snake1.x[snake1.len - 1], snake1.y[snake1.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}//将蛇的每⼀节依次向前移动⼀节(蛇头除外)for (i = snake1.len - 1; i > 0; i--){snake1.x[i] = snake1.x[i - 1];snake1.y[i] = snake1.y[i - 1];}if (pre_key == 72 && key == 80)key = 72;if (pre_key == 80 && key == 72)key = 80;if (pre_key == 75 && key == 77)key = 75;if (pre_key == 77 && key == 75)key = 77;switch (key){case 75:snake1.x[0] -= 2;//往左break;case 77:snake1.x[0] += 2;//往右break;case 72:snake1.y[0]--;//往上break;case 80:snake1.y[0]++;//往下break;}//打印出蛇头getoxy(snake1.x[0], snake1.y[0]);printf("★");getoxy(W - 2, 0);//由于⽬前没有吃到⾷物,changFlag值为0changeFlag = 0;return;}bool sfjs()//判断游戏是否结束的函数{if (snake1.y[0] == 0 || snake1.y[0] == H){return false;}if (snake1.x[0] == 0 || snake1.x[0] == W){return false;}for (i = 1; i < snake1.len; i++){if (snake1.x[i] == snake1.x[0] && snake1.y[i] == snake1.y[0])//注意判断是否结束的函数需要注意{return false;}}return true;//即返回这个函数本⾝为真}int yy(){PlaySound(TEXT("F:\\⼩苹果.wav"), NULL, SND_NODEFAULT | SND_ASYNC | SND_LOOP);//即利⽤转换参数进⾏代//SND_LOOP-->//重复播放声⾳,必须与SND_ASYNC标志⼀块使⽤//SND_ASYNC-->//⽤异步⽅式播放声⾳,PlaySound函数在开始播放后⽴即返回//SND_NODEFAULT -->不播放缺省声⾳,若⽆此标志,则PlaySound在没找到声⾳时会播放缺省声⾳-->典型找⽂件⾳乐是⽤的格式查看⽅式进⾏找的 return 0;}//------------------------------------------主函数区-------------------------------int main(){yy();menu1();system("pause");return 0;}效果图:更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
C语言课程设计贪吃蛇源代码
C语言程序贪吃蛇代码#include<stdio.h>#include<windows.h>#include<time.h>#include<stdlib.h>#include<conio.h>#define N 21FILE *fp;int S;void boundary(void);//开始界面void end(void); //结束void gotoxy(int x,int y)//位置函数{COORD pos;pos.X=x;pos.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); }void color(int a)//颜色函数{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);}void init(int food[2])//初始化函数(初始化围墙、显示信息、苹果){system("cls");int i,j;//初始化围墙int wall[N+2][N+2]={{0}};//初始化围墙的二维数组for(i=1;i<=N;i++){for(j=1;j<=N;j++)wall[i][j]=1;}color(10);for(i=0;i<N+2;i++)//畵围墙{for(j=0;j<N+2;j++){if(wall[i][j])printf(" ");else printf("#") ;}printf("\n") ;}gotoxy(N+3,3);//显示信息color(14);printf("\t\t按a,b,c,d改变方向\n");gotoxy(N+3,1);color(14);printf("\t\t按任意键暂停,按1返回,按2退出\n"); gotoxy(N+5,3);color(14);printf("score:\n");food[0]=rand()%N+1;//随机出现食物food[1]=rand()%N+1;gotoxy(food[0],food[1]);color(12);printf("*\n");}void play()//具体玩的过程{system("cls");int i,j;int** snake=NULL;//定义蛇的二维指针int food[2];//食物的数组,food[0]代表横坐标,food[1]代表纵坐标int score=0;//为得分int tail[2];//此数组为了记录蛇的头的坐标int node=3;//蛇的节数char ch='p';srand((unsigned)time(NULL));//随机数发生器的初始化函数init(food);snake=(int**)realloc(snake,sizeof(int*)*node);//改变snake所指内存区域的大小为node长度for(i=0;i<node;i++)snake[i]=(int*)malloc(sizeof(int)*2);for(i=0;i<node;i++)//初始化蛇的长度{snake[i][0]=N/2;snake[i][1]=N/2+i;gotoxy(snake[i][0],snake[i][1]);color(14);printf("*\n");}while(1)//进入消息循环{gotoxy(5,0);color(10);printf("#");gotoxy(0,5);color(10);printf("#");gotoxy(0,7);color(10);printf("#");gotoxy(0,9);color(10);printf("#");tail[0]=snake[node-1][0];//将蛇的后一节坐标赋给tail数组tail[1]=snake[node-1][1];gotoxy(tail[0],tail[1]);color(0);printf(" ");for(i=node-1;i>0;i--)//蛇想前移动的关键算法,后一节的占据前一节的地址坐标{snake[i][0]=snake[i-1][0];snake[i][1]=snake[i-1][1];gotoxy(snake[i][0],snake[i][1]);color(14);printf("*\n");}if(kbhit())//捕捉输入信息gotoxy(0,N+2);ch=getche();}switch(ch){case 'w':snake[0][1]--;break;case 's':snake[0][1]++;break;case 'a':snake[0][0]--;break;case 'd':snake[0][0]++;break;case '1':boundary() ;break;case '2':end();break;default: break;}gotoxy(snake[0][0],snake[0][1]);color(14);printf("*\n");Sleep(abs(200-0.5*score));//使随着分数的增长蛇的移动速度越来越快if(snake[0][0]==food[0]&&snake[0][1]==food[1])//吃掉食物后蛇分数加1,蛇长加1 {score++;//分数增加S=score;node++;//节数增加snake=(int**)realloc(snake,sizeof(int*)*node);snake[node-1]=(int*)malloc(sizeof(int)*2);food[0]=rand()%N+1;//产生随机数且要在围墙内部food[1]=rand()%N+1;gotoxy(food[0],food[1]);color(12);printf("*\n");gotoxy(N+12,3);color(14);printf("%d\n",score);//输出得分}if(snake[0][1]==0||snake[0][1]==N+1||snake[0][0]==0||snake[0][0]==N+1)//撞到围墙后失败{gotoxy(N/2,N/2);color(30);printf("GAME OVER\n");for(i=0;i<node;i++)free(snake[i]);Sleep(INFINITE);exit(0);}}//从蛇的第四节开始判断是否撞到自己,因为蛇头为两节,第三节不可能拐过来for (i=3; i<node; i++){for(j=0;j<node;j++){if (snake[i][0]==snake[j][0] && snake[i][1]==snake[j][1]){gotoxy(N/2,N/2);color(30);printf("GAME OVER\n");for(i=0;i<node;i++)free(snake[i]);Sleep(INFINITE);exit(0);;}}}}void end()//结束函数{system("cls");system("cls");printf("EXIT\n");}void grade()//成绩记录函数{system("cls");int i=0;char s;if( (fp=fopen("f:\\贪吃蛇\\贪吃蛇.txt","ar") )==NULL)//打开文件{printf("\nCannot open file!\n");exit(0);}if(i<S)i=S;color(14);fwrite(&i,sizeof(i),1,fp);fclose(fp);printf("最高的分为:%d\n\n",i);printf("\t按1返回\n\n");printf("\t按2退出\n\n");s=getche();switch(s){case '1':boundary();break;case '2': end();break;}}void boundary()//开始界面{system("cls");char s;color(14);printf("\t\t欢迎来玩!!\n\n");printf("\t\t1:开始\n\n");printf("\t\t2:查看成绩\n\n");printf("\t\t3:退出\n\n");printf("\t\t请选择:");s=getche();switch(s){case '1': play();break;case '2': grade();break;case '3': end();break;}}int main(){boundary();getchar();return 0;}。
纯C语言编写贪吃蛇(附源码,无EasyX、MFC)
纯C语⾔编写贪吃蛇(附源码,⽆EasyX、MFC)⼤⼀下学期,我所选的C语⾔⼯程实践是写⼀个贪吃蛇游戏。
那⼏天真的挺肝的,完成本专业的答辩之后就没怎么动过这程序了。
那时候写的贪吃蛇,还有⼀个栈溢出的问题没有解决,是因为当时所学知识有限,还没想到较好的解决⽅法。
现在⼤⼆上学期,在上了好⼏节数据结构之后,对栈有了⼀定的了解,随着对栈的学习,我想出了解决我写的贪吃蛇栈溢出的办法。
其实是前两天刚刚有这个想法,刚刚才测试并实现了,办法可⾏。
现在我加⼊了计算机学院的创新开放实验室,打算做的⼀个项⽬是微信⼩程序。
以后想记录⼀下我的开发过程和⼀些经历,⼜刚刚完善好贪吃蛇的代码,就简单记录⼀下吧。
因为代码⽐较长,先把参考资料写⼀下,想⾃⼰⼿写⼀遍的建议先看参考资料,再看这⾥的代码参考资料源代码/*预处理*/#include <windows.h>#include <stdio.h>#include <conio.h>#include <string.h>#include <time.h>/*宏定义*/#define YES 1#define NO 0//蛇的移动⽅向#define U 1 //上#define D 2 //下#define L 3 //左#define R 4 //右#define RESPEED 250 //蛇的移动速度/*定义节点*/typedef struct SNAKE{int x;int y;struct SNAKE* next;}snake;/*全局变量*/snake* head, * food; //蛇头指针,⾷物指针snake* q; //遍历蛇的时候⽤到的指针/*【以下为所有函数的声明】*/void HideCursor(void); //隐藏光标void color(short int num); //颜⾊函数void StartWindow(void); //开始界⾯int gotoxy(int x, int y); //定位光标位置void creatMap(void); //创建地图void notice(int* score, int* highscore, int* Time, int* LongTime); //提⽰void initsnake(void); //初始化蛇⾝int biteself(unsigned long* sleeptime); //判断是否咬到了⾃⼰int createfood(void); //随机出现⾷物void endgame(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime); //结束游戏void pause(int* PauseBegin, int* PauseEnd); //暂停游戏void gamecontrol(unsigned long* sleeptime, int* count, int* score, int* highscore, int* status, int* endgamestatus,int* Time, int* LongTime, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //控制游戏(包含蛇不能穿墙)void snakemove(unsigned long* sleeptime, int* count, int* score, int* status, int* endgamestatus); //蛇移动void gamestart(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime, int* TimeBegin); //游戏初始化void gamecontinue(unsigned long* sleeptime, int* count, int* score, int* highscore, int* status, int* endgamestatus,int* Time, int* LongTime, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //再来⼀局void stop(unsigned long* sleeptime); //蛇停⽌移动void start(unsigned long* sleeptime); //蛇恢复移动void reset(int* count, int* score, int* Time, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //重置多项数据void updatescore(int* score, int* highscore, int* Time, int* LongTime); //更新多项数据int main(void){unsigned long sleeptime = RESPEED;int score = 0, highscore = 0, count = 0; //count是记录吃到⾷物的次数int status, endgamestatus = 0; //游戏结束情况,0未开始游戏前退出,1撞到墙,2咬到⾃⼰,3主动退出游戏,4通关HideCursor();gamestart(&score, &highscore, &endgamestatus, &Time, &LongTime, &TimeBegin);gamecontrol(&sleeptime, &count, &score, &highscore, &status, &endgamestatus, &Time, &LongTime, &TimeBegin, &TimeEnd, &TimePause, &Pa useBegin, &PauseEnd);endgame(&score, &highscore, &endgamestatus, &Time, &LongTime);gamecontinue(&sleeptime, &count, &score, &highscore, &status, &endgamestatus, &Time, &LongTime, &TimeBegin, &TimeEnd, &TimePause, &P auseBegin, &PauseEnd);return 0;}void HideCursor(void) //隐藏光标{CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);}void color(short int num){HANDLE hConsole = GetStdHandle((STD_OUTPUT_HANDLE));SetConsoleTextAttribute(hConsole, num);}void StartWindow(void){short int i;system("mode con cols=120 lines=30"); //设置窗⼝⼤⼩printf("温馨提⽰:请使⽤键盘操作(⿏标点击可能会导致程序出错)\n");printf("╔═══════════════════════════════════════════════════╗ \n");for (i = 0; i < 26; i++){printf("║ ║ \n");}printf("╚═══════════════════════════════════════════════════╝ \n");gotoxy(23, 2);color(3);printf("贪吃蛇");for (i = 15; ; i--){gotoxy(18, 4);color(i);printf("按任意键加载程序");Sleep(600);if (i == 1){i = 15;}if (kbhit()) //判断是否按键,等待输⼊按键为0,按键为1{break;}}gotoxy(10, 4);printf("1.开始游戏 2.退出游戏");getch();}int gotoxy(int x, int y){HANDLE handle; //定义句柄变量handle,创建⼀个句柄COORD pos; //定义结构体coord (坐标系coord)pos.X = x; //横坐标xpos.Y = y; //纵坐标yhandle = GetStdHandle(STD_OUTPUT_HANDLE); //获取控制台输出句柄(值为-11)SetConsoleCursorPosition(handle, pos); //移动光标return YES;}void creatMap(void){int i;//地图⼤⼩:长24×宽20printf("■");gotoxy(i, 27);printf("■");}for (i = 7; i < 28; i++) //打印左右边框{gotoxy(2, i);printf("■");gotoxy(50, i);printf("■");}}void notice(int* score, int* highscore, int* Time, int* LongTime){system("title 2018051170 Project:贪吃蛇");gotoxy(4, 4);color(15);printf("得分:%3d 最⾼分:%3d ⽣存:%4ds 最久⽣存:%4ds", *score, *highscore, *Time, *LongTime); gotoxy(60, 7);printf("Author: 2018051170 Project: 贪吃蛇");gotoxy(60, 9);printf("游戏说明:");gotoxy(60, 10);printf("不能穿墙,不能咬到⾃⼰");gotoxy(60, 11);printf("↑↓←→控制蛇的移动");gotoxy(60, 12);printf("ESC:退出游戏空格:暂停游戏");}void initsnake(void){int i;snake* tail;tail = (snake*)malloc(sizeof(snake)); //从蛇尾开始,插头法,以x,y设定开始的位置tail->x = 26;tail->y = 14;tail->next = NULL;for (i = 1; i < 3; i++){head = (snake*)malloc(sizeof(snake));head->next = tail;head->x = 26 - 2 * i;head->y = 14;tail = head;}while (tail != NULL) //从头到为,输出蛇⾝{gotoxy(tail->x, tail->y);if (i == 3){color(2);printf("●");i++;}else if (tail != NULL){color(2);printf("■");}tail = tail->next;}}int biteself(unsigned long* sleeptime){snake* self;self = head->next;while (self != NULL){if (self->x == head->x && self->y == head->y)self = self->next;}return NO;}int createfood(void){snake* food_1;food_1 = (snake*)malloc(sizeof(snake));srand((unsigned)time(NULL)); //产⽣⼀个随机数while ((food_1->x % 2) != 0) //保证其为偶数,使得⾷物能与蛇头对其{food_1->x = rand() % 50; //保证其在墙壁⾥X1 < X < X2if (food_1->x <= 4){food_1->x = food_1->x + 4;}}food_1->y = rand() % 27; //保证其在墙壁⾥Y1 < Y < Y2if (food_1->y < 7){food_1->y = food_1->y + 7;}q = head;while (q != NULL) //判断蛇⾝是否与⾷物重合{if (q->x == food_1->x && q->y == food_1->y){free(food_1);return 1;}if (q->next == NULL){break;}q = q->next;}gotoxy(food_1->x, food_1->y);food = food_1;color(3);printf("★");return 0;}void endgame(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime) {color(15);gotoxy(60, 14);if (*endgamestatus == 0){printf("您退出了游戏。
贪吃蛇c语言精简版
贪吃蛇c语言精简版//贪吃蛇#include<stdio.h>#include <windows.h>#include <stdlib.h>#include <time.h>#include <conio.h>struct all_xy{POINT point;struct all_xy *next;};int x=2,y=0,key,i,found_time;POINT save_point,save_point2,food_xy={20,10};BOOL end_self=FALSE,flag;struct all_xy *head=NULL,*node1,*node2;void gotoxy(int x, int y){COORD coord;coord.X = x,coord.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);}void snake_add(){for(node2=head;head!=NULL&&node2->next!=NULL;node2=node2->next);node1=(struct all_xy *)malloc(sizeof(struct all_xy));node1->point=(head==NULL?food_xy:node2->point);node1->next=NULL;if(head==NULL){head=node1;return;}else{for(node2=head;node2->next!=NULL;node2=node2->next);node2->next=node1;} }void make_food(long *x,long *y){for(found_time=0;found_time<500;found_time++){*x=(rand()%38+1)*2,*y=rand()%23+1;for(node1=head,flag=FALSE;node1!=NULL;node1=node1->next)if(*x==node1->point.x&&*y==node1->point.y){flag=TRUE;break;}if(!flag){gotoxy(*x,*y);printf("○");return;}}MessageBox(NULL,"已找不到空点放食物了,程序结束!","你太牛了!",MB_ICONASTERISK);exit(0);}int main(){for(i=0;i<3;i++)snake_add();for(srand(time(NULL)),make_food(&food_xy.x,&food_xy.y);;Sleep(400)){if(kbhit()){if((key=getch())==224)key=getch();switch(key){case 80:y!=-1?(x=0,y=1):printf("\a");break;case 72:y!=1?(x=0,y=-1):printf("\a");break;case 75:x!=2?(x=-2,y=0):printf("\a");break;case 77:x!=-2?(x=2,y=0):printf("\a");break;}}node2=head,node1=node2->next,save_point=node1->point;node1->point=node2->point,node1=node1->next;head->point.x+=x,head->point.y+=y;for(node2=head->next;node2!=NULL;node2=node2->next)//依次检查是否自己撞到自己if(node2->point.x==head->point.x&&node2->point.y==head->point.y)//如果发现头结点和任意一个结点的X Y相同则设置end_self的值并跳出{end_self=TRUE;break;}if(head->point.x<0||head->point.x>=78||head->point.y<0||head->point.y>=25| |end_self==TRUE){gotoxy(32,5);printf("游戏结束!");getch();return 0;}for(;node1!=NULL;node1=node1->next){save_point2=node1->point,node1->point=save_point;node2=node1,save_point=save_point2;}gotoxy(save_point.x,save_point.y);printf(" ");if(head->point.x==food_xy.x&&head->point.y==food_xy.y)snake_add(),make_food(&food_xy.x,&food_xy.y);for(node1=head;node1!=NULL;node1=node1->next)gotoxy(node1->point.x,node1->point.y),node1==head?printf("⊙"):printf("□");}}。
贪吃蛇C语言代码实现(难度可选)
贪吃蛇C语⾔代码实现(难度可选)本⽂实例为⼤家分享了C语⾔实现贪吃蛇的具体代码,供⼤家参考,具体内容如下/*****************************************************************************贪吃蛇(难度可选)**********************************制作者:Xu Lizi ⽇期:2012/12/31****************************部分函数有借鉴**********************************************************************************/#include<stdio.h>#include<conio.h>#include<string.h>#include<stdlib.h>#include<time.h>int snakey[100]={5,4,3,2,1}; /*定义蛇的横坐标*/int snakex[100]={1,1,1,1,1}; /*定义蛇的纵坐标,蛇头起始位置为(5,1)*/int life=0; /*定义蛇的⽣命,0表⽰存活,1表⽰死亡*/int lenght=5; /*定义蛇的长度,初始为5节*/char map[12][24]={"***********************", /*y*/"* *","* *","* *","* *","* *","* *","* *","* *","* *","* *",/*x*/ "***********************"};void put_money(int i,int j) /*放钱函数,使⽤随机数,随机出现⾷物*/{int x=0,y=0;srand(time(NULL));while ( (map[y][x]==003) || (map[y][x]==002) || (map[y][x]=='*') || ((x==i)&&(y==j)) ){x=rand()%21+1;y=rand()%10+1;}map[y][x]='$';return;}void output() /*输出*/{system("cls");int i,j;for(i=0; i<12; i++){for(j=0; j<23; j++) printf("%c", map[i][j]);printf("\n");}return;}void gameover() /*游戏结束*/{life=1;printf("笨蛋,输了吧\n");return;}void turn_up() /*向上移动*/{system("cls");int i;if ( (snakex[0]==1) || (map[snakex[0]-1][snakey[0]]==003) ) gameover(); else { if (map[snakex[0]-1][snakey[0]]=='$'){put_money( snakey[0], snakex[0]-1 );lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}map[snakex[lenght]][snakey[lenght]]=' ';snakex[0]--;for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}void turn_down() /*向下*/{system("cls");int i;if ( (snakex[0]==10) || (map[snakex[0]+1][snakey[0]]==003) ) gameover();else { if (map[snakex[0]+1][snakey[0]]=='$'){put_money(snakey[0],snakex[0]+1);lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}snakex[0]++;map[snakex[lenght]][snakey[lenght]]=' ';for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}void turn_left() /*向左*/{system("cls");int i;if ( (snakey[0]==1) || (map[snakex[0]][snakey[0]-1]==003) ) gameover();else { if (map[snakex[0]][snakey[0]-1]=='$'){put_money(snakey[0]-1,snakex[0]);lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}map[snakex[lenght]][snakey[lenght]]=' ';snakey[0]--;for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}void turn_right() /*向右*/{system("cls");int i;if ( (snakey[0]==21) || (map[snakex[0]][snakey[0]+1]==003) ) gameover();else {if (map[snakex[0]][snakey[0]+1]=='$'){put_money(snakey[0]+1,snakex[0]);lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}map[snakex[lenght]][snakey[lenght]]=' ';snakey[0]++;for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}int main(){int i,timeover,hard;long start;char name , direcation;printf("\n 向上移动:W ;向下移动:S ; 向左移动:A ;向右移动:D \n");printf("\t请选择难度(数字)\n\t分1~5级,分别代表\n\t1难,2中上,3中,4中下5,易:\n");scanf("%d",&hard);system("cls");for(i=1;i<5;i++) map[1][i]=003; /*输出蛇⾝*/map[1][5]=002; /*输出蛇头*/put_money(0,0);output();while(life!=1) /*当蛇死亡时结束循环*/{/*让蛇⾃动运⾏的函数******有借鉴*/timeover=1;start=clock();while((timeover=(clock()-start<=hard*100))&&!kbhit()); //难度设定if(timeover){direcation=getch();}/*让蛇⾃动运⾏的函数******有借鉴*/switch(direcation){case 'w':turn_up();break;case 's':turn_down();break;case 'a':turn_left();break;case 'd':turn_right();break;}}return 0;}更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
C语言实现贪吃蛇游戏
C语言实现贪吃蛇游戏贪吃蛇游戏是一款经典的益智休闲游戏,通过控制一条贪吃蛇在游戏画面中不断吃食物,使其身体不断变长的同时避免碰壁或撞到自己以免游戏结束。
本文将使用C语言进行贪吃蛇游戏的实现,并介绍其基本原理和步骤。
首先,我们需要了解贪吃蛇游戏的基本规则。
在游戏开始时,屏幕上会出现一条初始长度为1的贪吃蛇和一个食物。
玩家可以通过按下方向键来控制贪吃蛇的移动方向,当贪吃蛇吃到食物时,其身体长度就会增加,并随机在屏幕上出现一个新的食物。
当贪吃蛇的头部撞到墙壁或撞到自己的身体时,游戏结束。
接下来,我们将介绍如何使用C语言来实现贪吃蛇游戏。
首先,我们需要定义贪吃蛇的数据结构。
我们可以将贪吃蛇的每个身体部分看作一个节点,每个节点包含一个坐标表示位置和一个指针指向下一个节点。
使用链表来表示贪吃蛇的身体可以方便地进行长度的增加和删除操作。
在游戏开始前,我们需要初始化游戏界面和贪吃蛇。
可以使用二维数组来表示游戏界面,其中每个元素代表一个格子。
将贪吃蛇的初始位置(通常位于游戏界面的中心)作为链表的头节点,并将其绘制在游戏界面上。
接下来,我们需要监听玩家的输入,并根据输入来改变贪吃蛇的移动方向。
可以使用C语言中的键盘事件处理函数来实现这一功能,并通过对按键的判断来确定贪吃蛇的新的移动方向。
一旦玩家改变了贪吃蛇的移动方向,我们需要更新贪吃蛇的位置。
贪吃蛇的身体每移动一步,就将链表中的每个节点的坐标改变为前一个节点的坐标。
我们还需要判断贪吃蛇是否吃到了食物。
如果贪吃蛇的头部和食物的坐标相同,就将贪吃蛇的长度增加,并在游戏界面中重新生成一个新的食物。
同时,我们还需要判断贪吃蛇是否碰到了墙壁或撞到了自己的身体。
如果贪吃蛇的头部的坐标超出了游戏界面的范围,或者与贪吃蛇的身体的节点坐标相同,就表示游戏结束。
在游戏进行的过程中,我们需要不断地更新游戏界面,并将贪吃蛇和食物绘制在屏幕上。
可以使用C语言中的绘图函数来实现这一功能。
同时,我们还可以添加一些音效和背景音乐来增强游戏的趣味性。
c语言控制台的贪吃蛇(Clanguageconsolesnake)
c语言控制台的贪吃蛇(C language console snake)*1* *1* *1* xt* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* xt* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* / / ZT* xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓rx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓TX ✓TX ✓TX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ✓Ix xlx / /*1* *1* *1* xt* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* xt* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1*//ZT* xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓rx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓TX ✓TX ✓TX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ✓Ix xlx/// **************版权所有*** 2011. 9. 20 ***咸鱼************** /*1* *1* *1* xt* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* xt* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1*//ZT* xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓rx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓TX ✓TX ✓TX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ✓Ix xlx/// ***友情提示:如想速度快点,请改小_sleep (500)函数中参数****1* *1* *1* xt* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* XL* xt* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* *1* / / ZT* xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx xlx ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓?* ✓rx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓Tx ✓TX ✓TX ✓TX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ZTX ✓Ix xlx / /#包括〈stdio. h >#包括〈〈程序。
c语言贪吃蛇UI界面版
c语言U I界面版贪吃蛇使用ege图形库,游戏实现单双人功能。
道具有炸弹,随机魔盒,炸弹。
有随机障碍物生成。
不附加图片。
/*****************************************************************************出品方:债组* 成员:冯强陈志豪邓青松俄木木果* 时间:2016/7/11 ********************************************************************************/#include "graphics.h"#include <stdio.h>#include<time.h>#include<stdlib.h>#include<stdio.h>#include<time.h>#include<windows.h>#include <process.h>#define printf outtextint speed=5;#define U 1#define D 2#define L 3#define R 4#define A 5#define S 6#define W 7#define Dd 8#define VK_A 0x41//虚拟键值宏定义#define VK_S 0x53#define VK_W 0x57#define VK_D 0X44#define VK_N 0X4E#define VK_M 0x4d#define wd 10//蛇身的宽#define hg 10//蛇身的高//蛇身的一个节点typedef struct SNAKE{int x;int y;struct SNAKE *next;}snake;//全局变量//int score = 0, add = 10, score1 = 0, add1 = 10;;//总得分与每次吃食物得分。
C语言实现贪吃蛇小黑窗
C语⾔实现贪吃蛇⼩⿊窗本⽂实例为⼤家分享了C语⾔实现贪吃蛇⼩⿊窗的具体代码,供⼤家参考,具体内容如下思路:1.利⽤整型⼆维数组保存显⽰数据,⼩蛇每移动⼀次清屏并便利数组做到动态效果。
每次移动(清屏)的间隔时间控制了游戏难度,这个时间应不断缩减,直到游戏结束。
2.需要保存⼩蛇移动的⽅向,然后写⼀个函数通过⼩蛇的移动⽅向去处理⼆维数组中的数据,达到移动⼩蛇的⽬的。
3.⼩蛇的移动可分解为两个过程:头部像前⽅⽣长⼀格然后尾部消去⼀格。
如果蛇头吃到⾷物,尾部⽆需消去,此时应⽴即随机⽣成⼀个新的⾷物。
4.游戏开始时⼩蛇应随机⽣成在地图某⼀位置,此时⼩蛇的默认移动⽅向也应该是随机的。
5每次移动前应接收玩家由键盘输⼊的移动⽅向,如果接收到后,判断合法后将其设为⼩蛇的默认移动⽅向,如果玩家未进⾏任何输⼊,⼩蛇应按照默认⽅向移动。
个⼈难点:1.⼩蛇移动该函数需要拿到蛇头当时所在的位置坐标和⼩蛇的移动⽅向。
随后可由蛇头位置往移动⽅向往前⽣长⼀格,即将⼆维数组中⽬标移动位置的数据设置为⼩蛇的数据。
消去蛇尾另写⼀个函数,调⽤前需先判断是否吃到⾷物,是否撞到墙壁或者是⾃⾝,然后决定是否削去尾部。
消去蛇尾需获得蛇尾的位置,所以我们在该函数内加⼊递归搜索蛇尾的算法:进⼊函数后先判断此时的位置是否为蛇尾,若不是就将⾃⾝位置往后移动⼀格(将蛇⾝往后⼀格的坐标输⼊给DeleteTail函数,然后继续此过程),直到遇到蛇尾,然后将其消去(置零)。
具体代码实现如下:int MoveSnake(int trend, int* px, int* py, int data[ROW][COL], int* t){int ret = 1;//默认前进成功//printf("trend=%d\n", trend);switch (trend) {case 1:*py -= 1; break;//向上case 2:*px -= 1; break;//向左case 3:*py += 1; break;//向下case 4:*px += 1; break;//向右}//找到即将前进的坐标if (data[*py][*px] == 6) {data[*py][*px] = trend;CreatFood(data);*t *= 0.9;}//如果蛇头要前进的格⼦是⾷物,向前长⼀格,尾部不变;else if (data[*py][*px] == 0) {data[*py][*px] = trend;//向前长⼀格DeleteTail(*px, *py, data);//消去最后的尾巴}else {ret = 0;printf("前进失败\n");}//前进失败return ret;}int DeleteTail(int x, int y, int data[ROW][COL]){//PrintTest(data);if (data[y][x] <= 4 && data[y][x] >= 1) {switch (data[y][x]) {case 1:if (DeleteTail(x, y + 1, data) == 0) {data[y][x] = 0;}break;case 2:if (DeleteTail(x + 1, y, data) == 0) {data[y][x] = 0;}break;case 3:if (DeleteTail(x, y - 1, data) == 0) {data[y][x] = 0;}break;case 4:if (DeleteTail(x - 1, y, data) == 0) {data[y][x] = 0;}break;}return 1;}else {return 0;}}2.输⼊在实际代码实现的过程中,我发现scanf函数⽆法实现需求,理由是程序执⾏到scanf语句时,会停留在该位置,直到scanf函数扫描到输⼊后,程序才会继续进⾏。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
c语言贪吃蛇U I界面版Newly compiled on November 23, 2020
c语言U I界面版贪吃蛇
使用ege图形库,游戏实现单双人功能。
道具有炸弹,随机魔盒,炸弹。
有随机障碍物生成。
不附加图片。
/*************************************************************************** *
*
出品方:债组 *
成员:冯强陈志豪邓青松俄木木果 *
时间:2016/7/11 *
*
*
**************************************************************************** */
#include ""
#include <>
#include<>
#include<>
#include<>
#include<>
#include<>
#include <>
#define printf outtext
int speed=5;
#define U 1
#define D 2
#define L 3
#define R 4
#define A 5
#define S 6
#define W 7
#define Dd 8
#define VK_A 0x41;
}
else if (endgamestatus == 2)
{
xyprintf(200, 200, "对不起,您咬到自己了。
游戏结束.");
}
else if (endgamestatus == 3).←.→分别控制蛇的移动, F1 为加速,2 为减速\n");
xyprintf(25,13,"加速将能得到更高的分数。
\n");*/
}
int main()
{
initgraph(640, 480);
setcaption("债组:青白夺塔");
UI();
Fence() ;
getch();
return 0;
}。