贪吃蛇源程序(c语言版的)

合集下载

C语言实现贪吃蛇游戏

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语言小游戏源代码《贪吃蛇》
void main(void){/*主函数体,调用以下四个函数*/ init(); setbkcolor(7); drawk(); gameplay(); close(); }
void init(void){/*构建图形驱动函数*/ int gd=DETECT,gm; initgraph(&gd,&gm,""); cleardevice(); }
欢迎您阅读该资料希望该资料能给您的学习和生活带来帮助如果您还了解更多的相关知识也欢迎您分享出来让我们大家能共同进步共同成长
C 语言小游戏源代码《贪吃பைடு நூலகம்》
#define N 200/*定义全局常量*/ #define m 25 #include <graphics.h> #include <math.h> #include <stdlib.h> #include <dos.h> #define LEFT 0x4b00 #define RIGHT 0x4d00 #define DOWN 0x5000 #define UP 0x4800 #define Esc 0x011b int i,j,key,k; struct Food/*构造食物结构体*/ { int x; int y; int yes; }food; struct Goods/*构造宝贝结构体*/ { int x; int y; int yes; }goods; struct Block/*构造障碍物结构体*/ { int x[m]; int y[m]; int yes; }block; struct Snake{/*构造蛇结构体*/ int x[N]; int y[N]; int node; int direction; int life; }snake; struct Game/*构建游戏级别参数体*/ { int score; int level; int speed;

贪吃蛇游戏c语言源代码

贪吃蛇游戏c语言源代码

Ì°³ÔÉßÓÎÏ·cÓïÑÔÔ´´úÂë.txtÊÀÉÏ×îÕä¹óµÄ²»ÊÇÓÀÔ¶µÃ²»µ½»òÒѾ­µÃµ½µÄ£¬¶øÊÇÄãÒѾ­µÃµ½²¢ÇÒËæʱ¶¼ÓпÉÄÜʧȥµÄ¶«Î÷£¡°®ÇéÊǵƣ¬ÓÑÇéÊÇÓ°×Ó¡£µÆÃðʱ£¬Äã»á·¢ÏÖÖÜΧ¶¼ÊÇÓ°×Ó¡£ÅóÓÑ£¬ÊÇÔÚ×îºó¿ÉÒÔ¸øÄãÁ¦Á¿µÄÈË¡£#inclu de <stdlib.h>#include <graphics.h>#include <bios.h>#include <dos.h>#include <conio.h>#define Enter 7181#define ESC 283#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#ifdef __cplusplus#define __CPPARGS ...#else#define __CPPARGS#endifvoid interrupt (*oldhandler)(__CPPARGS);void interrupt newhandler(__CPPARGS);void SetTimer(void interrupt (*IntProc)(__CPPARGS));void KillTimer(void);void Initgra(void);void TheFirstBlock(void);void DrawMap(void);void Initsnake(void);void Initfood(void);void Snake_Headmv(void);void Flag(int,int,int,int);void GameOver(void);void Snake_Bodymv(void);void Snake_Bodyadd(void);void PrntScore(void);void Timer(void);void Win(void);void TheSecondBlock(void);void Food(void);void Dsnkorfd(int,int,int);void Delay(int);struct Snake{int x;int y;int color;}Snk[12];struct Food{int x;int y;int color;}Fd;int flag1=1,flag2=0,flag3=0,flag4=0,flag5=0,flag6=0,checkx,checky,num,key=0,Times,Score,Hscore,Snkspeed,TimerCounter,TureorFalse; char Sco[2],Time[6];void main(){ Initgra();SetTimer(newhandler);TheFirstBlock();while(1){DrawMap();Snake_Headmv();GameOver();Snake_Bodymv();Snake_Bodyadd();PrntScore();Timer();Win();if(key==ESC)break;if(key==Enter){cleardevice();TheFirstBlock();}TheSecondBlock();Food();Delay(Snkspeed);}closegraph();KillTimer();}void interrupt newhandler(__CPPARGS){TimerCounter++;oldhandler();}void SetTimer(void interrupt (*IntProc)(__CPPARGS)){oldhandler=getvect(0x1c);disable();setvect(0x1c,IntProc);enable();}void KillTimer(){disable();setvect(0x1c,oldhandler);enable();}void Initgra(){int gd=DETECT,gm;initgraph(&gd,&gm,"d:\\tc");}void TheFirstBlock(){setcolor(11);settextstyle(0,0,4);outtextxy(100,220,"The First Block");loop:key=bioskey(0);if(key==Enter){cleardevice();Initsnake();Initfood();Score=0;Hscore=1;Snkspeed=10;num=2;Times=0;key=0;TureorFalse=1;TimerCounter=0;Time[0]='0';Time[1]='0';Time[2]=':';Time[3]='1';Time[4]='0';Time[5]='\0'; }else if(key==ESC) cleardevice();else goto loop;}void DrawMap(){line(10,10,470,10);line(470,10,470,470);line(470,470,10,470);line(10,470,10,10);line(480,20,620,20);line(620,20,620,460);line(620,460,480,460);line(480,460,480,20);}void Initsnake(){randomize();num=2;Snk[0].x=random(440);Snk[0].x=Snk[0].x-Snk[0].x%20+50;Snk[0].y=random(440);Snk[0].y=Snk[0].y-Snk[0].y%20+50;Snk[0].color=4;Snk[1].x=Snk[0].x;Snk[1].y=Snk[0].y+20;Snk[1].color=4;}void Initfood(){randomize();Fd.x=random(440);Fd.x=Fd.x-Fd.x%20+30;Fd.y=random(440);Fd.y=Fd.y-Fd.y%20+30;Fd.color=random(14)+1;}void Snake_Headmv(){if(bioskey(1)){key=bioskey(0);switch(key){case UP:Flag(1,0,0,0);break;case DOWN:Flag(0,1,0,0);break;case LEFT:Flag(0,0,1,0);break;case RIGHT:Flag(0,0,0,1);break;default:break;}}if(flag1){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].y-=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color); }if(flag2){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].y+=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}if(flag3){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].x-=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}if(flag4){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].x+=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}}void Flag(int a,int b,int c,int d){flag1=a;flag2=b;flag3=c;flag4=d;}void GameOver(){int i;if(Snk[0].x<20||Snk[0].x>460||Snk[0].y<20||Snk[0].y>460) {cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop1:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}elseif(key==ESC)cleardevice();elsegoto loop1;}for(i=3;i<num;i++){if(Snk[0].x==Snk[i].x&&Snk[0].y==Snk[i].y) {cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop2:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}elseif(key==ESC)cleardevice();else goto loop2;}}}void Snake_Bodymv(){int i,s,t;for(i=1;i<num;i++){Dsnkorfd(checkx,checky,Snk[i].color); Dsnkorfd(Snk[i].x,Snk[i].y,0);s=Snk[i].x;t=Snk[i].y;Snk[i].x=checkx;Snk[i].y=checky;checkx=s;checky=t;}}void Food(){if(flag5){randomize();Fd.x=random(440);Fd.x=Fd.x-Fd.x%20+30;Fd.y=random(440);Fd.y=Fd.y-Fd.y%20+30;Fd.color=random(14)+1;flag5=0;}Dsnkorfd(Fd.x,Fd.y,Fd.color);}void Snake_Bodyadd(){if(Snk[0].x==Fd.x&&Snk[0].y==Fd.y) {if(Snk[num-1].x>Snk[num-2].x){num++;Snk[num-1].x=Snk[num-2].x+20;Snk[num-1].y=Snk[num-2].y;Snk[num-1].color=Fd.color;}elseif(Snk[num-1].x<Snk[num-2].x) {num++;Snk[num-1].x=Snk[num-2].x-20; Snk[num-1].y=Snk[num-2].y; Snk[num-1].color=Fd.color;}elseif(Snk[num-1].y>Snk[num-2].y) {num++;Snk[num-1].x=Snk[num-2].x; Snk[num-1].y=Snk[num-2].y+20; Snk[num-1].color=Fd.color;}elseif(Snk[num-1].y<Snk[num-2].y) {num++;Snk[num-1].x=Snk[num-2].x; Snk[num-1].y=Snk[num-2].y-20; Snk[num-1].color=Fd.color;}flag5=1;Score++;}}void PrntScore(){if(Hscore!=Score){setcolor(11);settextstyle(0,0,3); outtextxy(490,100,"SCORE"); setcolor(2);setfillstyle(1,0);rectangle(520,140,580,180); floodfill(530,145,2);Sco[0]=(char)(Score+48);Sco[1]='\0';Hscore=Score;setcolor(4);settextstyle(0,0,3); outtextxy(540,150,Sco);}}void Timer(){if(TimerCounter>18){Time[4]=(char)(Time[4]-1);if(Time[4]<'0'){Time[4]='9';Time[3]=(char)(Time[3]-1);}if(Time[3]<'0'){Time[3]='5';Time[1]=(char)(Time[1]-1);}if(TureorFalse){setcolor(11);settextstyle(0,0,3);outtextxy(490,240,"TIMER");setcolor(2);setfillstyle(1,0);rectangle(490,280,610,320);floodfill(530,300,2);setcolor(11);settextstyle(0,0,3);outtextxy(495,290,Time);TureorFalse=0;}if(Time[1]=='0'&&Time[3]=='0'&&Time[4]=='0') {setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}else if(key==ESC) cleardevice();else goto loop;}TimerCounter=0;TureorFalse=1;}}void Win(){if(Score==3)Times++;if(Times==2){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"You Win");loop:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();key=0;}else if(key==ESC) cleardevice();else goto loop;}}void TheSecondBlock(){if(Score==3){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(100,220,"The Second Block"); loop:key=bioskey(0);if(key==Enter){cleardevice();Initsnake();Initfood();Score=0;Hscore=1;Snkspeed=8;num=2;key=0;}else if(key==ESC) cleardevice();else goto loop;}}void Dsnkorfd(int x,int y,int color) {setcolor(color);setfillstyle(1,color);circle(x,y,10);floodfill(x,y,color);}void Delay(int times){int i;for(i=1;i<=times;i++)delay(15000);}。

C语言贪吃蛇全部程序及说明Word版

C语言贪吃蛇全部程序及说明Word版

#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("你的得分:%d\n",sum=10*(sum-1));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 ] = '@';elseif(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(); //食物吃完了马上再产生一个食物}elseover = 1;}。

c语言贪吃蛇源码

c语言贪吃蛇源码

#include <stdio.h>#include <Windows.h>#include <conio.h>#include <time.h>#define MAX_WIDE 50 //宽#define MAX_HIGH 16 //高short randxy, score = 0; //score是所得分数static int dx = 1,dy = 0;int SLEEP;COORD coord;/*一、如果用户定义了COORD coord,那么coord其实是一个结构体变量,其中X和Y是它的成员,通过修改coord.X和coord.Y的值就可以实现光标的位置控制。

二、计算的时候按位计算,&两边操作数对应位上全为1时,结果的该位值为1。

否则该位值为0三、举例:short int a=8;a=a>>1;1.a=0 000 10002.右移一位后:a= 0 000 1003.补0:a=0 000 01004.化为十进制数:a=4*/struct Snake{short len;short body[MAX_WIDE*MAX_HIGH];}snake; //蛇的结构体/*********************测试函数********************/void test1(){coord.X = 0;coord.Y = 0;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);putchar(getch());return;}void test2(){printf("(%d,%d)",dx,dy);}/***********************在制定位置设置出现****************************/void draw(){//画出蛇的身体for(short i = 0; i < snake.len; i++){coord.X = snake.body[i] & 127; //127二进制为:00000000 11111111coord.Y = snake.body[i] >> 8; // X等于body的低8位,Y等于body的高8位SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); //设置控制台光标位置,使光标到(x,y)putchar('*');}//画出最新点coord.X = randxy & 127;coord.Y = randxy >> 8;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);putchar('*');}/***********************控制snake函数********************/void run(){char key;short i, j;//snake.body[0]蛇头位置,while()条件指的是蛇在制定区域内,区域大小:MAX_WIDE*MAX_HIGHwhile( snake.body[0] > 0 && ( (snake.body[0] & 127) < MAX_WIDE) && (snake.body[0]>>8 < MAX_HIGH) ){for(;kbhit();) key = getch(); // kbhit()检查当前是否有键盘输入,若有则返回一个非0值,否则返回0switch(key){case 'w': dx = 0, dy = -1; break;case 's': dx = 0, dy = 1; break;case 'a': dx = -1, dy = 0; break;case 'd': dx = 1, dy = 0; break;}for(j = 1; j < snake.len; j++) // 蛇撞到自己会结束退出if(snake.body[j] == snake.body[0])return;if(randxy == snake.body[0]) //蛇吃到最新点的变动{snake.len++, score += 10;randxy = ((rand() % 16 + 0) <<8) | (rand() % 50 + 0); //原来的点被吃掉后产生新的点//rand()函数是产生随机数的一个随机函数//“|”按位或运算,在这里是指把(rand() % 16 + 0)这个八位二进制数向左移动8位,//尾部拼接上(rand() % 50 + 0)形成一个16位二进制数赋值给randxy }for(i = snake.len-1; i > 0; i--) //移动前准备,前一项赋值给后一项snake.body[i] = snake.body[i-1];//移动蛇身snake.body[0] = ((snake.body[0] & 127) + dx) | ((snake.body[0] >>8) + dy)<<8;draw();Sleep(SLEEP);system("cls");}}int main(){int level;again:snake.body[MAX_WIDE*MAX_HIGH] = 0;snake.body[0] = (MAX_HIGH/2)<<8 | MAX_WIDE/2;snake.len = 1;srand((unsigned)time(NULL)); //把系统时间作为种子,初始化// srand()它需要提供一个种子,这个种子会对应一个随机数,如果使用相同的种子后面的rand()函数会出现一样的随机数。

C语言项目案例之贪吃蛇

C语言项目案例之贪吃蛇

C语⾔项⽬案例之贪吃蛇项⽬案例:贪吃蛇下载链接:1. 初始化墙代码:// 初始化墙void init_wall(void){for (size_t y = 0; y <= HIGH; ++y){for (size_t x = 0; x <= WIDE; ++x){if (x == WIDE || y == HIGH) // 判断是否到墙{printf("=");}else{printf(" ");}}printf("\n");}}效果:2. 定义蛇和⾷物类型typedef struct{int x;int y;}FOOD; // ⾷物typedef struct{int x;int y;}BODY; // ⾝体typedef struct{int size; // ⾝体长度BODY body[WIDE*HIGH];}SNAKE; // 蛇3. 初始化蛇和⾷物// 定义⼀个蛇和⾷物SNAKE snake;FOOD food;// 初始化⾷物void init_food(void){food.x = rand() % WIDE; // 随机⽣成坐标food.y = rand() % HIGH;}// 初始化蛇void init_snake(void){snake.size = 2;// 将蛇头初始化到墙中间snake.body[0].x = WIDE / 2;snake.body[0].y = HIGH / 2;// 蛇⾝紧跟蛇头snake.body[1].x = WIDE / 2 - 1;snake.body[1].y = HIGH / 2;}4. 显⽰UI// 显⽰UIvoid showUI(void){// 显⽰⾷物// 存放光标位置COORD coord;coord.X = food.x;coord.Y = food.y;// 光标定位SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); putchar('$');// 显⽰蛇for (size_t i = 0; i < snake.size; ++i){// 设置光标coord.X = snake.body[i].x;coord.Y = snake.body[i].y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); if (i == 0)}else{putchar('#');}}}效果:最终代码// main.c#define _CRT_SECURE_NO_WARNINGS#include "./snakeGame.h"int main(void){// 取消光标CONSOLE_CURSOR_INFO cci;cci.bVisible = FALSE; // 取消光标cci.dwSize = sizeof(cci);SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cci); system("color 2");printf("欢迎来到贪吃蛇\n准备好了吗?按s/S开始,q/Q退出\n"); char ch = _getch();switch (ch){case 's':case 'S':system("color 0");system("cls");break;default:return 0;}init_wall();init_food();init_snake();showUI();playGame();return 0;}// snakeGame.c#include "./snakeGame.h"// 定义⼀个蛇和⾷物SNAKE snake;FOOD food;// ⽅向增量int dx = 0;int dy = 0;int lx, ly; // 尾节点// 初始化⾷物void init_food(void){food.x = rand() % WIDE; // 随机⽣成坐标food.y = rand() % HIGH;}// 初始化蛇void init_snake(void){snake.size = 2;snake.fraction = 0;// 将蛇头初始化到墙中间snake.body[0].x = WIDE / 2;snake.body[0].y = HIGH / 2;snake.body[1].x = WIDE / 2 - 1;snake.body[1].y = HIGH / 2;}// 初始化墙void init_wall(void){for (size_t y = 0; y <= HIGH; ++y){for (size_t x = 0; x <= WIDE; ++x){if (x == WIDE || y == HIGH) // 判断是否到墙{printf("=");}else{printf(" ");}}printf("\n");}printf("分数:0\n");}// 显⽰UIvoid showUI(void){// 显⽰⾷物// 存放光标位置COORD coord;coord.X = food.x;coord.Y = food.y;// 光标定位SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);putchar('$');// 显⽰蛇for (size_t i = 0; i < snake.size; ++i){// 设置光标coord.X = snake.body[i].x;coord.Y = snake.body[i].y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);if (i == 0){putchar('@');}else{putchar('#');}}// 处理尾节点coord.X = lx;coord.Y = ly;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);putchar(' ');coord.X = WIDE;coord.Y = HIGH;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);printf("\n分数:%d\n",snake.fraction);}void playGame(void){COORD _coord;system("color 7");char key = 'D';// 蛇不能撞墙while (snake.body[0].x >= 0 && snake.body[0].x <= WIDE && snake.body[0].y >= 0 && snake.body[0].y <= HIGH) {// 蛇不能撞⾃⼰for (size_t i = 1; i < snake.size; ++i){if (snake.body[0].x == snake.body[i].x && snake.body[0].y == snake.body[i].y){goto OVER;}}// 撞⾷物if (snake.body[0].x == food.x && snake.body[0].y == food.y){++snake.size;++snake.fraction;// 随机出现⾷物init_food();}// 控制蛇移动// 判断是否按下按键if (_kbhit()){key = _getch(); // 不需要敲回车,按下就⽴马确认}// 判断W A S D中哪个按键按下switch (key){case 'w':case 'W':dx = 0;dy = -1;break;case 'a':case 'A':dx = -1;dy = 0;break;case 's':case 'S':dx = 0;dy = 1;break;case 'd':dx = 1;dy = 0;break;case 'q':case 'Q':_coord.X = WIDE;_coord.Y = HIGH;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), _coord); putchar('\n');return;}// 蛇移动// 记录尾节点位置lx = snake.body[snake.size - 1].x;ly = snake.body[snake.size - 1].y;for (size_t i = snake.size - 1; i > 0; --i){snake.body[i].x = snake.body[i - 1].x;snake.body[i].y = snake.body[i - 1].y;}// 更新蛇头snake.body[0].x += dx;snake.body[0].y += dy;showUI();Sleep(500); // 延时}// 游戏结束OVER:system("color 4");_coord.X = 6;_coord.Y = HIGH + 1;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), _coord); printf("\n游戏结束");printf("按r/R重新开始,按q/Q退出\n");char _key;_key = _getch();switch (_key){case 'r':case 'R':system("cls");init_wall();init_food();init_snake();showUI();playGame();case 'Q':case 'q':default:system("color 7");return;}}// snakeGame.h#pragma once#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <Windows.h>#define WIDE 60 // 长#define HIGH 20 // ⾼typedef struct{int x;int y;}FOOD; // ⾷物typedef struct{int x;int y;}BODY; // ⾝体typedef struct{int size; // ⾝体长度int fraction; // 分数BODY body[WIDE*HIGH];}SNAKE; // 蛇void init_wall(void);void init_food(void);void init_snake(void);void showUI(void);void playGame(void);。

贪吃蛇的c语言源程序

贪吃蛇的c语言源程序

#include<stdio.h>#include<graphics.h>#include<stdlib.h>#include<dos.h>#include<bios.h>#include<time.h>#define NULL 0#define UP 4471#define LEFT 7777#define DOWN 8051#define RIGHT 8292#define PAUSE 6512#define ESC 283#define SNAKE_COLOR 4#define SNAKE_BOND_COLOR 2#define SNAKE_STYLE LTBKSLASH_FILL #define FOOD_STYLE CLOSE_DOT_FILL #define MAP_COLOR 8#define MAP_BOND_COLOR 6#define MAP_STYLE SOLID_FILLtypedef struct Snake_Node{int x,y;struct Snake_Node *next;}Snake_Node,*P_Snake_Node;struct{int x,y,color;}Food;struct{int dx;int dy;}Direct={0,1};static int speed=1,len=4,px,py;static P_Snake_Node Head;static P_Snake_Node Map;void paint_node(int,int,int,int,int);void Put_Food(int);void Put_Snake_Node(P_Snake_Node,int); void Init();void Grow_up(int,int);void Make_Map();void Auto_Make_Map();void Load_Game();void Auto_Start();int Snake_Dead();void GO_GO_GO();void Play_Game();void Exit_Save();void Failed();void main();void paint_node(int x,int y,int color1,int color2,int style){setfillstyle(SOLID_FILL,color2);bar(x*10,479-y*10,x*10+9,479-y*10-9);setfillstyle(style,color1);bar(x*10+1,479-y*10-1,x*10+9-1,479-y*10-9+1);setfillstyle(SOLID_FILL,15);}void Put_Food(int color){randomize();Food.x=random(46)+1;Food.y=random(46)+1;Food.color=color;paint_node(Food.x,Food.y,Food.color,Food.color,FOOD_STYLE);}void Put_Snake_Node(P_Snake_Node p,int flag){if(flag)paint_node(p->x,p->y,SNAKE_COLOR,SNAKE_BOND_COLOR,SNAKE_STYLE);elsepaint_node(p->x,p->y,getbkcolor(),getbkcolor(),SOLID_FILL);}void Init(){int gdrive=VGA,gmode=VGAHI;initgraph(&gdrive,&gmode,"d:\\TC20\\turboc2");setfillstyle(XHATCH_FILL,2);bar(490,0,509,479);setfillstyle(SOLID_FILL,6);bar(480,0,489,479);setfillstyle(SOLID_FILL,15);setcolor(9);setlinestyle(CENTER_LINE,0,3);line(490,0,490,479);setcolor(3);setlinestyle(SOLID_LINE,0,3);line(509,0,509,479);line(509,479,639,479);line(639,479,639,0);line(639,0,509,0);setlinestyle(SOLID_LINE,0,0);setcolor(10);settextstyle(TRIPLEX_FONT,HORIZ_DIR,3); outtextxy(530,12,"GREEDY");outtextxy(537,40,"SNAKE");settextstyle(0,0,0);setcolor(13);outtextxy(510,80,"<<============>>"); setcolor(1);setlinestyle(CENTER_LINE,0,3);line(573,90,573,305);outtextxy(510,310,"+++++++++++++++++"); setcolor(5);settextstyle(GOTHIC_FONT,0,5);outtextxy(512,390,"~~~~~~~");outtextxy(512,392,"~~~~~~~");outtextxy(512,388,"~~~~~~~");setcolor(10);settextstyle(SANS_SERIF_FONT,1,1); outtextxy(510,115,"->");outtextxy(510,165,"<-");settextstyle(SANS_SERIF_FONT,0,1); outtextxy(512,215,"->");outtextxy(512,265,"<-");setcolor(14);settextstyle(DEFAULT_FONT,0,1); outtextxy(550,128,":W");outtextxy(550,175,":S");outtextxy(550,222,":A");outtextxy(550,272,":D");setcolor(10);settextstyle(SMALL_FONT,0,5);outtextxy(575,125,"PAUSE /");outtextxy(575,140,"CONTINUE:");outtextxy(580,250,"EXIT:");/*************/}void Grow_Up(int x,int y){P_Snake_Node p;p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=x;p->y=y;p->next=Head->next;Head->next=p;Head=p;++len;++speed;}void Auto_Make_Map(){P_Snake_Node p,q;p=q=Map=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=0;p->y=0;p->next=NULL;while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=(q->x)+1;p->y=q->y;q->next=p;p->next=NULL;q=p;if((p->x)==47) break;}while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=q->x;p->y=(q->y)+1;q->next=p;p->next=NULL;q=p;if((p->y)==47) break;}while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=(q->x)-1;p->y=q->y;q->next=p;p->next=NULL;q=p;if((p->x)==0) break;}while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=q->x;p->y=(q->y)-1;q->next=p;p->next=NULL;q=p;if((p->y)==1) break;}p=Map;while(p){paint_node(p->x,p->y,MAP_COLOR,MAP_BOND_COLOR,MAP_STYLE);p=p->next;}}void Auto_Start(){int i=1;P_Snake_Node p,q;Head=p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=24;p->y=24-3;p->next=NULL;q=p;while(i<=3){q=(P_Snake_Node)malloc(sizeof(Snake_Node));p->next=q;q->x=p->x;q->y=(p->y)+1;q->next=NULL;p=q;++i;}p->next=Head;Head=p;while(i>=1){Put_Snake_Node(p,1);p=p->next;i--;}Put_Food(14);Auto_Make_Map();}int Snake_Dead(){P_Snake_Node p;int i=1;p=Head->next->next;while(i<=len-4){if(p->x==px && p->y==py)return(1);++i;p=p->next;}p=Map;while(p){if(p->x==px && p->y==py)return(1);p=p->next;}return(0);}void GO_GO_GO(){px=(Head->x)+(Direct.dx);py=(Head->y)+(Direct.dy);if(!Snake_Dead()){if(px==Food.x&&py==Food.y){Grow_Up(px,py);Put_Snake_Node(Head,1);Put_Food(14);}else{Head=Head->next;Put_Snake_Node(Head,0);Head->x=px;Head->y=py;Put_Snake_Node(Head,1);}}elseFailed();}void Play_Game(){int wait;while(1){while(!kbhit()){GO_GO_GO();wait=0;while(wait<=2){delay(30000);++wait;}}switch(bioskey(0)){case UP:{if(Direct.dx!=0&&Direct.dy!=-1){Direct.dx=0;Direct.dy=1;}break;}case LEFT:{if(Direct.dx!=1&&Direct.dy!=0){Direct.dx=-1;Direct.dy=0;}break;}case DOWN:{if(Direct.dx!=0&&Direct.dy!=1){Direct.dx=0;Direct.dy=-1;}break;}case RIGHT:{if(Direct.dx!=-1&&Direct.dy!=0){Direct.dx=1;Direct.dy=0;}break;}case ESC:{exit(1);break;}}}}void Failed(){setcolor(4);settextstyle(TRIPLEX_FONT, HORIZ_DIR, 6);outtextxy(90,200,"GAME OVER!");getch();exit(1);/**********/ }void main(){Init();getch();Auto_Start();Play_Game();getch(); closegraph();}。

(完整word版)C语言最简洁的贪吃蛇源代码

(完整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语言代码

贪吃蛇c语言代码#include <graphics.h>#include <conio.h>#include <stdlib.h>#include <dos.h>#define NULL 0#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181struct snake{int centerx;int centery;int newx;int newy;struct snake *next;};struct snake *head;int grade=60; /*控制速度的*******/int a,b; /* 背静遮的位置*/void *far1,*far2,*far3,*far4; /* 蛇身指针背静遮的指针虫子*/ int size1,size2,size3,size4; /* **全局变量**/int ch=RIGHT; /**************存按键开始蛇的方向为RIGHT***********/int chy=RIGHT;int flag=0; /*********判断是否退出游戏**************/int control=4; /***********判断上次方向和下次方向不冲突***/int nextshow=1; /*******控制下次蛇身是否显示***************/int scenterx; /***************随即矩形中心坐标***************/int scentery;int sx; /*******在a b 未改变前得到他们的值保证随机矩形也不在此出现*******/int sy;/************************蛇身初始化**************************/void snakede(){struct snake *p1,*p2;head=p1=p2=(struct snake *)malloc(sizeof(struct snake));p1->centerx=80;p1->newx=80;p1->centery=58;p1->newy=58;p1=(struct snake *)malloc(sizeof(struct snake));p2->next=p1;p1->centerx=58;p1->newx=58;p1->centery=58;p1->newy=58;p1->next=NULL;}/*******************end*******************/void welcome() /*************游戏开始界面,可以选择速度**********/ {int key;int size;int x=240;int y=300;int f;void *buf;setfillstyle(SOLID_FILL,BLUE);bar(98,100,112,125);setfillstyle(SOLID_FILL,RED);bar(98,112,112,114);setfillstyle(SOLID_FILL,GREEN);bar(100,100,110,125);size=imagesize(98,100,112,125);buf=malloc(size);getimage(98,100,112,125,buf);cleardevice();setfillstyle(SOLID_FILL,BLUE);bar(240,300,390,325);outtextxy(193,310,"speed:");setfillstyle(SOLID_FILL,RED);bar(240,312,390,314);setcolor(YELLOW);outtextxy(240,330,"DOWN");outtextxy(390,330,"UP");outtextxy(240,360,"ENTER to start..." );outtextxy(270,200,"SNAKE");fei(220,220);feiyang(280,220);yang(340,220);putimage(x,y,buf,COPY_PUT);setcolor(RED);rectangle(170,190,410,410);while(1){ if(bioskey(1)) /********8选择速度部分************/ key=bioskey(0);switch(key){case ENTER:f=1;break;case DOWN:if(x>=240){ putimage(x-=2,y,buf,COPY_PUT);grade++;key=0;break;}case UP:if(x<=375){ putimage(x+=2,y,buf,COPY_PUT);grade--;key=0;break;}}if (f==1)break;} /********** end ****************/free(buf);}/*************************随即矩形*****************//***********当nextshow 为1的时候才调用此函数**********/void ran(){ int nx;int ny;int show; /**********控制是否显示***********/int jump=0;struct snake *p;p=head;if(nextshow==1) /***********是否开始随机产生***************/while(1){show=1;randomize();nx=random(14);ny=random(14);scenterx=nx*22+58;scentery=ny*22+58;while(p!=NULL){if(scenterx==p->centerx&&scentery==p->centery||scenterx==sx&&scentery==sy) {show=0;jump=1;break;}elsep=p->next;if(jump==1)break;}if(show==1){putimage(scenterx-11,scentery-11,far3,COPY_PUT); nextshow=0;break;}}}/***********过关动画**************/void donghua(){ int i;cleardevice();setbkcolor(BLACK);randomize();while(1){for(i=0;i<=5;i++){putpixel(random(640),random(80),13);putpixel(random(640),random(80)+80,2); putpixel(random(640),random(80)+160,3); putpixel(random(640),random(80)+240,4); putpixel(random(640),random(80)+320,1); putpixel(random(640),random(80)+400,14);}setcolor(YELLOW);settextstyle(0,0,4);outtextxy(130,200,"Wonderful!!");setfillstyle(SOLID_FILL,10);bar(240,398,375,420);feiyang(300,400);fei(250,400);yang(350,400);if(bioskey(1))if(bioskey(0)==ESC){flag=1;break;}}}/*************************end************************//***********************初始化图形系统*********************/ void init(){int a=DETECT,b;int i,j;initgraph(&a,&b,"");}/***************************end****************************//***画立体边框效果函数******/void tline(int x1,int y1,int x2,int y2,int white,int black){ setcolor(white);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(black);line(x2,y1,x2,y2);line(x1,y2,x2,y2);}/****end*********//*************标志**********/int feiyang(int x,int y){int feiyang[18][18]={ {0,0,0,0,0,0,1,1,1,1,1,1,0,1,1,0,0,0},{0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0},{0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0},{0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0},{0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,0,0},{0,0,1,1,1,0,0,0,0,1,0,1,1,1,0,0,0,0},{0,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,0,0},{0,0,0,1,1,1,0,1,1,1,1,1,0,0,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0},{0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (feiyang[i][j]==1)putpixel(j+x,i+y,RED);}}/********"飞"字*************/int fei(int x,int y){int fei[18][18]={{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (fei[i][j]==1)putpixel(j+x,i+y,BLUE);}}/*********"洋"字**************/int yang(int x,int y){int yang[18][18]={{0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, {1,1,0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0},{0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,1,0,0}, {0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0}, {0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0}, {1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}, {0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0}, {0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,0}, {0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0}, {0,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0}, {0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0}, {0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0}, {1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0}, {0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0}, {0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}, {0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}}; int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (yang[i][j]==1)putpixel(j+x,i+y,BLUE);}}/******************主场景**********************/int bort(){ int a;setfillstyle(SOLID_FILL,15);bar(49,49,71,71);setfillstyle(SOLID_FILL,BLUE);bar(50,50,70,70);size1=imagesize(49,49,71,71);far1=(void *)malloc(size1);getimage(49,49,71,71,far1);cleardevice();setfillstyle(SOLID_FILL,12);bar(49,49,71,71);size2=imagesize(49,49,71,71);far2=(void *)malloc(size2);getimage(49,49,71,71,far2);setfillstyle(SOLID_FILL,12);bar(49,49,71,71);setfillstyle(SOLID_FILL,GREEN);bar(50,50,70,70);size3=imagesize(49,49,71,71);far3=(void *)malloc(size3);getimage(49,49,71,71,far3);cleardevice(); /*取蛇身节点背景节点虫子节点end*/ setbkcolor(8);setfillstyle(SOLID_FILL,GREEN);bar(21,23,600,450);tline(21,23,600,450,15,8); /***开始游戏场景边框立体效果*******/ tline(23,25,598,448,15,8);tline(45,45,379,379,8,15);tline(43,43,381,381,8,15);tline(390,43,580,430,8,15);tline(392,45,578,428,8,15);tline(412,65,462,85,15,8);tline(410,63,464,87,15,8);tline(410,92,555,390,15,8);tline(412,94,553,388,15,8);tline(431,397,540,420,15,8);tline(429,395,542,422,15,8);tline(46,386,377,428,8,15);tline(44,384,379,430,8,15);setcolor(8);outtextxy(429,109,"press ENTER ");outtextxy(429,129,"---to start"); /*键盘控制说明*/outtextxy(429,169,"press ESC ");outtextxy(429,189,"---to quiet");outtextxy(469,249,"UP");outtextxy(429,289,"LEFT");outtextxy(465,329,"DOWN");outtextxy(509,289,"RIGHT");setcolor(15);outtextxy(425,105,"press ENTER ");outtextxy(425,125,"---to start");outtextxy(425,165,"press ESC ");outtextxy(425,185,"---to quiet");outtextxy(465,245,"UP");outtextxy(425,285,"LEFT");outtextxy(461,325,"DOWN");outtextxy(505,285,"RIGHT"); /*******end*************/setcolor(8);outtextxy(411,52,"score");outtextxy(514,52,"left");setcolor(15);outtextxy(407,48,"score");outtextxy(510,48,"left");size4=imagesize(409,62,465,88); /****分数框放到存********/far4=(void *)malloc(size4);getimage(409,62,465,88,far4);putimage(500,62,far4,COPY_PUT); /*******输出生命框***********/setfillstyle(SOLID_FILL,12);setcolor(RED);outtextxy(415,70,"0"); /***************输入分数为零**********/outtextxy(512,70,"20"); /*************显示还要吃的虫子的数目*********/bar(46,46,378,378);feiyang(475,400);fei(450,400);yang(500,400);outtextxy(58,390,"mailto:jiangzhiliang002tom."); outtextxy(58,410,"snake game");outtextxy(200,410,"made by yefeng");while(1){ if(bioskey(1))a=bioskey(0);if(a==ENTER)break;}}/******************gameover()******************/void gameover(){ char *p="GAME OVER";int cha;setcolor(YELLOW);settextstyle(0,0,6);outtextxy(100,200,p);while(1){if(bioskey(1))cha=bioskey(0);if(cha==ESC){flag=1;break;}}}/***********显示蛇身**********************/void snakepaint(){struct snake *p1;p1=head;putimage(a-11,b-11,far2,COPY_PUT);while(p1!=NULL){putimage(p1->newx-11,p1->newy-11,far1,COPY_PUT);p1=p1->next;}}/****************end**********************//*********************蛇身刷新变化游戏关键部分*******************/ void snakechange(){struct snake *p1,*p2,*p3,*p4,*p5;int i,j;static int n=0;static int score;static int left=20;char sscore[5];char sleft[1];p2=p1=head;while(p1!=NULL){ p1=p1->next;if(p1->next==NULL){a=p1->newx;b=p1->newy; /************记录最后节点的坐标************/ sx=a;sy=b;}p1->newx=p2->centerx;p1->newy=p2->centery;p2=p1;}p1=head;while(p1!=NULL){p1->centerx=p1->newx;p1->centery=p1->newy;p1=p1->next;}/********判断按键方向*******/if(bioskey(1)){ ch=bioskey(0);if(ch!=RIGHT&&ch!=LEFT&&ch!=UP&&ch!=DOWN&&ch!=ESC) /********chy为上一次的方向*********/ch=chy;}switch(ch){case LEFT: if(control!=4){head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}else{ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}chy=ch;break;case DOWN:if(control!=1){ head->newy=head->newy+22;head->centery=head->newy; control=3;if(head->newy>377)gameover();}else{ head->newy=head->newy-22; head->centery=head->newy;control=1;if(head->newy<47)gameover();}chy=ch;break;case RIGHT: if(control!=2){ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}else{ head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}chy=ch;break;case UP: if(control!=3){ head->newy=head->newy-22;head->centery=head->newy;control=1;if(head->newy<47)gameover();}else{ head->newy=head->newy+22;head->centery=head->newy;control=3;if(head->newy>377)gameover();}chy=ch;break;case ESC:flag=1;break;}/* if 判断是否吃蛇*/if(flag!=1){ if(head->newx==scenterx&&head->newy==scentery) { p3=head;while(p3!=NULL){ p4=p3;p3=p3->next;}p3=(struct snake *)malloc(sizeof(struct snake));p4->next=p3;p3->centerx=a;p3->newx=a;p3->centery=b;p3->newy=b;p3->next=NULL;a=500;b=500;putimage(409,62,far4,COPY_PUT); /********** 分数框挡住**************/ putimage(500,62,far4,COPY_PUT); /*********把以前的剩下虫子的框挡住********/ score=(++n)*100;left--;itoa(score,sscore,10);itoa(left,sleft,10);setcolor(RED);outtextxy(415,70,sscore);outtextxy(512,70,sleft);nextshow=1;if(left==0) /************判断是否过关**********/donghua(); /*******如果过关,播放过关动画*********************/ }p5=head; /*********************判断是否自杀***************************/ p5=p5->next;p5=p5->next;p5=p5->next;p5=p5->next; /****从第五个节点判断是否自杀************/while(p5!=NULL){if(head->newx==p5->centerx&&head->newy==p5->centery){ gameover();break;}elsep5=p5->next;}}}/************snakechange()函数结束*******************//*****************************主函数******************************************/ int main(){ int i;init(); /**********初始化图形系统**********/welcome(); /*********8欢迎界面**************/bort(); /*********主场景***************/snakede(); /**********连表初始化**********/while(1){ snakechange();if(flag==1)break;snakepaint();ran();for(i=0;i<=grade;i++)delay(3000);}free(far1); free(far2); free(far3); free(far4); closegraph(); return 0;}。

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

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

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

程序可在VS2013下编译运行。

1 #include<stdio.h>2 #include<time.h>3 #include<windows.h>4 #include<stdlib.h>56#define U 17#define D 28#define L 39#define R 4 //蛇的状态,U:上;D:下;L:左 R:右1011 typedef struct SNAKE //蛇身的一个节点12 {13int x;14int y;15struct SNAKE *next;16 }snake;1718//全局变量//19int score = 0, add = 10;//总得分与每次吃食物得分。

20int status, sleeptime = 200;//每次运行的时间间隔21 snake *head, *food;//蛇头指针,食物指针22 snake *q;//遍历蛇的时候用到的指针23int endGamestatus = 0; //游戏结束的情况,1:撞到墙;2:咬到自己;3:主动退出游戏。

2425//声明全部函数//26void Pos();27void creatMap();28void initSnake();29int biteSelf();30void createFood();31void cantCrossWall();32void snakeMove();33void pause();34void runGame();35void initGame();36void endGame();37void gameStart();3839void 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 }4849void creatMap()//创建地图50 {51int i;52for (i = 0; i<58; i += 2)//打印上下边框53 {54 Pos(i, 0);55 printf("■");//一个方块占两个位置56 Pos(i, 26);57 printf("■");58 }59for (i = 1; i<26; i++)//打印左右边框60 {61 Pos(0, i);62 printf("■");63 Pos(56, i);64 printf("■");65 }66 }6768void initSnake()//初始化蛇身69 {70 snake *tail;71int i;72 tail = (snake*)malloc(sizeof(snake));//从蛇尾开始,头插法,以x,y设定开始的位置//73 tail->x = 24;74 tail->y = 5;75 tail->next = NULL;76for (i = 1; i <= 4; i++)//初始长度为477 {78 head = (snake*)malloc(sizeof(snake));79 head->next = tail;80 head->x = 24 + 2 * i;81 head->y = 5;82 tail = head;83 }84while (tail != NULL)//从头到为,输出蛇身85 {86 Pos(tail->x, tail->y);87 printf("■");88 tail = tail->next;89 }90 }91//??92int biteSelf()//判断是否咬到了自己93 {94 snake *self;95 self = head->next;96while (self != NULL)97 {98if (self->x == head->x && self->y == head->y)99 {100return1;101 }102 self = self->next;103 }104return0;105 }106107void createFood()//随机出现食物108 {109 snake *food_1;110 srand((unsigned)time(NULL));//为了防止每次产生的随机数相同,种子设置为time111 food_1 = (snake*)malloc(sizeof(snake));112while ((food_1->x % 2) != 0) //保证其为偶数,使得食物能与蛇头对其113 {114 food_1->x = rand() % 52 + 2;115 }116 food_1->y = rand() % 24 + 1;117 q = head;118while (q->next == NULL)119 {120if (q->x == food_1->x && q->y == food_1->y) //判断蛇身是否与食物重合121 {122free(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 }131132void cantCrossWall()//不能穿墙133 {134if (head->x == 0 || head->x == 56 || head->y == 0 || head->y == 26)135 {136 endGamestatus = 1;137 endGame();138 }139 }140141void snakeMove()//蛇前进,上U,下D,左L,右R142 {143 snake * nexthead;144 cantCrossWall();145146 nexthead = (snake*)malloc(sizeof(snake));147if (status == U)148 {149 nexthead->x = head->x;150 nexthead->y = head->y - 1;151if (nexthead->x == food->x && nexthead->y == food->y)//如果下一个有食物//152 {153 nexthead->next = head;154 head = nexthead;155 q = head;156while (q != NULL)157 {158 Pos(q->x, q->y);159 printf("■");160 q = q->next;161 }162 score = score + add;163 createFood();164 }165else//如果没有食物//166 {167 nexthead->next = head;168 head = nexthead;169 q = head;170while (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("");178free(q->next);179 q->next = NULL;180 }181 }182if (status == D)183 {184 nexthead->x = head->x;185 nexthead->y = head->y + 1;186if (nexthead->x == food->x && nexthead->y == food->y) //有食物187 {188 nexthead->next = head;189 head = nexthead;190 q = head;191while (q != NULL)192 {193 Pos(q->x, q->y);194 printf("■");195 q = q->next;196 }197 score = score + add;198 createFood();199 }200else//没有食物201 {202 nexthead->next = head;203 head = nexthead;204 q = head;205while (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("");213free(q->next);214 q->next = NULL;215 }216 }217if (status == L)218 {219 nexthead->x = head->x - 2;220 nexthead->y = head->y;221if (nexthead->x == food->x && nexthead->y == food->y)//有食物222 {223 nexthead->next = head;224 head = nexthead;225 q = head;226while (q != NULL)227 {228 Pos(q->x, q->y);229 printf("■");230 q = q->next;231 }232 score = score + add;233 createFood();234 }235else//没有食物236 {237 nexthead->next = head;238 head = nexthead;239 q = head;240while (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("");248free(q->next);249 q->next = NULL;250 }251 }252if (status == R)253 {254 nexthead->x = head->x + 2;255 nexthead->y = head->y;256if (nexthead->x == food->x && nexthead->y == food->y)//有食物257 {258 nexthead->next = head;259 head = nexthead;260 q = head;261while (q != NULL)262 {263 Pos(q->x, q->y);264 printf("■");265 q = q->next;266 }267 score = score + add;268 createFood();269 }270else//没有食物271 {272 nexthead->next = head;273 head = nexthead;274 q = head;275while (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("");283free(q->next);284 q->next = NULL;285 }286 }287if (biteSelf() == 1) //判断是否会咬到自己288 {289 endGamestatus = 2;290 endGame();291 }292 }293294void pause()//暂停295 {296while (1)297 {298 Sleep(300);299if (GetAsyncKeyState(VK_SPACE))300 {301break;302 }303304 }305 }306307void runGame()//控制游戏308 {309310 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;321while (1)322 {323 Pos(64, 10);324 printf("得分:%d ", score);325 Pos(64, 11);326 printf("每个食物得分:%d分", add);327if (GetAsyncKeyState(VK_UP) && status != D)328 {329 status = U;330 }331else if (GetAsyncKeyState(VK_DOWN) && status != U) 332 {333 status = D;334 }335else if (GetAsyncKeyState(VK_LEFT) && status != R) 336 {337 status = L;338 }339else if (GetAsyncKeyState(VK_RIGHT) && status != L) 340 {341 status = R;342 }343else if (GetAsyncKeyState(VK_SPACE))344 {345 pause();346 }347else if (GetAsyncKeyState(VK_ESCAPE))348 {349 endGamestatus = 3;350break;351 }352else if (GetAsyncKeyState(VK_F1))353 {354if (sleeptime >= 50)355 {356 sleeptime = sleeptime - 30;357 add = add + 2;358if (sleeptime == 320)359 {360 add = 2;//防止减到1之后再加回来有错361 }362 }363 }364else if (GetAsyncKeyState(VK_F2))365 {366if (sleeptime<350)367 {368 sleeptime = sleeptime + 30;369 add = add - 2;370if (sleeptime == 350)371 {372 add = 1; //保证最低分为1373 }374 }375 }376 Sleep(sleeptime);377 snakeMove();378 }379 }380381void initGame()//开始界面382 {383 Pos(40, 12);384385 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("加速将能得到更高的分数。

C语言实现贪吃蛇游戏(命令行)

C语言实现贪吃蛇游戏(命令行)

C语⾔实现贪吃蛇游戏(命令⾏)这是⼀个纯C语⾔写的贪吃蛇游戏,供⼤家参考,具体内容如下#include<stdio.h>#include<stdlib.h>#include<windows.h>#include<time.h>#include<conio.h>#define SNAKE_LENGTH 100//定义蛇的最⼤长度#define SCREEN_WIDETH 80#define SCREEN_HEIGHT 30//定义每⼀节蛇的坐标struct coor{int x;int y;};//枚举⽅向enum CH {right = VK_RIGHT,left = VK_LEFT,up = VK_UP,down = VK_DOWN};//定义蛇的属性struct snake{int len;//当前蛇的长度struct coor coord[SNAKE_LENGTH];//每⼀节蛇的坐标enum CH CH;//定义蛇的⽅向int SPEED;int flag;//定义蛇的状态 1表⽰存活 0表⽰死亡}snake;//光标移动函数void gotoxy(int x, int y){COORD pos;pos.X = x;pos.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);}//初始化游戏界⾯void init_sence(){//初始化上下墙for (int i = 0; i < SCREEN_WIDETH; i += 2){gotoxy(i,0);printf("■");gotoxy(i, SCREEN_HEIGHT);printf("■");}//初始化左右墙for (int i = 0; i <=SCREEN_HEIGHT; i++){gotoxy(0, i);printf("■");gotoxy(SCREEN_WIDETH,i);printf("■");}//打印提⽰信息gotoxy(SCREEN_WIDETH + 5, 2);printf("\t\t贪吃蛇");gotoxy(SCREEN_WIDETH + 5, 6);printf("2018//12//1");gotoxy(SCREEN_WIDETH + 5, 8);printf("作者:⼩⾖芽");gotoxy(SCREEN_WIDETH + 5, 10);printf("F1:加速\tF2:减速");gotoxy(SCREEN_WIDETH + 5, 12);printf("CTRL:继续\t空格:暂停");gotoxy(SCREEN_WIDETH + 5, 14);printf("ESC:退出游戏");gotoxy(SCREEN_WIDETH + 5, 28);printf("建议:QQ:2862841130:::");}struct foodcoord {int x;int y;int flag;//定义⾷物的状态}food;//**这是c程序**#include"snake.h"//蛇的移动void move_snake();//画出蛇void draw_snake();//产⽣⾷物void creatfood();//判断蛇是否吃到⾷物void eatfood();//判断蛇是否死掉void SnakeState();int main(){//设置窗⼝⼤⼩system("mode con cols=110 lines=31");//设置标题SetConsoleTitleA("贪吃蛇");//初始化蛇begin:snake.CH = VK_RIGHT;//初始化⽅向snake.len = 5; //初始化长度snake.SPEED = 300;//初始化蛇的移动速度snake.coord[1].x = SCREEN_WIDETH / 2;//初始化蛇头的坐标 snake.coord[1].y = SCREEN_HEIGHT / 2;snake.coord[2].x = SCREEN_WIDETH / 2-2;//初始化蛇头的坐标 snake.coord[2].y = SCREEN_HEIGHT / 2;snake.coord[3].x = SCREEN_WIDETH / 2-4;//初始化蛇头的坐标 snake.coord[3].y = SCREEN_HEIGHT / 2;//初始化⾷物状态food.flag = 1;//1表⽰吃到⾷物 0表⽰没有吃到⾷物//初始化⾷物状态snake.flag = 1;//1活 0死init_sence();//初始化游戏界⾯while (1){draw_snake();//画蛇Sleep(snake.SPEED);//蛇的移动速度move_snake();//移动蛇if(food.flag)creatfood();//产⽣⾷物eatfood();//判断是否吃到⾷物SnakeState();//判断蛇是否死亡if (!snake.flag)break;}system("cls");gotoxy(SCREEN_WIDETH/2, SCREEN_HEIGHT/2-4);printf(" GAME OVER");gotoxy(SCREEN_WIDETH / 2-6, SCREEN_HEIGHT / 2+2);printf("你的得分是:\t\t\t%d ",snake.len-1);gotoxy(SCREEN_WIDETH / 2-6, SCREEN_HEIGHT / 2+4);printf("我不服再来:\t\t\tCTRL ");gotoxy(SCREEN_WIDETH / 2-6, SCREEN_HEIGHT / 2+6);printf("算了垃圾游戏毁我青春:\t\tESC");while (1){if (GetAsyncKeyState(VK_CONTROL)){system("cls");goto begin;}else if (GetAsyncKeyState(VK_ESCAPE))return 0;}}//蛇的移动void move_snake(){//判断是否有按键操作if (GetAsyncKeyState(up)){if(snake.CH!=down)snake.CH = up;}else if (GetAsyncKeyState(down)){if (snake.CH != up)snake.CH = down;}else if (GetAsyncKeyState(right)){if (snake.CH != left)snake.CH = right;}else if (GetAsyncKeyState(left)){if (snake.CH != right)snake.CH = left;}else if (GetAsyncKeyState(VK_F1)){if(snake.SPEED>=100)snake.SPEED -= 50;}else if (GetAsyncKeyState(VK_F2)){if (snake.SPEED <= 3000)snake.SPEED += 100;}//根据检测到的⽅向改变蛇头的位置switch (snake.CH){case right:snake.coord[1].x += 2; break;case left:snake.coord[1].x -= 2; break;case up:snake.coord[1].y -= 1; break;case down:snake.coord[1].y += 1; break;}}//画出蛇void draw_snake(){//画出蛇头gotoxy(snake.coord[1].x, snake.coord[1].y);printf("□");//画出蛇⾝,直接⼀个for循环实现for (int i = 2; i <= snake.len; i++){gotoxy(snake.coord[i].x, snake.coord[i].y);printf("□");}//擦掉尾巴gotoxy(snake.coord[snake.len].x, snake.coord[snake.len].y); printf(" ");//遍历每⼀节蛇for (int i = snake.len; i >1; i--){snake.coord[i].x = snake.coord[i - 1].x;snake.coord[i].y = snake.coord[i - 1].y;}gotoxy(0, 0);printf("■");gotoxy(85, 25);printf("得分:%d ", snake.len-1);}//产⽣⾷物void creatfood(){//随机种⼦⽣成srand((unsigned)time(NULL));if(food.flag)while (1){food.x = rand() % 80;food.y = rand() % 30;if (food.x % 2 == 0 && food.x >= 2 && food.x <= 78 && food.y > 1 && food.y < 30){int flag = 0;//判断产⽣的⾷物可不可能在蛇的⾝体上for (int i = 1; i <= snake.len; i++){if (snake.coord[i].x == food.x&&snake.coord[i].y == food.y){flag = 1;break;}}if (flag)continue;//绘制⾷物else{gotoxy(food.x, food.y);printf("⊙");food.flag = 0;break;}}}food.flag = 0;}//判断蛇是否吃到⾷物void eatfood(){//只需要判断蛇头是否与⾷物重合if (food.x == snake.coord[1].x&&food.y == snake.coord[1].y){snake.len+=1;food.flag = 1;}}//判断蛇是否死掉void SnakeState(){if (snake.coord[1].x < 2 || snake.coord[1].x>78 || snake.coord[1].y < 1 || snake.coord[1].y>29) snake.flag = 0;for (int i = 2; i <= snake.len; i++){if (snake.coord[1].x == snake.coord[i].x&&snake.coord[1].y == snake.coord[i].y)snake.flag = 0;}}更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

贪吃蛇C语言源代码

贪吃蛇C语言源代码

#include <stdio.h>#include <stdlib.h>#include <Windows.h>//windows编程头文件#include <time.h>#include <conio.h>//控制台输入输出头文件#ifndef __cplusplustypedef char bool;#define false 0#define true 1#endif//将光标移动到控制台的(x,y)坐标点处void gotoxy(int x, int y){COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }#define SNAKESIZE 100//蛇的身体最大节数#define MAPWIDTH 78//宽度#define MAPHEIGHT 24//高度//食物的坐标struct {int x;int y;}food;//蛇的相关属性struct {int speed;//蛇移动的速度int len;//蛇的长度int x[SNAKESIZE];//组成蛇身的每一个小方块中x的坐标int y[SNAKESIZE];//组成蛇身的每一个小方块中y的坐标}snake;//绘制游戏边框void drawMap();//随机生成食物void createFood();//按键操作void keyDown();//蛇的状态bool snakeStatus();//从控制台移动光标void gotoxy(int x, int y);int key = 72;//表示蛇移动的方向,72为按下“↑”所代表的数字//用来判断蛇是否吃掉了食物,这一步很重要,涉及到是否会有蛇身移动的效果以及蛇身增长的效果int changeFlag = 0;int sorce = 0;//记录玩家的得分int i;void drawMap(){//打印上下边框for (i = 0; i <= MAPWIDTH; i += 2)//i+=2是因为横向占用的是两个位置{//将光标移动依次到(i,0)处打印上边框gotoxy(i, 0);printf("■");//将光标移动依次到(i,MAPHEIGHT)处打印下边框gotoxy(i, MAPHEIGHT);printf("■");}//打印左右边框for (i = 1; i < MAPHEIGHT; i++){//将光标移动依次到(0,i)处打印左边框gotoxy(0, i);printf("■");//将光标移动依次到(MAPWIDTH, i)处打印左边框gotoxy(MAPWIDTH, i);printf("■");}//随机生成初试食物while (1){srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//生成的食物横坐标的奇偶必须和初试时蛇头所在坐标的奇偶一致,因为一个字符占两个字节位置,若不一致//会导致吃食物的时候只吃到一半if (food.x % 2 == 0)break;}//将光标移到食物的坐标处打印食物gotoxy(food.x, food.y);printf("*");//初始化蛇的属性snake.len = 3;snake.speed = 200;//在屏幕中间生成蛇头snake.x[0] = MAPWIDTH / 2 + 1;//x坐标为偶数snake.y[0] = MAPHEIGHT / 2;//打印蛇头gotoxy(snake.x[0], snake.y[0]);printf("■");//生成初试的蛇身for (i = 1; i < snake.len; i++){//蛇身的打印,纵坐标不变,横坐标为上一节蛇身的坐标值+2snake.x[i] = snake.x[i - 1] + 2;snake.y[i] = snake.y[i - 1];gotoxy(snake.x[i], snake.y[i]);printf("■");}//打印完蛇身后将光标移到屏幕最上方,避免光标在蛇身处一直闪烁gotoxy(MAPWIDTH - 2, 0);return;}void keyDown(){int pre_key = key;//记录前一个按键的方向if (_kbhit())//如果用户按下了键盘中的某个键{fflush(stdin);//清空缓冲区的字符//getch()读取方向键的时候,会返回两次,第一次调用返回0或者224,第二次调用返回的才是实际值key = _getch();//第一次调用返回的不是实际值key = _getch();//第二次调用返回实际值}/**蛇移动时候先擦去蛇尾的一节*changeFlag为0表明此时没有吃到食物,因此每走一步就要擦除掉蛇尾,以此营造一个移动的效果*为1表明吃到了食物,就不需要擦除蛇尾,以此营造一个蛇身增长的效果*/if (changeFlag == 0){gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}//将蛇的每一节依次向前移动一节(蛇头除外)for (i = snake.len - 1; i > 0; i--){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.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;/***控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*///判断蛇头应该往哪个方向移动switch (key){case 75:snake.x[0] -= 2;//往左break;case 77:snake.x[0] += 2;//往右break;case 72:snake.y[0]--;//往上break;case 80:snake.y[0]++;//往下break;}//打印出蛇头gotoxy(snake.x[0], snake.y[0]);printf("■");gotoxy(MAPWIDTH - 2, 0);//由于目前没有吃到食物,changFlag值为0changeFlag = 0;return;}void createFood(){if (snake.x[0] == food.x && snake.y[0] == food.y)//蛇头碰到食物{//蛇头碰到食物即为要吃掉这个食物了,因此需要再次生成一个食物while (1){int flag = 1;srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//随机生成的食物不能在蛇的身体上for (i = 0; i < snake.len; i++){if (snake.x[i] == food.x && snake.y[i] == food.y){flag = 0;break;}}//随机生成的食物不能横坐标为奇数,也不能在蛇身,否则重新生成if (flag && food.x % 2 == 0)break;}//绘制食物gotoxy(food.x, food.y);printf("*");snake.len++;//吃到食物,蛇身长度加1sorce += 10;//每个食物得10分snake.speed -= 5;//随着吃的食物越来越多,速度会越来越快changeFlag = 1;//很重要,因为吃到了食物,就不用再擦除蛇尾的那一节,以此来造成蛇身体增长的效果}return;}bool snakeStatus(){//蛇头碰到上下边界,游戏结束if (snake.y[0] == 0 || snake.y[0] == MAPHEIGHT)return false;//蛇头碰到左右边界,游戏结束if (snake.x[0] == 0 || snake.x[0] == MAPWIDTH)return false;//蛇头碰到蛇身,游戏结束for (i = 1; i < snake.len; i++){if (snake.x[i] == snake.x[0] && snake.y[i] == snake.y[0])return false;}return true;}int main(){drawMap();while (1){keyDown();if (!snakeStatus())break;createFood();Sleep(snake.speed);}gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2);printf("Game Over!\n");gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2 + 1);printf("本次游戏得分为:%d\n", sorce);Sleep(5000);return 0;}。

贪吃蛇的C语言程序

贪吃蛇的C语言程序
sbit P03=P0^3;
sbit P04=P0^4;
#define RIGHT 1
#define LIFT 2
#define UP 3
#define DOWN 4
bit ESC=1; //开始暂停标志位
bit START=1; //重新开始标志位
bit M_LEVEL=0; //显示难度标志位
bit hero=0; //完成游戏
unsigned char gamespeed=20;//游戏速度调节
unsigned char level=1; //难度
unsigned char code s[]="--ByTang";
unsigned char s1[]="1";
struct Food
{
uchar x;/*食物的横坐标*/
uchar y;/*食物的纵坐标*/
delay(gamespeed); //速度设置
/*去除蛇的的最后一节*/
RectArea(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+2,snake.y[snake.node-1]+2,0);
}//EDN while(!ESC)
if(hero)
{
ClearLCD();
img12864_disp(wancheng);
hz_disp(0,110,1,xie,1);
hz_disp(2,110,1,xie,1);
hz_disp(4,110,1,shi,1);
hz_disp(6,110,1,wan,1);
hz_disp(6,20,4,tangwei,1);

Win-TC(C语言)贪吃蛇游戏程序设计

Win-TC(C语言)贪吃蛇游戏程序设计

Win-TC (C语言)贪吃蛇游戏程序设计贪吃蛇游戏是大家熟悉的一个经典游戏,现在用Win-TC编译环境来实现游戏过程。

游戏功能如下:游戏开始后在屏幕出现一条自由活动的蛇,玩家可通过小键盘的方向功能键来控制蛇的运动方向,系统每间隔10秒钟随机投放一次食物(一颗食用果或毒果)。

蛇每吃到一颗食用果后其身体长度会自动增长一节,玩家得到5分的成绩奖励,当蛇吃到毒果或碰到四周边界和蛇头碰到蛇身的某一部位时,游戏结束。

(更新版本)图1、贪吃蛇游戏效果图游戏源程序清单如下:#include <graphics.h>#include <stdlib.h>#include <time.h>#include <bios.h>#include <dos.h>#include <stdio.h>#define MAXSIZE 1000 /*定义贪吃蛇最大长度*/#define LEFT 75 /*定义方向键左向键盘值*/#define RIGHT 77 /*定义方向键右向键盘值*/#define UP 72 /*定义方向键上向键盘值*/#define DOWN 80 /*定义方向键下向键盘值*/#define WINTOP 120 /*定义游戏区上边界y坐标值*/#define WINDOWN 360 /*定义游戏区下边界y坐标值*/#define WINLEFT 140 /*定义游戏区左边界x坐标值*/ #define WINRIGHT 500 /*定义游戏区右边界x坐标值*/char FILLC[]={0xfe,0x90,0x49,0xa0,0x30,0xc0,0x29,0xc0,0x46,0xa0,0xfe,0x90,0x49,0xa0,0x30,0xc0,0x21,0xc0,0x53,0x20,0x80,0x90,0x10,0x40}; /*恢复屏幕数据*/char RNULL[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; /*头部数据*//*top*/char headt[]={0x00,0x00,0x0f,0x00,0x1f,0x80,0x3f,0xc0,0x26,0x40,0x26,0x40,0x3f,0xc0,0x3f,0xc0,0x3f,0xc0,0x3f,0xc0,0x1f,0x80,0x1f,0x80};/*down*/char headd[]={0x1f,0x80,0x1f,0x80,0x3f,0xc0,0x3f,0xc0,0x3f,0xc0,0x3f,0xc0,0x26,0x40,0x26,0x40,0x3f,0xc0,0x1f,0x80,0x0f,0x00,0x00,0x00};/*right*/char headr[]={0x00,0x00,0x00,0x00,0x3f,0x80,0xfc,0xc0,0xfc,0xe0,0xff,0xe0,0xff,0xe0,0xfc,0xe0,0xfc,0xc0,0x3f,0x80,0x00,0x00,0x00,0x00};/*left*/char headl[]={0x00,0x00,0x00,0x00,0x1f,0xc0,0x33,0xf0,0x73,0xf0,0x7f,0xf0,0x7f,0xf0,0x73,0xf0,0x33,0xf0,0x1f,0xc0,0x00,0x00,0x00,0x00};/*身体数据*//*left down*/char leftd[]={0x1f,0x80,0x1f,0x80,0x1f,0xc0,0x1f,0xf0,0x1f,0xf0,0x0f,0xf0,0x0f,0xf0,0x07,0xf0,0x01,0xf0,0x00,0x00,0x00,0x00,0x00,0x00};/*right down*/char rightd[]={0x1f,0x80,0x1f,0x80,0x3f,0x80,0xff,0x80,0xff,0x80,0xff,0x00,0xff,0x00,0xfe,0x00,0xf8,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; /*left top*/char leftt[]={0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xf0,0x07,0xf0,0x0f,0xf0,0x0f,0xf0,0x1f,0xf0,0x1f,0xf0,0x1f,0xc0,0x1f,0x80,0x1f,0x80};/*right top*/char rightt[]={0x00,0x00,0x00,0x00,0x00,0x00,0xf8,0x00,0xfe,0x00,0xff,0x00,0xff,0x00,0xff,0x80,0xff,0x80,0x3f,0x80,0x1f,0x80,0x1f,0x80};/*top down*/char tp_dn[]={0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80}; /*left right*/char lf_rh[]={0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xf0,0xff,0xf0,0xff,0xf0,0xff,0xf0,0xff,0xf0,0xff,0xf0,0x00,0x00,0x00,0x00,0x00,0x00}; /*尾巴数据*//*down*/char re_dn[]={0x09,0x00,0x19,0x80,0x19,0x80,0x19,0x80,0x19,0x80,0x19,0x80,0x19,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80}; /*top*/char re_tp[]={0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x1f,0x80,0x19,0x80,0x19,0x80,0x19,0x80,0x19,0x80,0x19,0x80,0x19,0x80,0x09,0x00}; /*right*/char re_rh[]={0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0xf0,0xff,0xf0,0x01,0xf0,0x01,0xf0,0xff,0xf0,0x7f,0xf0,0x00,0x00,0x00,0x00,0x00,0x00}; /*left*/char re_lf[]={0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xe0,0xff,0xf0,0xf8,0x00,0xf8,0x00,0xff,0xf0,0xff,0xe0,0x00,0x00,0x00,0x00,0x00,0x00}; /*食用果数据*/char sfood[]={0x00,0x00,0x0f,0x00,0x1f,0x80,0x3f,0xc0,0x7f,0xe0,0x7f,0xe0,0x7f,0xe0,0x7f,0xe0,0x3f,0xc0,0x1f,0x80,0x0f,0x00,0x00,0x00}; /*毒果数据*/char block[]={0x06,0x00,0x06,0x00,0x0f,0x00,0x0f,0x00,0x3f,0xc0,0x7f,0xe0,0x7f,0xe0,0x3f,0xc0,0x0f,0x00,0x0f,0x00,0x06,0x00,0x06,0x00}; /*定义贪吃蛇数据类型*/typedef struct TANCHISHE{int x;/*每节位置x分量*/int y;/*每节位置y分量*/int ns;/*每节蛇体(位图)状态标识*/int left; /*向左运动标识状态*/int right;/*向右运动标识状态*/int top;/*向上运动标识状态*/int down;/*向下运动标识状态*/}TANCHISHE;/*定义整条蛇的数据类型*/typedef struct{TANCHISHE Snakeh;/*头部数据*/TANCHISHE Snakeb[MAXSIZE];/*刷新蛇体数据*/TANCHISHE old_Snakeb[MAXSIZE];/*保存上一次蛇体数据*/TANCHISHE Snaket;/*尾巴数据*/int cx;/*恢复屏幕数据位置x分量*/int cy;/*恢复屏幕数据位置y分量*/int hx;/*头部位置x分量*/int hy;/*头部位置y分量*/int size;/*每节长度大小*/int front;/*队列头指针*/int rear;/*队列尾指针*/}TCsQueue;static char *TCShead[4]={headt,headd,headl,headr};static char *TCSbody[6]={leftt,leftd,rightt,rightd,lf_rh,tp_dn};static char *TCStail[4]={re_lf,re_rh,re_tp,re_dn};/*定义食物的数据类型*/typedef struct FOOD{int fx;/*食物x坐标位置分量*/int fy;/*食物y坐标位置分量*/int fns;/*食物种类标识符*/int fkey;/*游戏区是否有食物标识符*/int fnew_t;/*投放食物时间分量*/}FOOD;/*设置蛇头运动方向*/void SetSnakeHeadMove(int top,int down,int left,int right,TCsQueue *st) {st->Snakeh.top=top;st->Snakeh.down=down;st->Snakeh.left=left;st->Snakeh.right=right;}/*初始化蛇*/void init_TCs(TCsQueue *st){int nt,sx=320,sy=240,size=12;srand((unsigned) time(NULL));nt=rand()%4;st->front=-1;st->rear=0;st->Snakeh.x=sx;st->Snakeh.y=sy;st->Snakeh.ns=nt;SetSnakeHeadMove(0,0,0,0,st);st->size=size;st->Snakeb[st->rear].left=0;st->Snakeb[st->rear].right=0;st->Snakeb[st->rear].top=0;st->Snakeb[st->rear].down=0;switch(nt){case 0:st->hx=sx;st->hy=sy;st->Snakeh.top=1;st->Snakeb[st->rear].ns=5;st->Snakeb[st->rear].top=1;st->Snakeb[st->rear].x=st->Snakeh.x;st->Snakeb[st->rear].y=st->Snakeh.y+st->size; st->Snaket.ns=2;st->Snaket.x=st->Snakeb[st->rear].x;st->Snaket.y=st->Snakeb[st->rear].y+st->size; st->cx=st->Snaket.x;st->cy=st->Snaket.y+st->size;break;case 1:st->hx=sx;st->hy=sy+size;st->Snakeh.down=1;st->Snakeb[st->rear].ns=5;st->Snakeb[st->rear].down=1;st->Snakeb[st->rear].x=st->Snakeh.x;st->Snakeb[st->rear].y=st->Snakeh.y-st->size; st->Snaket.ns=3;st->Snaket.x=st->Snakeb[st->rear].x;st->Snaket.y=st->Snakeb[st->rear].y-st->size; st->cx=st->Snaket.x;st->cy=st->Snaket.y-st->size;break;case 2:st->hx=sx;st->hy=sy;st->Snakeh.left=1;st->Snakeb[st->rear].ns=4;st->Snakeb[st->rear].left=1;st->Snakeb[st->rear].x=st->Snakeh.x+st->size;st->Snakeb[st->rear].y=st->Snakeh.y;st->Snaket.ns=0;st->Snaket.x=st->Snakeb[st->rear].x+st->size;st->Snaket.y=st->Snakeb[st->rear].y;st->cx=st->Snaket.x+st->size;st->cy=st->Snaket.y;break;case 3:st->hx=sx+size;st->hy=sy;st->Snakeh.right=1;st->Snakeb[st->rear].ns=4;st->Snakeb[st->rear].right=1;st->Snakeb[st->rear].x=st->Snakeh.x-st->size;st->Snakeb[st->rear].y=st->Snakeh.y;st->Snaket.ns=1;st->Snaket.x=st->Snakeb[st->rear].x-st->size;st->Snaket.y=st->Snakeb[st->rear].y;st->cx=st->Snaket.x-st->size;st->cy=st->Snaket.y;break;}st->old_Snakeb[st->rear].ns=st->Snakeb[st->rear].ns;st->old_Snakeb[st->rear].x=st->Snakeb[st->rear].x;st->old_Snakeb[st->rear].y=st->Snakeb[st->rear].y;st->old_Snakeb[st->rear].left=st->Snakeb[st->rear].left;st->old_Snakeb[st->rear].right=st->Snakeb[st->rear].right;st->old_Snakeb[st->rear].top=st->Snakeb[st->rear].top;st->old_Snakeb[st->rear].down=st->Snakeb[st->rear].down; }/*获取键盘按键码*/int get_key(){union REGS rg;rg.h.ah=0;int86(0x16,&rg,&rg);return rg.h.ah;}/*绘制位图*/void DrawBit(int x,int y,char maske[]){int i,j,k,n=2,size=12;for(i=0;i<size;i++)for(j=0;j<n;j++)for(k=0;k<8;k++){if(j&&k>3)break;if(maske[i*n+j]&(0x80>>k)){if(FILLC[i*n+j]&(0x80>>k))putpixel(x+j*8+k,y+i,10);elseputpixel(x+j*8+k,y+i,2);}elseputpixel(x+j*8+k,y+i,0);}}/*绘制蛇体*/void DrawSnake(TCsQueue *st){int i;DrawBit(st->Snakeh.x,st->Snakeh.y,TCShead[st->Snakeh.ns]);for(st->front=0;st->front<=st->rear;st->front++)DrawBit(st->Snakeb[st->front].x,st->Snakeb[st->front].y,TCSbody[st->Snakeb[st->front].ns]);DrawBit(st->Snaket.x,st->Snaket.y,TCStail[st->Snaket.ns]);DrawBit(st->cx,st->cy,RNULL);st->front=-1;for(i=0;i<3;i++){delay(50000);}}/*刷新和保存蛇体运动轨迹数据*/void Set_Snake(int x,int y,int ns,int left,int right,int top,int down,TCsQueue *st){st->Snakeb[0].x=x;st->Snakeb[0].y=y;st->Snakeb[0].ns=ns;st->Snakeb[0].left=left;st->Snakeb[0].right=right;st->Snakeb[0].down=down;for(st->front=1;st->front<=st->rear;st->front++){st->Snakeb[st->front].ns=st->old_Snakeb[st->front-1].ns;st->Snakeb[st->front].x=st->old_Snakeb[st->front-1].x;st->Snakeb[st->front].y=st->old_Snakeb[st->front-1].y;st->Snakeb[st->front].left=st->old_Snakeb[st->front-1].left;st->Snakeb[st->front].right=st->old_Snakeb[st->front-1].right;st->Snakeb[st->front].top=st->old_Snakeb[st->front-1].top;st->Snakeb[st->front].down=st->old_Snakeb[st->front-1].down;}st->cx=st->Snaket.x;st->cy=st->Snaket.y;st->Snaket.x=st->old_Snakeb[st->rear].x;st->Snaket.y=st->old_Snakeb[st->rear].y;if(st->old_Snakeb[st->rear].left)st->Snaket.ns=0;if(st->old_Snakeb[st->rear].right)st->Snaket.ns=1;if(st->old_Snakeb[st->rear].top)st->Snaket.ns=2;if(st->old_Snakeb[st->rear].down)st->Snaket.ns=3;for(st->front=0;st->front<=st->rear;st->front++){st->old_Snakeb[st->front].ns=st->Snakeb[st->front].ns;st->old_Snakeb[st->front].x=st->Snakeb[st->front].x;st->old_Snakeb[st->front].y=st->Snakeb[st->front].y;st->old_Snakeb[st->front].left=st->Snakeb[st->front].left;st->old_Snakeb[st->front].right=st->Snakeb[st->front].right;st->old_Snakeb[st->front].top=st->Snakeb[st->front].top;st->old_Snakeb[st->front].down=st->Snakeb[st->front].down;}st->front=-1;DrawSnake(st);}/*描述蛇体运动轨迹*/void Move_Snake(TCsQueue *st){if(st->Snakeh.top){st->Snakeh.y-=st->size;st->hx=st->Snakeh.x;Set_Snake(st->Snakeh.x,st->Snakeh.y+st->size,5,0,0,1,0,st);}if(st->Snakeh.down){st->Snakeh.y+=st->size;st->hx=st->Snakeh.x;st->hy=st->Snakeh.y+st->size;Set_Snake(st->Snakeh.x,st->Snakeh.y-st->size,5,0,0,0,1,st);}if(st->Snakeh.left){st->Snakeh.x-=st->size;st->hx=st->Snakeh.x;st->hy=st->Snakeh.y;Set_Snake(st->Snakeh.x+st->size,st->Snakeh.y,4,1,0,0,0,st);}if(st->Snakeh.right){st->Snakeh.x+=st->size;st->hx=st->Snakeh.x+st->size;st->hy=st->Snakeh.y;Set_Snake(st->Snakeh.x-st->size,st->Snakeh.y,4,0,1,0,0,st);}}/*输出蛇长度和游戏成绩*/void OutData(TCsQueue *st){char tms[100];setfillstyle(1,8);bar(260,80,330,95);sprintf(tms," %d ",st->rear);outtextxy(265,80,tms);bar(400,80,470,95);sprintf(tms," %d ",st->rear*5);outtextxy(405,80,tms);}/*描述蛇体增长数据*/void InputSnakebody(TCsQueue *st){if(st->rear>MAXSIZE-1)/*判断队列是否有空位*/{Move_Snake(st);setcolor(15);settextstyle(1,0,2);outtextxy(270,240,"Game over!");outtextxy(235,255,"The snake too long!"); outtextxy(235,270,"Press a key to exit");getch();closegraph();exit(0);}else{Move_Snake(st);/*吃掉食物占居食物的位置*/ /*队尾指针后移初始化新蛇体(增长部分)数据尾巴数据连到正确位置*/st->rear++;st->Snakeb[st->rear].left=0;st->Snakeb[st->rear].right=0;st->Snakeb[st->rear].top=0;st->Snakeb[st->rear].down=0;st->Snakeb[st->rear].x=st->Snaket.x;st->Snakeb[st->rear].y=st->Snaket.y;if(st->Snaket.ns==0){st->Snakeb[st->rear].ns=4;st->Snakeb[st->rear].left=1;st->Snaket.x+=st->size;st->cx=st->Snaket.x+st->size;st->cy=st->Snaket.y;}if(st->Snaket.ns==1){st->Snakeb[st->rear].ns=4;st->Snakeb[st->rear].right=1;st->Snaket.x-=st->size;st->cx=st->Snaket.x-st->size;st->cy=st->Snaket.y;}if(st->Snaket.ns==2){st->Snakeb[st->rear].ns=5;st->Snakeb[st->rear].top=1;st->Snaket.y+=st->size;st->cx=st->Snaket.x;st->cy=st->Snaket.y+st->size;}if(st->Snaket.ns==3){st->Snakeb[st->rear].ns=5;st->Snakeb[st->rear].down=1;st->Snaket.y-=st->size;st->cx=st->Snaket.x;st->cy=st->Snaket.y-st->size;}st->old_Snakeb[st->rear].ns=st->Snakeb[st->rear].ns;st->old_Snakeb[st->rear].x=st->Snakeb[st->rear].x;st->old_Snakeb[st->rear].y=st->Snakeb[st->rear].y;st->old_Snakeb[st->rear].left=st->Snakeb[st->rear].left;st->old_Snakeb[st->rear].right=st->Snakeb[st->rear].right;st->old_Snakeb[st->rear].top=st->Snakeb[st->rear].top;st->old_Snakeb[st->rear].down=st->Snakeb[st->rear].down;}OutData(st);}/*根据条件重组蛇体运动轨迹数据*/void SnakeObject(TCsQueue *st,int key){switch(key){case LEFT:if(!st->Snakeh.left&&!st->Snakeh.right){st->Snakeh.ns=2;st->Snakeh.x-=st->size;st->hx=st->Snakeh.x;if(st->Snakeh.top)Set_Snake(st->Snakeh.x+st->size,st->Snakeh.y,2,1,0,0,0,st);if(st->Snakeh.down){st->hy-=st->size;Set_Snake(st->Snakeh.x+st->size,st->Snakeh.y,3,1,0,0,0,st);}SetSnakeHeadMove(0,0,1,0,st);}break;case RIGHT:if(!st->Snakeh.left&&!st->Snakeh.right){st->Snakeh.ns=3;st->Snakeh.x+=st->size;st->hx=st->Snakeh.x+st->size;if(st->Snakeh.top)Set_Snake(st->Snakeh.x-st->size,st->Snakeh.y,0,0,1,0,0,st); if(st->Snakeh.down){st->hy-=st->size;Set_Snake(st->Snakeh.x-st->size,st->Snakeh.y,1,0,1,0,0,st); }SetSnakeHeadMove(0,0,0,1,st);}break;case UP:if(!st->Snakeh.top&&!st->Snakeh.down){st->Snakeh.ns=0;st->Snakeh.y-=st->size;st->hy=st->Snakeh.y;if(st->Snakeh.left)Set_Snake(st->Snakeh.x,st->Snakeh.y+st->size,1,0,0,1,0,st); if(st->Snakeh.right){st->hx-=st->size;Set_Snake(st->Snakeh.x,st->Snakeh.y+st->size,3,0,0,1,0,st); }SetSnakeHeadMove(1,0,0,0,st);}break;case DOWN:if(!st->Snakeh.top&&!st->Snakeh.down){st->Snakeh.ns=1;st->Snakeh.y+=st->size;st->hy=st->Snakeh.y+st->size;if(st->Snakeh.left)Set_Snake(st->Snakeh.x,st->Snakeh.y-st->size,0,0,0,0,1,st); if(st->Snakeh.right){st->hx-=st->size;Set_Snake(st->Snakeh.x,st->Snakeh.y-st->size,2,0,0,0,1,st); }SetSnakeHeadMove(0,1,0,0,st);}break;}}/*判断蛇是否触到边界或触到身体和触到毒果如果是结束游戏退出*/int GameOver(TCsQueue *st,FOOD *ft){int qt=0;if(st->hx<WINLEFT||st->hx==WINRIGHT)qt=1;if(st->hy<WINTOP||st->hy==WINDOWN)qt=1;for(st->front=0;st->front<=st->rear;st->front++){if(st->Snakeh.top){if(st->hx==st->Snakeb[st->front].x&&st->hy==st->Snakeb[st->front].y+st->size) qt=1;if(st->hx==st->Snaket.x&&st->hy==st->Snaket.y+st->size)qt=1;}if(st->Snakeh.left){if(st->hx==st->Snakeb[st->front].x+st->size&&st->hy==st->Snakeb[st->front].y) qt=1;if(st->hx==st->Snaket.x+st->size&&st->hy==st->Snaket.y)qt=1;}if(st->Snakeh.right||st->Snakeh.down){if(st->hx==st->Snakeb[st->front].x&&st->hy==st->Snakeb[st->front].y)qt=1;if(st->hx==st->Snaket.x&&st->hy==st->Snaket.y)qt=1;}}if(ft->fkey&&!ft->fns){if(st->Snakeh.top||st->Snakeh.down){if(st->hx==ft->fx){if(st->hy==ft->fy+st->size||st->hy==ft->fy)qt=1;}}if(st->Snakeh.left||st->Snakeh.right){if(st->hy==ft->fy){if(st->hx==ft->fx+st->size||st->hx==ft->fx)qt=1;}}}if(qt){setcolor(15);settextstyle(1,0,2);outtextxy(270,240,"Game over!");outtextxy(235,255,"Press a key to exit");}return qt;}/*显示帮助信息*/void GameHelp(){char ts[2];setfillstyle(1,7);bar(200,70,408,210);setcolor(6);outtextxy(280,80,"HELP");sprintf(ts,"%c",24);outtextxy(210,100,"Press the key ");outtextxy(325,100,ts);outtextxy(340,100,"to UP");sprintf(ts,"%c",25);outtextxy(210,120,"Press the key ");outtextxy(325,120,ts);outtextxy(340,120,"to DOWN");sprintf(ts,"%c",26);outtextxy(210,140,"Press the key ");outtextxy(325,140,ts);outtextxy(340,140,"to RIGHT");sprintf(ts,"%c",27);outtextxy(210,160,"Press the key ");outtextxy(325,160,ts);outtextxy(340,160,"to LEFT");outtextxy(230,190,"Press a key to game ");setcolor(15);line(200,90,408,90);line(200,180,408,180);getch();setfillstyle(1,8);bar(200,70,408,210);}/*绘制游戏窗口平台*/void GameWindow(){setfillstyle(1,1);bar(75,20,565,460);setfillstyle(1,8);bar(78,55,562,425);setcolor(6);rectangle(78,55,562,425);setcolor(9);rectangle(75,20,565,460);setcolor(15);outtextxy(80,35,"Game snake");GameHelp();outtextxy(150,80,"Snake length ");outtextxy(350,80,"Score ");setfillstyle(1,6);bar(128,108,512,372);setfillstyle(1,0);bar(139,119,500,360);setcolor(14);rectangle(139,119,500,360);}/*获取食物,蛇体增长一节,玩家得到5分成绩*/ void GetFood(FOOD *ft,TCsQueue *st){if(ft->fkey&&ft->fns){if(st->Snakeh.top||st->Snakeh.down){if(st->hx==ft->fx){if(st->hy==ft->fy+st->size||st->hy==ft->fy)InputSnakebody(st),ft->fkey=0;}}if(st->Snakeh.left||st->Snakeh.right){if(st->hy==ft->fy){if(st->hx==ft->fx+st->size||st->hx==ft->fx)InputSnakebody(st),ft->fkey=0;}}}}/*安放食物(先判断蛇体以外的空地然后随机放置食物,10秒钟投放一次,如果蛇没吃到食物,先清除原来的食物然后在新的位置安放食物。

C语言贪吃蛇源代码

C语言贪吃蛇源代码

C语言贪吃蛇源代码 TTA standardization office【TTA 5AB- TTAK 08- TTA 2C】#include<stdio.h>#include<process.h>#include<windows.h>#include<conio.h>#include<time.h>#include<stdlib.h>#define WIDTH 40#define HEIGH 12enum direction{//方向LEFT,RIGHT,UP,DOWN};struct Food{//食物int x;int y;};struct Node{//画蛇身int x;int y;struct Node *next;};struct Snake{//蛇属性int lenth;//长度enum direction dir;//方向};struct Food *food; //食物struct Snake *snake;//蛇属性struct Node *snode,*tail;//蛇身int SPEECH=200;int score=0;//分数int smark=0;//吃食物标记int times=0;int STOP=0;void Initfood();//产生食物void Initsnake();//构造snakevoid Eatfood();//头部前进void Addnode(int x, int y);//增加蛇身void display(struct Node *shead);//显示蛇身坐标void move();//蛇移动void draw();//画蛇void Homepage();//主页void keybordhit();//监控键盘按键void Addtail();//吃到食物void gotoxy(int x, int y)//定位光标{COORD pos;pos.X = x - 1;pos.Y = y - 1;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); }void Initsnake()//构造snake{int i;snake=(struct Snake*)malloc(sizeof(struct Snake));tail=(struct Node*)malloc(sizeof(struct Node));food = (struct Food*)malloc(sizeof(struct Food));snake->lenth=5;//初始长度 5snake->dir=RIGHT;//初始蛇头方向右for(i=2;i<=snake->lenth 2;i )//增加 5 个结点{Addnode(i,2);}}void Initfood()//产生食物{struct Node *p=snode;int mark=1;srand((unsigned)time(NULL));//以时间为种子产生随机数while(1){food->x=rand()%(WIDTH-2) 2;//食物X坐标food->y=rand()%(HEIGH-2) 2;//食物Y坐标while(p!=NULL){if((food->x==p->x)&&(food->y==p->y))//如果食物产生在蛇身上{//则重新生成食物mark=0;//食物生成无效break;}p=p->next;if(mark==1)//如果食物不在蛇身上,生成食物,否则重新生成食物{gotoxy(food->x,food->y);printf("%c",3);break;}mark=1;p=snode;}}void move()//移动{struct Node *q, *p=snode;if(snake->dir==RIGHT){Addnode(p->x 1,p->y);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}if(snake->dir==LEFT){Addnode(p->x-1,p->y);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}if(snake->dir==UP){Addnode(p->x,p->y-1);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}if(snake->dir==DOWN){Addnode(p->x,p->y 1);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}}void Addnode(int x, int y)//增加蛇身{struct Node *newnode=(struct Node *)malloc(sizeof(struct Node)); struct Node *p=snode;newnode->next=snode;newnode->x=x;newnode->y=y;snode=newnode;//结点加到蛇头if(x<2||x>=WIDTH||y<2||y>=HEIGH)//碰到边界{STOP=1;gotoxy(10,19);printf("撞墙,游戏结束,任意键退出!\n");//失败_getch();free(snode);//释放内存free(snake);exit(0);}while(p!=NULL)//碰到自身{if(p->next!=NULL)if((p->x==x)&&(p->y==y)){STOP=1;gotoxy(10,19);printf("撞到自身,游戏结束,任意键退出!\n");//失败_getch();free(snode);//释放内存free(snake);exit(0);}p=p->next;}}void Eatfood()//吃到食物{Addtail();score ;}void Addtail()//增加蛇尾{struct Node *newnode=(struct Node *)malloc(sizeof(struct Node)); struct Node *p=snode;tail->next=newnode;newnode->x=50;newnode->y=20;newnode->next=NULL;//结点加到蛇头tail=newnode;//新的蛇尾}void draw()//画蛇{struct Node *p=snode;int i,j;while(p!=NULL){gotoxy(p->x,p->y);printf("%c",2);tail=p;p=p->next;}if(snode->x==food->x&&snode->y==food->y)//蛇头坐标等于食物坐标{smark=1;Eatfood();//增加结点Initfood();//产生食物}if(smark==0){gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点printf("%c",' ');//如果吃到食物,不清楚尾结点}else{times=1;}if((smark==1)&&(times==1)){gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点printf("%c",' ');//如果吃到食物,不清楚尾结点smark=0;}gotoxy(50,12);printf("食物: %d,%d",food->x,food->y);gotoxy(50,5);printf("分数: %d",score);gotoxy(50,7);printf("速度: %d",SPEECH);gotoxy(15,14);printf("按o键加速");gotoxy(15,15);printf("按p键减速");gotoxy(15,16);printf("按空格键暂停");}void HideCursor()//隐藏光标{CONSOLE_CURSOR_INFO cursor_info = {1, 0};SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info); }void Homepage()//绘主页{int x,y;HideCursor();//隐藏光标printf("----------------------------------------\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("----------------------------------------\n");gotoxy(5,13);printf("任意键开始游戏!按W.A.S.D控制方向");_getch();Initsnake();Initfood();gotoxy(5,13);printf(" ");}void keybordhit()//监控键盘{char ch;if(_kbhit()){ch=getch();switch(ch){case 'W':case 'w':if(snake->dir==DOWN)//如果本来方向是下,而按相反方向无效{break;}elsesnake->dir=UP;break;case 'A':case 'a':if(snake->dir==RIGHT)//如果本来方向是右,而按相反方向无效{break;}elsesnake->dir=LEFT;break;case 'S':case 's':if(snake->dir==UP)//如果本来方向是上,而按相反方向无效{break;}elsesnake->dir=DOWN;break;case 'D':case 'd':if(snake->dir==LEFT)//如果本来方向是左,而按相反方向无效{break;}elsesnake->dir=RIGHT;break;case 'O':case 'o':if(SPEECH>=150)//速度加快{SPEECH=SPEECH-50;}break;case 'P':case 'p':if(SPEECH<=400)//速度减慢{SPEECH=SPEECH 50;}break;case ' '://暂停gotoxy(15,18);printf("游戏已暂停,按任意键恢复游戏"); system("pause>nul");gotoxy(15,18);printf(" "); break;default:break;}}}int main(void)//程序入口{Homepage();while(!STOP){keybordhit();//监控键盘按键move();//蛇的坐标变化draw();//蛇的重绘Sleep(SPEECH);//暂时挂起线程}return 0;}。

贪吃蛇游戏代码(C语言编写)

贪吃蛇游戏代码(C语言编写)

贪吃蛇游戏代码(C语言编写)#include "graphics.h"#include "stdio.h"#define MAX 200#define MAXX 30#define MAXY 30#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181#define PAGEUP 18688#define PAGEDOWN 20736#define KEY_U 5749#define KEY_K 9579#define CTRL_P 6512#define TRUE 1#define FALSE 0#define GAMEINIT 1#define GAMESTART 2#define GAMEHAPPY 3#define GAMEOVER 4struct SPlace{int x;int y;int st;} place[MAX];int speed;int count;int score;int control;int head;int tear;int x,y;int babyx,babyy;int class;int eat;int game;int gamedelay[]={5000,4000,3000,2000,1000,500,250,100}; int gamedelay2[]={1000,1};static int hitme=TRUE,hit = TRUE; void init(void);void nextstatus(void);void draw(void);void init(void){int i;for(i=0;i<max;i++)< p="">{place[i].x = 0;place[i].y = 0;place[i].st = FALSE;}place[0].st = TRUE;place[1].st = TRUE;place[1].x = 1;speed = 9;count = 0;score = 0;control = 4;head = 1;tear = 0;x = 1;y = 0;babyx = rand()%MAXX;babyy = rand()%MAXY;eat = FALSE;game = GAMESTART;}void nextstatus(void){int i;int exit;int xx,yy;xx = x;yy = y;switch(control){case 1: y--; yy = y-1; break;case 2: y++; yy = y+1; break;case 3: x--; xx = x-1; break;case 4: x++; xx = x+1; break;}hit = TRUE;if ( ((control == 1) || (control ==2 )) && ( (y < 1) ||(y >= MAXY-1)) || (((control == 3) || (control == 4)) && ((x < 1) ||(x >= MAXX-1) ) ) ){}if ( (y < 0) ||(y >= MAXY) ||(x < 0) ||(x >= MAXX) ){game = GAMEOVER;control = 0;return;}for (i = 0; i < MAX; i++){if ((place[i].st) &&(x == place[i].x) &&(y == place[i].y) ){game = GAMEOVER;control = 0;return;}if ((place[i].st) &&(xx == place[i].x) &&(yy == place[i].y) ){hit = FALSE;goto OUT;}}OUT:if ( (x == babyx) && (y == babyy) ) {count ++;score += (1+class) * 10;}head ++;if (head >= MAX) head = 0;place[head].x = x;place[head].y = y;place[head].st= TRUE;if (eat == FALSE){place[tear].st = FALSE;tear ++;if (tear >= MAX) tear = 0;}else{eat = FALSE;exit = TRUE;while(exit){babyx = rand()%MAXX;babyy = rand()%MAXY;exit = FALSE;for( i = 0; i< MAX; i++ )if( (place[i].st)&&( place[i].x == babyx) && (place[i].y == babyy))exit ++;}}if (head == tear) game = GAMEHAPPY;}void draw(void){char temp[50];int i,j;for (i = 0; i < MAX; i++ ){setfillstyle(1,9);if (place[i].st)bar(place[i].x*15+1,place[i].y*10+1,place[i].x*15+14,place[i]. y*10+9);}setfillstyle(1,4);bar(babyx*15+1,babyy*10+1,babyx*15+14,babyy*10+9);setcolor(8);setfillstyle(1,8);bar(place[head].x*15+1,place[head].y*10+1,place[head].x*1 5+14,place[head].y*10+9); /* for( i = 0; i <= MAXX; i++ ) line( i*15,0, i*15, 10*MAXY);for( j = 0; j <= MAXY; j++ )line( 0, j*10, 15*MAXX, j*10); */rectangle(0,0,15*MAXX,10*MAXY);sprintf(temp,"Count: %d",count);settextstyle(1,0,2);setcolor(8);outtextxy(512,142,temp);setcolor(11);outtextxy(510,140,temp);sprintf(temp,"1P: %d",score);settextstyle(1,0,2);setcolor(8);outtextxy(512,102,temp); setcolor(12);outtextxy(510,100,temp); sprintf(temp,"Class: %d",class); setcolor(8);outtextxy(512,182,temp); setcolor(11);outtextxy(510,180,temp);}main(){int pause = 0;char temp[50];int d,m;int key;int p;static int keydown = FALSE; int exit = FALSE;int stchange = 0;d = VGA;m = VGAMED;initgraph( &d, &m, "" ); setbkcolor(3);class = 3;init();p = 1;while(!exit){if (kbhit()){key = bioskey(0);switch(key){case UP: if( (control != 2)&& !keydown)control = 1;keydown = TRUE;break;case DOWN: if( (control != 1)&& !keydown)control = 2;keydown = TRUE;break;case LEFT: if( (control != 4)&& !keydown)control = 3;keydown = TRUE;break;case RIGHT: if( (control != 3)&& !keydown)control = 4;keydown = TRUE;break;case ESC: exit = TRUE;break;case ENTER: init();break;case PAGEUP: class --; if (class<0) class = 0; break;case PAGEDOWN: class ++;if (class>7) class = 7; break;case KEY_U: if( ( (control ==1) ||(control ==2))&& !keydown) control = 3;else if(( (control == 3) || (control == 4))&& !keydown)control = 1;keydown = TRUE;break;case KEY_K: if( ( (control ==1) ||(control ==2))&& !keydown) control = 4;else if(( (control == 3) || (control == 4))&& !keydown)control = 2;keydown = TRUE;break;case CTRL_P:pause = 1 - pause; break;}}stchange ++ ;putpixel(0,0,0);if (stchange > gamedelay[class] + gamedelay2[hit]){stchange = 0;keydown = FALSE;p = 1 - p;setactivepage(p);cleardevice();if (!pause)nextstatus();else{settextstyle(1,0,4);setcolor(12);outtextxy(250,100,"PAUSE");}draw();if(game==GAMEOVER){settextstyle(0,0,6);setcolor(8);outtextxy(101,101,"GAME OVER"); setcolor(15);outtextxy(99,99,"GAME OVER"); setcolor(12);outtextxy(100,100,"GAME OVER"); sprintf(temp,"Last Count: %d",count); settextstyle(0,0,2);outtextxy(200,200,temp);}if(game==GAMEHAPPY){settextstyle(0,0,6);setcolor(12);outtextxy(100,300,"YOU WIN"); sprintf(temp,"Last Count: %d",count); settextstyle(0,0,2);outtextxy(200,200,temp);}setvisualpage(p);}}closegraph();}</max;i++)<>。

C语言课程设计贪吃蛇源代码

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语⾔编写贪吃蛇(附源码,⽆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语言写简单贪吃蛇源代码.doc

简单贪吃蛇c语言代码,一个C语言写简单贪吃蛇源代码.doc

简单贪吃蛇c语⾔代码,⼀个C语⾔写简单贪吃蛇源代码.doc ⼀个C语⾔写简单贪吃蛇源代码#include#include#include#include#include#includeint grade=5,point=0,life=3;voidset(),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.x&&head_f->y==food.y) {Sleep(100);crate();food.judge=0;point=point+(6-grade)*10;if(food.x<30||food.y<30||food.x>570||food.y>570)life++;menu();}if(head_f->x<5||head_f->x>595||head_f->y<5||head_f->y>595) {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->x&&head_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;。

贪吃蛇C程序(gtk)

贪吃蛇C程序(gtk)

贪吃蛇源程序#include <gtk/gtk.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#define length 10/*最长蛇节数*/#define side 24/*每节蛇身以及食物的边长*/#define p_prize 20/*特殊食物概率*/GtkWidget *window;/*定义窗体*/GtkWidget *fixed;/*定义固定容器构件*/GtkWidget *snake[length];/*蛇的节数*/GtkWidget *food[length];/*食物数*/GtkWidget *border_up;/*上边界*/GtkWidget *border_down;/*下边界*/GtkWidget *border_left;/*左边界*/GtkWidget *border_right;/*右边界*/GtkWidget *game_score_label;/*当前分数标签*/GtkWidget *game_score[2*length-12];/*当前分数值*/GtkWidget *game_pause;/*游戏暂停*/GtkWidget *game_speed_label;/*速度调节标签*/GtkWidget *game_speed[4];/*当前速度*/GtkWidget *death;/*游戏失败提示窗口*/GtkWidget *win;/*游戏通关提示窗口*/GtkWidget *direction[4];/*改变蛇的方向*/GdkColor color[20];/*颜色值*/gint function(gpointer data);/*主体函数*/void up(void);/*往上*/void down(void);/*往下*/void left(void);/*往左*/void right(void);/*往右*/gboolean key_control(GtkWidget *widget,GdkEventKey *event);//键盘void show_pause(void);/*暂停|开始游戏*/void speed_control0(void);/*速度控制*/void speed_control1(void);void speed_control2(void);void eat(void);/*吃到食物*/void showwin(void);/*游戏通关*/void showdeath(void);/*游戏结束*/gpointer data;gint sign;/*定时器*/int i=0;/*暂停开始状态标记*/int j=0;/*累加变量*/int j1=0;int k=0;/*未设置速度前为0 游戏过程中为1 游戏结束时为-1*/int snake_x[length],snake_y[length],food_x[length],food_y[length];/*蛇及食物的坐标位置数组*/int flag=3;/*方向标记*/int jieshu=6;/*蛇当前节数*/int stop=1;/*蛇停止运动时stop=1*/int speed=0;int op_speed[3]={100,300,500};int prize[2*length-12]={0};charscore[41][8]={"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","1 6","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32"," 33","34","35","36","37","38","39","40"};char dir[4][4]={"上","下","左","右"};/*四个方向键的显示值*/int main(int argc,char *argv[ ]){gtk_init(&argc,&argv);/*初始化*/window=gtk_window_new(GTK_WINDOW_TOPLEVEL);/*游戏窗口*/gdk_color_parse ("#00F0F0", &color[0]);gdk_color_parse ("#F00000", &color[1]);gdk_color_parse ("#0F0000", &color[2]);gdk_color_parse ("#00F000", &color[3]);gdk_color_parse ("#000F00", &color[4]);gdk_color_parse ("#0000F0", &color[5]);gdk_color_parse ("#00000F", &color[6]);gdk_color_parse ("#F0F000", &color[7]);gdk_color_parse ("#FF0000", &color[8]);gdk_color_parse ("#0FF000", &color[9]);gdk_color_parse ("#00FF00", &color[10]);gdk_color_parse ("#F00F00", &color[11]);gdk_color_parse ("#F000F0", &color[12]);gdk_color_parse ("#F0F0F0", &color[13]);gdk_color_parse ("#F0000F", &color[14]);gdk_color_parse ("#0FF00F", &color[15]);gdk_color_parse ("#00FFF0", &color[16]);gdk_color_parse ("#F00FF0", &color[17]);gdk_color_parse ("#FF00F0", &color[18]);gdk_color_parse ("#F0F0FF", &color[19]);gtk_window_set_title(GTK_WINDOW(window),"贪吃蛇键盘、鼠标两种控制方式游戏前请先选择难度蛇不会咬到自己彩色食物加分多");/*设定游戏标题*/gtk_widget_set_usize(window,580,480);/*设置窗口大小*/gtk_widget_set_uposition(window,400,100);/*设定窗口位置*/g_signal_connect(GTK_OBJECT(window),"destroy",G_CALLBACK(gtk_main_quit),N ULL);gtk_window_set_resizable(GTK_WINDOW(window),FALSE);/*不允许修改窗口大小*/fixed=gtk_fixed_new();/*创建固定容器构件*//*蛇与食物*/srand((int)time(0));/*设置随机数种子*/for(j=0;j<length;j++){snake[j]=gtk_button_new_with_label("ss");/*创建蛇身*/food[j]=gtk_button_new_with_label("food");/*创建食物*/gtk_widget_set_size_request(snake[j],side,side);/*蛇身尺寸*/gtk_widget_set_size_request(food[j],side,side);/*食物大小*/gtk_widget_modify_bg(snake[j], GTK_STATE_NORMAL,&color[0]);if((rand()%100+1)<=p_prize){gtk_widget_modify_bg(food[j],GTK_STATE_NORMAL,&color[(rand()%19 )+1]);for(j1=j+1;j1<2*length-12;j1++){prize[j1]++;}}}for(j=0;j<length;j++) /*将蛇身放在窗口的指定位置*/{gtk_fixed_put(GTK_FIXED(fixed),snake[j],snake_x[j]=side*(6-j),snake_y[j]=sid e);/*蛇身初始位置设定*/gtk_fixed_put(GTK_FIXED(fixed),food[j],food_x[j]=side*(rand()%10)+side,foo d_y[j]=side*((rand()%10))+side);/*食物位置随机设定,最好利用系统时间获得随机分布*/}for(j=0;j<6;j++) /*初始显示6节蛇身*/{gtk_widget_show(snake[j]);/*显示蛇身*/}gtk_widget_show(food[0]);/*显示第一个食物*//*键盘按键控制方向*/g_signal_connect(G_OBJECT(window), "key-press-event",G_CALLBACK(key_control), NULL);/*方向键鼠标控制*/for(j=0;j<4;j++){direction[j]=gtk_button_new_with_label(dir[j]);/*方向按键*/gtk_widget_modify_bg(direction[j], GTK_STATE_NORMAL, &color[10]);gtk_widget_set_size_request(direction[j],50,50);/*按键大小*/gtk_widget_set_sensitive(direction[j],FALSE);/*方向无效*/}/*4个方向键位置设置*/gtk_fixed_put(GTK_FIXED(fixed),direction[0],485,25);/*上键位置*/gtk_fixed_put(GTK_FIXED(fixed),direction[1],485,125);/*下键位置*/gtk_fixed_put(GTK_FIXED(fixed),direction[2],442,75);/*左键位置*/gtk_fixed_put(GTK_FIXED(fixed),direction[3],528,75);/*右键位置*//*4个方向键的功能设置*/g_signal_connect(GTK_OBJECT(direction[0]),"clicked",G_CALLBACK(up),NULL);g_signal_connect(GTK_OBJECT(direction[1]),"clicked",G_CALLBACK(down),NULL);g_signal_connect(GTK_OBJECT(direction[2]),"clicked",G_CALLBACK(left),NULL);g_signal_connect(GTK_OBJECT(direction[3]),"clicked",G_CALLBACK(right),NULL); /*显示4个方向键*/for(j=0;j<4;j++){gtk_widget_show(direction[j]);/*显示4个方向按键*/}/*游戏边界*/border_left=gtk_button_new();/*创建游戏范围左边界*/gtk_widget_set_sensitive(border_left,FALSE);/*设定左边界类型不敏感*/ border_right=gtk_button_new();/*创建游戏范围右边界*/gtk_widget_set_sensitive(border_right,FALSE);/*右边界不敏感*/border_up=gtk_button_new();/*创建游戏范围上边界*/gtk_widget_set_sensitive(border_up,FALSE);/*上边界不敏感*/border_down=gtk_button_new();/*创建游戏范围下边界*/gtk_widget_set_sensitive(border_down,FALSE);/*下边界不敏感*/gtk_widget_modify_bg(border_up, GTK_STATE_NORMAL, &color[1]);gtk_widget_modify_bg(border_down, GTK_STATE_NORMAL, &color[1]);gtk_widget_modify_bg(border_left, GTK_STATE_NORMAL, &color[1]);gtk_widget_modify_bg(border_right, GTK_STATE_NORMAL, &color[1]);gtk_fixed_put(GTK_FIXED(fixed),border_left,15,15);/*左边界加入固定容器构件*/gtk_fixed_put(GTK_FIXED(fixed),border_right,432,15);/*右边界加入固定容器构件*/gtk_fixed_put(GTK_FIXED(fixed),border_up,15,15);/*上边界加入固定>容器构件*/gtk_fixed_put(GTK_FIXED(fixed),border_down,15,432);/*将下边界加入固定容器构件*/gtk_widget_set_size_request(border_up,580,10);/*上边界尺寸*/gtk_widget_set_size_request(border_down,580,10);/*下边界尺寸*/gtk_widget_set_size_request(border_left,10,425);/*左边界尺寸*/gtk_widget_set_size_request(border_right,10,425);/*右边界尺寸*/gtk_widget_show(border_up);/*显示上边界*/gtk_widget_show(border_down);/*显示下边界*/gtk_widget_show(border_left);/*显示左边界*/gtk_widget_show(border_right);/*显示右边界*//*计分功能*/game_score_label=gtk_button_new_with_label("目前得分:");gtk_widget_modify_bg(game_score_label, GTK_STATE_NORMAL, &color[6]);gtk_widget_set_sensitive(game_score_label,FALSE);/*不敏感*/gtk_fixed_put(GTK_FIXED(fixed),game_score_label,15,440);/*放入固定容器构件*/gtk_widget_show(game_score_label);/*显示标签*/for(j=0;j<2*length-12;j++){game_score[j]=gtk_button_new_with_label(score[j]);gtk_widget_modify_bg(game_score[j], GTK_STATE_NORMAL, &color[7]);gtk_fixed_put(GTK_FIXED(fixed),game_score[j],80,440);}gtk_widget_show(game_score[0]);/*暂停|开始功能*/game_pause=gtk_button_new_with_label("暂停|开始");gtk_widget_modify_bg(game_pause, GTK_STATE_NORMAL, &color[13]);gtk_widget_set_size_request(game_pause,140,140);/*设定尺寸*/gtk_fixed_put(GTK_FIXED(fixed),game_pause,439,295);/*位置设定*/gtk_widget_set_sensitive(game_pause,FALSE);g_signal_connect(GTK_OBJECT(game_pause),"clicked",G_CALLBACK(show_pause) ,NULL);/*暂停|开始按键功能设置*/gtk_widget_show(game_pause);/*显示暂停|开始按键*//*游戏速度步进调节功能*/game_speed_label=gtk_button_new_with_label("游戏难度选择");gtk_widget_set_sensitive(game_speed_label,FALSE);/*标签不敏感*/game_speed[0]=gtk_button_new_with_label("1困难");/*快速按钮*/game_speed[1]=gtk_button_new_with_label("2一般");/*一般按钮*/game_speed[2]=gtk_button_new_with_label("3容易");/*慢速按钮*/gtk_widget_modify_bg(game_speed[0], GTK_STATE_NORMAL, &color[1]);gtk_widget_modify_bg(game_speed[1], GTK_STATE_NORMAL, &color[3]);gtk_widget_modify_bg(game_speed[2], GTK_STATE_NORMAL, &color[5]);gtk_fixed_put(GTK_FIXED(fixed),game_speed_label,465,190);/*速度调节标签位置*/for(j=0;j<3;j++){gtk_fixed_put(GTK_FIXED(fixed),game_speed[j],445+45*j,220);}/*速度按钮功能设置*/g_signal_connect(GTK_OBJECT(game_speed[0]),"clicked",G_CALLBACK(speed_con trol0),NULL);g_signal_connect(GTK_OBJECT(game_speed[1]),"clicked",G_CALLBACK(speed_con trol1),NULL);g_signal_connect(GTK_OBJECT(game_speed[2]),"clicked",G_CALLBACK(speed_con trol2),NULL);/*显示按钮*/gtk_widget_show(game_speed_label);for(j=0;j<3;j++){gtk_widget_show(game_speed[j]);}/*游戏通关*/win=gtk_button_new_with_label("!!!恭喜你!!!");/*通关提示*/gtk_widget_modify_bg(win, GTK_STATE_NORMAL, &color[9]);gtk_widget_set_size_request(win,200,100);/*通关提示大小*/gtk_fixed_put(GTK_FIXED(fixed),win,120,150);/*通关提示位置*/g_signal_connect(GTK_OBJECT(win),"clicked",G_CALLBACK(gtk_main_quit),NULL);/*设定点击游戏成功提示窗口后游戏关闭*//*游戏失败*/death=gtk_button_new_with_label("!!!你输了!!!");/*创建游戏失败提示*/ gtk_widget_modify_bg(death, GTK_STATE_NORMAL, &color[8]);gtk_widget_set_size_request(death,200,100);/*设置游戏失败提示大小*/gtk_fixed_put(GTK_FIXED(fixed),death,120,150);/*设定游戏失败提示位置*/g_signal_connect(GTK_OBJECT(death),"clicked",G_CALLBACK(gtk_main_quit),NUL L);/*设定点击游戏失败提示窗口后游戏关闭*//*显示游戏窗口*/gtk_container_add(GTK_CONTAINER(window),fixed);/*放入窗体*/gtk_widget_show(fixed);/*显示固定容器构件*/gtk_widget_show(window);/*显示窗体*/gtk_main();/*等待gtk_main_quit执行后正常退出程序*/}/*以下为回调函数部分*/gint function(gpointer data){int q;eat();/*调用吃食物函数*/if(!stop)/*判断是否处于暂停状态*/{switch(flag)/*判断当前运动方向标记值*/{case 0:if(snake_y[0]<48)/*蛇已撞墙*/{showdeath();break;/*显示游戏失败提示*/}gtk_fixed_move(GTK_FIXED(fixed),snake[0],snake_x[0],snake_y[0]-side);break;/*蛇未撞墙则把蛇头往运动方向移动一格*/ case 1:if(snake_y[0]>400)/*蛇已撞墙*/{showdeath();break;/*显示游戏失败提示*/}gtk_fixed_move(GTK_FIXED(fixed),snake[0],snake_x[0],snake_y[0]+side);break;/*蛇未撞墙蛇头往运动方向移动一格*/case 2:if(snake_x[0]<48)/*蛇已撞墙*/{showdeath();break;/*显示游戏失败提示*/}gtk_fixed_move(GTK_FIXED(fixed),snake[0],snake_x[0]-side,snake_y[0]);break;/*蛇未撞墙蛇头往运动方向移动一格*/case 3:if(snake_x[0]>400)/*蛇已撞墙*/{showdeath();break;/*显示游戏失败提示*/}gtk_fixed_move(GTK_FIXED(fixed),snake[0],snake_x[0]+side,snake_y[0]);break;/*蛇未撞墙蛇头往运动方向移动一格*/}for(j=length-1;j>0;j--)/*剩余蛇身位置处理*/{gtk_fixed_move(GTK_FIXED(fixed),snake[j],snake_x[j]=snake_x[j-1],snake_y[j]= snake_y[j-1]);/*后一节蛇身移至前一节蛇身的位置*/}switch(flag)/*根据当前运动方向改变蛇头位置坐标值*/{case 0:snake_y[0]=snake_y[0]-side;break;/*若向上则将y减去一节蛇身长度*/ case 1:snake_y[0]=snake_y[0]+side;break;/*若向下则将y加上一节蛇身长度*/ case 2:snake_x[0]=snake_x[0]-side;break;/*若向左则将x减去一节蛇身长度*/ case 3:snake_x[0]=snake_x[0]+side;break;/*若向右则将x加上一节蛇身长度*/ }}}gboolean key_control(GtkWidget *widget, GdkEventKey *event)//键盘{if(k==0)/*通过数字1 2 3选择难度*/{if(strcmp(gdk_keyval_name(event->keyval),"1")==0)speed_control0();else if(strcmp(gdk_keyval_name(event->keyval),"2")==0)speed_control1();else if(strcmp(gdk_keyval_name(event->keyval),"3")==0)speed_control2();}else if(k==1)/*游戏开始后回车键暂停和开始游戏*/{if(strcmp(gdk_keyval_name(event->keyval),"Return")==0) show_pause();}else if(k==-1)/*游戏结束后回车键退出游戏*/{if(strcmp(gdk_keyval_name(event->keyval),"Return")==0)gtk_main_quit();}if(!stop)/*暂停状态不记录键盘方向控制*/{if(strcmp(gdk_keyval_name(event->keyval),"Up")==0)up();else if(strcmp(gdk_keyval_name(event->keyval),"Down")==0)down();else if(strcmp(gdk_keyval_name(event->keyval),"Left")==0)left();else if(strcmp(gdk_keyval_name(event->keyval),"Right")==0)right();}}void up(void)/*按“上”方向键*/{if(flag!=1)/*当前运动方向不为“下”时才向上运动*/flag=0;/*修改方向标记*/}void down(void)/*按“下”方向键*/{if(flag!=0)/*当前运动方向不为“上”时才向下运动*/flag=1;/*修改方向标记*/}void left(void)/*按“左”方向键*/{if(flag!=3)/*当前运动方向不为“右”时才向左运动*/flag=2;/*修改方向标记*/}void right(void)/*按“右”方向键*/{if(flag!=2)/*当前运动方向不为“左”时才向右运动*/flag=3;/*修改方向标记*/}void show_pause(void)/*暂停|开始函数*/{if(i==0){stop=1;for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],FALSE);/*暂停时方向键无效*/}i=1;}else{stop=0;for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],TRUE);/*开始后方向键有效*/}i=0;}}void eat(void)/*吃食物函数*/{if(jieshu==length)/*蛇身长度已达极限,食物已吃完*/{stop=1;gtk_widget_hide(food[jieshu-6]);showwin();/*调用游戏通关处理函数*/}else if((snake_x[0]==food_x[jieshu-6])&&(snake_y[0]==food_y[jieshu-6]))/*判断是否成功吃到食物*/{gtk_widget_show(snake[jieshu]);/*蛇身增长一节*/gtk_widget_hide(food[jieshu-6]);/*除去本次所吃食物*/gtk_widget_hide(game_score[jieshu-6+prize[jieshu-6]]);/*除去上次得分*/ jieshu++;/*蛇身长度标记增长一节*/gtk_widget_show(game_score[jieshu-6+prize[jieshu-6]]);//新得分gtk_widget_show(food[jieshu-6]);/*显示下一个食物*/}}void speed_control0(void)/*游戏难度选择困难处理函数*/{gtk_widget_hide(game_speed[1]);/*隐藏其余难度值*/gtk_widget_hide(game_speed[2]);/*隐藏其余难度值*/speed=0;k=1;sign=g_timeout_add(op_speed[speed],function,data);/*创建定时器*/ gtk_widget_set_sensitive(game_speed[0],FALSE);/*当前速度不敏感*/ gtk_widget_set_sensitive(game_pause,TRUE);/*暂停|开始按钮有效*/ for(j=0;j<length;j++){gtk_widget_set_sensitive(snake[j],TRUE);gtk_widget_set_sensitive(food[j],TRUE);}for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],TRUE);/*使方向选择有效*/ }sleep(0.7);/*等待0.7S便于游戏者反应*/stop=0;/*开始游戏*/}void speed_control1(void)/*游戏难度选择一般处理函数*/{gtk_widget_hide(game_speed[0]);/*隐藏其余难度值*/gtk_widget_hide(game_speed[2]);/*隐藏其余难度值*/speed=1;k=1;sign=g_timeout_add(op_speed[speed],function,data);/*创建定时器*/ gtk_widget_set_sensitive(game_speed[1],FALSE);/*当前难度不敏感*/ gtk_widget_set_sensitive(game_pause,TRUE);/*暂停|开始按钮有效*/ for(j=0;j<length;j++){gtk_widget_set_sensitive(snake[j],TRUE);gtk_widget_set_sensitive(food[j],TRUE);}for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],TRUE);/*使方向选择有效*/ }sleep(0.7);/*等待0.7S便于游戏者反应*/stop=0;/*开始游戏*/}void speed_control2(void)/*游戏难度选择简单处理函数*/{gtk_widget_hide(game_speed[0]);/*隐藏其余难度值*/gtk_widget_hide(game_speed[1]);/*隐藏其余难度值*/speed=2;k=1;sign=g_timeout_add(op_speed[speed],function,data);/*创建定时器*/ gtk_widget_set_sensitive(game_speed[2],FALSE);/*当前难度不敏感*/ gtk_widget_set_sensitive(game_pause,TRUE);/*暂停|开始按钮有效*/ for(j=0;j<length;j++){gtk_widget_set_sensitive(snake[j],TRUE);gtk_widget_set_sensitive(food[j],TRUE);}for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],TRUE);/*使方向选择有效*/ }sleep(0.7);/*等待0.7S便于游戏者反应*/stop=0;/*开始游戏*/}void showwin(void)/*游戏通关处理函数*/{stop=1;for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],FALSE);/*方向键无效*/}gtk_widget_set_sensitive(game_pause,FALSE);/*暂停键失效*/sleep(0.3);/*离开0.3S*/gtk_widget_show(win);/*显示通关提示*/k=-1;}void showdeath(void)/*游戏失败处理函数*/{gtk_timeout_remove(sign);for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],FALSE);/*方向键无效*/}gtk_widget_set_sensitive(game_pause,FALSE);/*暂停键失效*/sleep(0.3);/*离开0.3S*/gtk_widget_show(death);/*显示失败提示*/k=-1;}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
qipan[1][4]='#';
printf("This is a game of a SNAKE.\nGOOD LUCK TO YOU !\n");
printf("Input your game speed,please.(e.g.300)\n");
scanf("%d",&gamespeed);
qipan[i][0]='|';
for(i=0;i<20;i++)
qipan[i][79]='|';
for(i=0;i<80;i++)
qipan[19][i]='_';
qipan[1][1]=qipan[1][2]=qipan[1][3]='*';//初始化蛇的位置
if(direction==80)
x=zuobiao[0][head]+1;y=zuobiao[1][head];
if(direction==75)
x=zuobiao[0][head];y=zuobiao[0][head]-1;
if(direction==77)
x=zuobiao[0][head];y=zuobiao[1][head]+1;
while(!kbhit()&&(timeover=clock()-start<=gamespeed));
if(timeover)
{
getch();
direction=getch();
}
else
direction=direction;
if(!(direction==72||direction==80||direction==75||direction==77))
if(x==0||x==18||y==78||y==0)
return 0;
if(qipan[x][y]!=' ')
return 0;
qipan[zuobiao[0][tail]][zuobiao[1][tail]]=' ';
tail=(tail+1)%80;
qipan[zuobiao[0][head]][zuobiao[1][head]]='*';
/*处理棋盘*/
char qipan[20][80];//定义棋盘
for(i=0;i<20;i++)
for(j=0;j<80;j++)
qipan[i][j]=' ';//初始化棋盘
for(i=0;i<80;i++)
qipan[0][i]='_';
for(i=0;i<20;i++)
int direction=77;
int gamespeed;
int timeover;
int change(char qipan[20][80],int zuobiao[2][80],char direction);
zuobiao[0][tail]=1;zuobiao[1][tail]=1;zuobiao[0][1]=1;zuobiao[1][1]=2;zuobiao[0][2]=1;zuobiao[1][2]=3;zuobiao[0][head]=1;zuobiao[1][head]=4;
{
return 0;
system("cls");
printf("GAME OVER!\n");
}
if(!change(qipan,zuobiao,direction))
{
direction='q';
system("cls");
printf("GAME OVER!\n");
head=(head+1)%80;
zuobiao[0][head]=x;
zuobiao[1][head]=y;
qipan[zuobiao[0][head]][zuobiao[1][head]]='#';
return 1;
}
while(direction!='q')
{
system("cls");
for(i=0;i<20;i++)//打印出棋盘
for(j=0;j<80;j++)
printf("%c",qipan[i][j]);
timeover=1;
start=clock(;
/*贪吃蛇*/
#include<stdio.h>
#include<time.h>
#include<conio.h>
#include<stdlib.h>
int head=3 ,tail=0;
int main()
{
int i,j,k=0;
int zuobiao[2][80];
long start;
}
}
return 0;
}
int change(char qipan[20][80],int zuobiao[2][80],char direction)
{
int x,y;
if(direction==72)
x=zuobiao[0][head]-1;y=zuobiao[1][head];
相关文档
最新文档