C语言最简洁的贪吃蛇源代码

合集下载

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);}。

vc贪吃蛇c语言代码

vc贪吃蛇c语言代码

vc贪吃蛇c语言代码#include "stdio.h"#include "stdio.h"#include "windows.h"#include "time.h"#include "setjmp.h"#define MAXNOD 500#define UP 1#define DOWN -1#define LEFT -2#define RIGHT 2#define YES 1#define NO 0jmp_buf retry;typedef struct{int x;int y;int status;}Food;typedef struct {int *px;int *py;int direction;int nodlen;int score;}Snack;int gotoxy(int x, int y){COORD cd;cd.X = x;cd.Y = y;returnSetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE ),cd); }void initialization(Snack *pss){system("color 0e");pss->px=(int *)malloc(MAXNOD*sizeof(int));pss->py=(int *)malloc(MAXNOD*sizeof(int));memset(pss->px,0,MAXNOD);memset(pss->py,0,MAXNOD);pss->px[0]=0;pss->py[0]=0;pss->px[1]=1;pss->py[1]=0;pss->direction=RIGHT;pss->nodlen=2;pss->score=0;}void getscoresys(Snack scr){gotoxy(68,7);cprintf("score: %d",scr.score);}int ctrltoi(char ctr){switch(ctr){case 'w':return UP;case 's':return DOWN;case 'a':return LEFT;case 'd':return RIGHT ;}}void boundary(){int cnt,y;gotoxy(15,3);for (cnt=0;cnt<45;cnt++) {cprintf("%c",4);}for (y=4;y<20;y++){gotoxy(15,y);cprintf("%c",219); gotoxy(59,y);cprintf("%c",219);}gotoxy(15,20);for (cnt=0;cnt<45;cnt++) {cprintf("%c",4);}gotoxy(68,9);cprintf("UP: W"); gotoxy(68,10);cprintf("DOWN: S");gotoxy(68,11);cprintf("LEFT: A");gotoxy(68,12);cprintf("RIGHT: D");gotoxy(68,14);cprintf("PAUSE: BLANK");gotoxy(68,15);cprintf("EXIT :ESC");}int isdead(Snack ts){int i;char select;for(i=0;i<ts.nodlen-1;i++)< p="">if((ts.px[i]==ts.px[ts.nodlen-1]&&ts.py[i]==ts.py[ts.nodlen-1])||((ts.px[ts.nodlen-1]<0))||(ts.px[ts.nodl en-1]>42)||(ts.py[ts.nodlen-1]<0)||(ts.py[ts.nodlen-1]>15)) {system("cls");gotoxy(15,12);cprintf("Game Over! Press ESC to exit, any other key to retry\a\n");flushall();select=getch();if(select==27) exit(0);system("cls");longjmp(retry,1);}void getfood(Snack s,Food *pf) {int i;cnt: do{pf->x=rand()%43;pf->y=rand()%16;for (i=0;i<s.nodlen;i++)< p=""> {if (s.px[i]==pf->x&&s.py[i]==pf->y) {goto cnt;}}break;}while(1);pf->status=YES;}int main(){Snack ss;Food foo;int i,j,dire;char ctrl;srand((unsigned)time(NULL)); setjmp(retry);initialization(&ss);getfood(ss,&foo);dogotoxy(foo.x+16,foo.y+4);if (foo.status==NO)getfood(ss,&foo);cprintf("%c",3);boundary();if(_kbhit()){ctrl=getch();if (ctrl=='w'||ctrl=='s'||ctrl=='a'||ctrl=='d') {dire=ctrltoi(ctrl);if(ss.direction==(0-dire)) ;elsess.direction=dire;}else if (ctrl==' ')system("pause");else if (ctrl==27)exit(0);}for (i=0;i<ss.nodlen-1;i++)< p="">{ss.px[i]=ss.px[i+1];ss.py[i]=ss.py[i+1];}switch(ss.direction){case UP:ss.py[ss.nodlen-1]=ss.py[ss.nodlen-1]-1;break;case DOWN:ss.py[ss.nodlen-1]=ss.py[ss.nodlen-1]+1;break;case LEFT:ss.px[ss.nodlen-1]=ss.px[ss.nodlen-1]-1;break;case RIGHT:ss.px[ss.nodlen-1]=ss.px[ss.nodlen-1]+1;}for(i=0;i<ss.nodlen;i++)< p="">{gotoxy(ss.px[i]+16,ss.py[i]+4);cprintf("%c",4);}isdead(ss);if (ss.px[ss.nodlen-1]==foo.x&&ss.py[ss.nodlen-1]==foo.y) { for (j=0;j<ss.nodlen;j++)< p="">{ss.px[ss.nodlen-j]=ss.px[ss.nodlen-j-1];ss.py[ss.nodlen-j]=ss.py[ss.nodlen-j-1];}ss.score +=10;ss.nodlen++;foo.status=NO;}getscoresys(ss);_sleep(199);system("cls");flushall();}while(1);}</ss.nodlen;j++)<> </ss.nodlen;i++)<> </ss.nodlen-1;i++)<> </s.nodlen;i++)<></ts.nodlen-1;i++)<>。

贪吃蛇 C语言代码

贪吃蛇 C语言代码
y=randno();
}
snake[x][y]=FOOD;
draw(snake);
/*---------------------------------------*/
/*--------控制的部分---------------------*/
while(judgeGO(snake))
}
if(x>0&&x<16&&y>0&&y<16)
{
if(a==0)
printf("█");
else printf("□");
return ;
}
}
void draw(int (*sna)[17])
draw(snake);
Sleep(100);
continue;
}
rightmove(snake);
draw(snake);
}
int randno()
{
srand(time(NULL)); //运用随机函数,取随机数,出现食物用
return rand()%15+1;
}
//判断游戏是否结束
bool judgeGO(int (*sna)[17])
{
int x,y,i=0,max=0,count=0;
while(!kbhit()&&key1!=77&&judgeGO(snake))
{
if(judgeF(snake,key))
{
draw(snake);
Sleep(100);

基于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;}}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||scenter x==sx&&scentery==sy){show=0;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,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,1,1,1,0,0,0,1,1,1,0,1,1,0,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:************************");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=(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; /****从第五个节点判断是否自杀************/ while(p5!=NULL){if(head->newx==p5->centerx&&head->newy==p5->cent ery){ 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;}。

vc贪吃蛇c语言代码

vc贪吃蛇c语言代码

#include "stdio.h"#include "stdio.h"#include "windows.h"#include "time.h"#include "setjmp.h"#define MAXNOD 500#define UP 1#define DOWN -1#define LEFT -2#define RIGHT 2#define YES 1#define NO 0jmp_buf retry;typedef struct{int x;int y;int status;}Food;typedef struct {int *px;int *py;int direction;int nodlen;int score;}Snack;int gotoxy(int x, int y){COORD cd;cd.X = x;cd.Y = y;return SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),cd); }void initialization(Snack *pss){system("color 0e");pss->px=(int *)malloc(MAXNOD*sizeof(int));pss->py=(int *)malloc(MAXNOD*sizeof(int));memset(pss->px,0,MAXNOD);memset(pss->py,0,MAXNOD);pss->px[0]=0;pss->py[0]=0;pss->px[1]=1;pss->py[1]=0;pss->direction=RIGHT;pss->nodlen=2;pss->score=0;}void getscoresys(Snack scr){gotoxy(68,7);cprintf("score: %d",scr.score);}int ctrltoi(char ctr){switch(ctr){case 'w':return UP;case 's':return DOWN;case 'a':return LEFT;case 'd':return RIGHT ;}}void boundary(){int cnt,y;gotoxy(15,3);for (cnt=0;cnt<45;cnt++){cprintf("%c",4);}for (y=4;y<20;y++){gotoxy(15,y);cprintf("%c",219);gotoxy(59,y);cprintf("%c",219);}gotoxy(15,20);for (cnt=0;cnt<45;cnt++){cprintf("%c",4);}gotoxy(68,9);cprintf("UP: W");gotoxy(68,10);cprintf("DOWN: S");gotoxy(68,11);cprintf("LEFT: A");gotoxy(68,12);cprintf("RIGHT: D");gotoxy(68,14);cprintf("PAUSE: BLANK");gotoxy(68,15);cprintf("EXIT :ESC");}int isdead(Snack ts){int i;char select;for(i=0;i<ts.nodlen-1;i++)if((ts.px[i]==ts.px[ts.nodlen-1]&&ts.py[i]==ts.py[ts.nodlen-1])||((ts.px[ts.nodlen-1]<0))||(ts.px[ts.nodl en-1]>42)||(ts.py[ts.nodlen-1]<0)||(ts.py[ts.nodlen-1]>15)){system("cls");gotoxy(15,12);cprintf("Game Over! Press ESC to exit, any other key to retry\a\n");flushall();select=getch();if(select==27) exit(0);system("cls");longjmp(retry,1);}}void getfood(Snack s,Food *pf){int i;cnt: do{pf->x=rand()%43;pf->y=rand()%16;for (i=0;i<s.nodlen;i++){if (s.px[i]==pf->x&&s.py[i]==pf->y){goto cnt;}}break;}while(1);pf->status=YES;}int main(){Snack ss;Food foo;int i,j,dire;char ctrl;srand((unsigned)time(NULL));setjmp(retry);initialization(&ss);getfood(ss,&foo);do{gotoxy(foo.x+16,foo.y+4);if (foo.status==NO)getfood(ss,&foo);cprintf("%c",3);boundary();if(_kbhit()){ctrl=getch();if (ctrl=='w'||ctrl=='s'||ctrl=='a'||ctrl=='d'){dire=ctrltoi(ctrl);if(ss.direction==(0-dire)) ;elsess.direction=dire;}else if (ctrl==' ')system("pause");else if (ctrl==27)exit(0);}for (i=0;i<ss.nodlen-1;i++){ss.px[i]=ss.px[i+1];ss.py[i]=ss.py[i+1];}switch(ss.direction){case UP:ss.py[ss.nodlen-1]=ss.py[ss.nodlen-1]-1;break;case DOWN:ss.py[ss.nodlen-1]=ss.py[ss.nodlen-1]+1;break;case LEFT:ss.px[ss.nodlen-1]=ss.px[ss.nodlen-1]-1;break;case RIGHT:ss.px[ss.nodlen-1]=ss.px[ss.nodlen-1]+1;}for(i=0;i<ss.nodlen;i++){gotoxy(ss.px[i]+16,ss.py[i]+4);cprintf("%c",4);}isdead(ss);if (ss.px[ss.nodlen-1]==foo.x&&ss.py[ss.nodlen-1]==foo.y) {for (j=0;j<ss.nodlen;j++){ss.px[ss.nodlen-j]=ss.px[ss.nodlen-j-1];ss.py[ss.nodlen-j]=ss.py[ss.nodlen-j-1];}ss.score +=10;ss.nodlen++;foo.status=NO;}getscoresys(ss);_sleep(199);system("cls");flushall();}while(1);}。

超简单贪吃蛇c语言代码编写

超简单贪吃蛇c语言代码编写

超简单贪吃蛇c语言代码编写贪吃蛇其实就是实现以下几步——1:蛇的运动(通过“画头擦尾”来达到蛇移动的视觉效果)2:生成食物3:蛇吃食物(实现“画头不擦尾”)4:游戏结束判断(也就是蛇除了食物,其余东西都不能碰)#include<stdio.h>#include<stdlib.h>#include<windows.h>#include<conio.h>#include<time.h>#define width 60#define hight 25#define SNAKESIZE 200//蛇身的最长长度int key=72;//初始化蛇的运动方向,向上int changeflag=1;//用来标识是否生成食物,1表示蛇还没吃到食物,0表示吃到食物int speed=0;//时间延迟struct {int len;//用来记录蛇身每个方块的坐标int x[SNAKESIZE];int y[SNAKESIZE];int speed;}snake;struct{int x;int y;}food;void gotoxy(int x,int y)//调用Windows的API函数,可以在控制台的指定位置直接操作,这里可暂时不用深究{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }//■○void drawmap(){//打印图框for (int _y = 0; _y < hight; _y++){for (int x = 0; x < width; x+=2){if (x == 0 || _y == 0 || _y == hight - 1 || x == width - 2){gotoxy(x, _y);printf("■");}}}//打印蛇头snake.len=3;snake.x[0]=width/2;snake.y[0]=hight/2;gotoxy(snake.x[0],snake.y[0]);printf("■");//打印蛇身for(int i=1;i<snake.len;i++){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1]+1;gotoxy(snake.x[i],snake.y[i]);printf("■");}//初始化食物的位置food.x=20;food.y=20;gotoxy(food.x,food.y);printf("○");}/**控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*/void snake_move()//按键处理函数{int history_key=key;if (_kbhit()){fflush(stdin);key = _getch();key = _getch();}if(changeflag==1)//还没吃到食物,把尾巴擦掉{gotoxy(snake.x[snake.len-1],snake.y[snake.len-1]);printf(" ");}for(int i=snake.len-1;i>0;i--){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}if(history_key==72&&key==80)key=72;if(history_key==80&&key==72)key=80;if(history_key==75&&key==77)key=75;if(history_key==77&&key==75)key=77;switch(key){case 72:snake.y[0]--;break;case 75:snake.x[0]-= 2;break;case 77:snake.x[0]+= 2;break;case 80:snake.y[0]++;break;}gotoxy(snake.x[0],snake.y[0]);printf("■");gotoxy(0,0);changeflag=1;}void creatfood(){if(snake.x[0] == food.x && snake.y[0] == food.y)//只有蛇吃到食物,才能生成新食物{changeflag=0;snake.len++;if(speed<=100)speed+=10;while(1){srand((unsigned int) time(NULL));food.x=rand()%(width-6)+2;//限定食物的x范围不超出围墙,但不能保证food.x 为偶数food.y=rand()%(hight-2)+1;for(int i=0;i<snake.len;i++){if(food.x==snake.x[i]&&food.y==snake.y[i])//如果产生的食物与蛇身重合则退出break;}if(food.x%2==0)break;//符合要求,退出循环}gotoxy(food.x,food.y);printf("○");}}bool Gameover(){//碰到围墙,OVERif(snake.x[0]==0||snake.x[0]==width-2)return false;if(snake.y[0]==0||snake.y[0]==hight-1) return false;//蛇身达到最长,被迫OVERif(snake.len==SNAKESIZE)return false;//头碰到蛇身,OVERfor(int i=1;i<snake.len;i++){if(snake.x[0]==snake.x[i]&&snake.y[0]==snake.y[i])return false;}return true;}int main(){system("mode con cols=60 lines=27");drawmap();while(Gameover()){snake_move();creatfood();Sleep(350-speed);//蛇的移动速度}return 0;}。

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

(完整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  实现)
temp=T.body[i]; map[temp/100][temp%100]=-1; i++; i%=ML; } if(order=='w') { jud=order; //printf("-->w\n"); if(map[sum/100-1][sum%100]!=-1) {
for(i=T.tail;i!=T.head;) {
; }
if(kbhit()&&(order=getch(),order=='w'||order=='s'||order=='a'|| order=='d'))
{
sum=T.body[(T.head-1+ML)%ML]; system("CLS"); for(i=T.tail;i!=T.head;) {
jud=order; //printf("-->a\n"); if(map[sum/100][sum%100-1]!=-1) { for(i=T.tail;i!=T.head;) { temp=T.body[i]; map[temp/100][temp%100]=0; i++; i%=ML; }
aaa(); } else {
sum=T.body[i]; map[sum/100][sum%100]=-1; i++; i%=ML; } while(1) { sum=getnum(); if(map[sum/100][sum%100]==0) {
map[sum/100][sum%100]=1; break; } } for(i=T.tail;i!=T.head;) { sum=T.body[i]; map[sum/100][sum%100]=0; i++; i%=ML; } } else { T.body[T.head++]=sum; T.head%=ML; T.tail=(++T.tail)%ML; } } void sss() { int sum,i; sum=T.body[(T.head-1+ML)%ML]+100; if(map[sum/100][sum%100]==1) { T.length++; T.body[T.head++]=sum; T.head%=ML; map[sum/100][sum%100]=0; for(i=T.tail;i!=T.head;) { sum=T.body[i]; map[sum/100][sum%100]=-1; i++;

C语言写的简单贪吃蛇,vc6.0编译通过

C语言写的简单贪吃蛇,vc6.0编译通过

#include<iostream>using namespace std;#include<windows.h>#include<stdlib.h>#include<time.h>#define ssize 20#define vsize 40 //地图的水平和垂直尺寸#define SL 200int key=3,count=0,life=0,whefd=0,score=0,level=1;//k是控制键,count是时间延迟计数器,p死亡证明,m地图上是否有食物。

score是分数,level等级。

struct snake{int body[100][2],lenght,direction;} snake;struct map{ char pla[ssize][vsize];} map;void init_map(){ //初始化地图for(int i=0;i<ssize;i++)for(int j=0;j<vsize;j++){map.pla[i][j]=' ';}}void init_snake(){ //初始化蛇,初始长度为3,方向为右。

snake.lenght=3;for(int i=0;i<snake.lenght;i++){snake.body[0][0]=ssize/2;snake.body[0][1]=snake.lenght-1;map.pla[ssize/2][snake.lenght-1]='@';}snake.direction=3;}void print_map(){ //打印地图和蛇for(int i=-1;i<=ssize;i++){for(int j=-1;j<=vsize;j++){if((i==-1&&j==-1)||(i==ssize&&j==-1)||(j==vsize&&i==-1)||(j==vsize&&i==ssize))cout<<"+";else if(i==-1||i==ssize)cout<<"-";else if(j==-1||j==vsize)cout<<"|";elsecout<<map.pla[i][j];}cout<<endl;}}void dead(){life=1;}void food(){ //出现食物int x,y,k=1;while(k){x=rand()%ssize;y=rand()%ssize;if(map.pla[x][y]!='@'){map.pla[x][y]=14;k=0;whefd=1;}}}void move(){ //移动int x,y,n=0;x=snake.body[snake.lenght-1][0]; //记录蛇尾y=snake.body[snake.lenght-1][1];for(int i=snake.lenght-1;i>0;i--){ //将除蛇头外的每一节向前移动一位snake.body[i][0]=snake.body[i-1][0];snake.body[i][1]=snake.body[i-1][1];}if((key+snake.direction)!=5) //按键方向与当前方向相反则无效snake.direction=key; //按键方向有效时,改变蛇的方向。

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语言精简版

贪吃蛇c语言精简版

贪吃蛇c语言精简版//贪吃蛇#include<stdio.h>#include <windows.h>#include <stdlib.h>#include <time.h>#include <conio.h>struct all_xy{POINT point;struct all_xy *next;};int x=2,y=0,key,i,found_time;POINT save_point,save_point2,food_xy={20,10};BOOL end_self=FALSE,flag;struct all_xy *head=NULL,*node1,*node2;void gotoxy(int x, int y){COORD coord;coord.X = x,coord.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);}void snake_add(){for(node2=head;head!=NULL&&node2->next!=NULL;node2=node2->next);node1=(struct all_xy *)malloc(sizeof(struct all_xy));node1->point=(head==NULL?food_xy:node2->point);node1->next=NULL;if(head==NULL){head=node1;return;}else{for(node2=head;node2->next!=NULL;node2=node2->next);node2->next=node1;} }void make_food(long *x,long *y){for(found_time=0;found_time<500;found_time++){*x=(rand()%38+1)*2,*y=rand()%23+1;for(node1=head,flag=FALSE;node1!=NULL;node1=node1->next)if(*x==node1->point.x&&*y==node1->point.y){flag=TRUE;break;}if(!flag){gotoxy(*x,*y);printf("○");return;}}MessageBox(NULL,"已找不到空点放食物了,程序结束!","你太牛了!",MB_ICONASTERISK);exit(0);}int main(){for(i=0;i<3;i++)snake_add();for(srand(time(NULL)),make_food(&food_xy.x,&food_xy.y);;Sleep(400)){if(kbhit()){if((key=getch())==224)key=getch();switch(key){case 80:y!=-1?(x=0,y=1):printf("\a");break;case 72:y!=1?(x=0,y=-1):printf("\a");break;case 75:x!=2?(x=-2,y=0):printf("\a");break;case 77:x!=-2?(x=2,y=0):printf("\a");break;}}node2=head,node1=node2->next,save_point=node1->point;node1->point=node2->point,node1=node1->next;head->point.x+=x,head->point.y+=y;for(node2=head->next;node2!=NULL;node2=node2->next)//依次检查是否自己撞到自己if(node2->point.x==head->point.x&&node2->point.y==head->point.y)//如果发现头结点和任意一个结点的X Y相同则设置end_self的值并跳出{end_self=TRUE;break;}if(head->point.x<0||head->point.x>=78||head->point.y<0||head->point.y>=25| |end_self==TRUE){gotoxy(32,5);printf("游戏结束!");getch();return 0;}for(;node1!=NULL;node1=node1->next){save_point2=node1->point,node1->point=save_point;node2=node1,save_point=save_point2;}gotoxy(save_point.x,save_point.y);printf(" ");if(head->point.x==food_xy.x&&head->point.y==food_xy.y)snake_add(),make_food(&food_xy.x,&food_xy.y);for(node1=head;node1!=NULL;node1=node1->next)gotoxy(node1->point.x,node1->point.y),node1==head?printf("⊙"):printf("□");}}。

简单贪吃蛇c语言代码,一个C语言写简单贪吃蛇源代码.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;}。

贪吃蛇简易代码

贪吃蛇简易代码

#include<windows.h>#include "resource1.h"#include <stdio.h>#include <stdlib.h>#include <time.h>//蛇的结构体typedef struct SNAKE{int x;int y;struct SNAKE *pNext;}Snake;//豆的结构体typedef struct BEAN{int x;int y;struct BEAN *pNext;}Bean;//函数原型void CreateSnake(Snake **pSnake);void deleteAll(Snake **pSnake);void ShowSnake(Snake *pSnake);void CreateBean(Bean **pBean,Snake *pSnake);void ShowBean(Bean *pBean);void DeleteBean(Bean **pBean);void SnakeRun(Snake **pSnake);void SnakeGrowUp(Snake *pSnake);int CanEatBean(Snake *pSnake,Bean *pBean);int CanDie(Snake *pSnake);/////////////////////////////////////////////////////////////////////////////////////char g_ClassName[20] = "ClassName";LRESULT CALLBACK WndProc(HWND hwnd,UINT nMsg,WPARAM wParam,LPARAM lParam); HBITMAP hBitMap;int CALLBACK WinMain(HINSTANCE hInstance,HINSTANCE hPreInstance,LPSTR pCmdLine,int nCmdShow){HBRUSH hBrush = CreateSolidBrush(RGB(100,100,410));HICON hIcon = LoadIcon(hInstance,MAKEINTRESOURCE(IDI_wnd_icon));HICON hIconsm = LoadIcon(hInstance,MAKEINTRESOURCE(IDI_wnd_iconsm));hBitMap = LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_wdnbitmap));//设计类WNDCLASSEX wndClass;wndClass.cbClsExtra = NULL;wndClass.cbSize = sizeof(wndClass);wndClass.cbWndExtra = NULL;wndClass.hbrBackground = hBrush;wndClass.hCursor = LoadCursor(hInstance,IDC_ARROW);wndClass.hIcon = hIcon;wndClass.hIconSm = hIconsm;wndClass.hInstance = hInstance;wndClass.lpfnWndProc = WndProc;wndClass.lpszClassName = g_ClassName;wndClass.style = CS_HREDRAW|CS_VREDRAW;wndClass.lpszMenuName = NULL;//注册if (!RegisterClassEx(&wndClass)){MessageBox(NULL,"注册失败","消息",MB_OK);}//创建HWND hwnd = CreateWindow(g_ClassName,"贪吃蛇",WS_OVERLAPPEDWINDOW,200,50,600+16,600+38,NULL,NULL,hInstance,NULL);if (!hwnd){MessageBox(NULL,"创建失败!","消息",MB_OK);}//显示ShowWindow(hwnd,nCmdShow);//消息循环MSG msg;while (GetMessage(&msg,NULL,0,0)){TranslateMessage(&msg); //翻译DispatchMessage(&msg); //回调函数}return 0;}HDC dc = NULL;Bean *pBean = NULL;Snake *pSnake = NULL;int VK = VK_RIGHT;LRESULT CALLBACK WndProc(HWND hwnd,UINT nMsg,WPARAM wParam,LPARAM lParam) {switch (nMsg){case WM_CREATE:{CreateSnake(&pSnake); //创建蛇CreateBean(&pBean,pSnake);dc = GetDC(hwnd);}break;case WM_KEYDOWN:{switch (wParam){case VK_RETURN://按下后就开始SetTimer(hwnd,1,150,NULL);break;case VK_UP:VK = VK_UP;break;case VK_DOWN:VK = VK_DOWN;break;case VK_LEFT:VK = VK_LEFT;break;case VK_RIGHT:VK = VK_RIGHT;break;case ' ':KillTimer(hwnd,1);break;}break;}case WM_TIMER:{/*创建背景*/RECT rect;GetWindowRect(hwnd,&rect);HDC hmeDc = CreateCompatibleDC(dc);SelectObject(hmeDc,hBitMap);StretchBlt(dc,0,0,rect.right-rect.left,rect.bottom-rect.top,hmeDc,0,0,500,600,SRCCOPY);DeleteDC(hmeDc);/*背景创建结束*///各种函数if (CanDie(pSnake)){KillTimer(hwnd,1);MessageBox(NULL,"笨蛋,撞到自己身上,我死啦!","消息",MB_OK);}if ( CanEatBean(pSnake,pBean) ){SnakeGrowUp(pSnake);DeleteBean(&pBean);CreateBean(&pBean,pSnake);SnakeRun(&pSnake);}else{SnakeRun(&pSnake);}ShowSnake(pSnake);ShowBean(pBean);}case WM_PAINT:{/*创建背景*/RECT rect;GetWindowRect(hwnd,&rect);HDC hmeDc = CreateCompatibleDC(dc);SelectObject(hmeDc,hBitMap);StretchBlt(dc,0,0,rect.right-rect.left,rect.bottom-rect.top,hmeDc,0,0,500,600,SRCCOPY);/*背景创建结束*/ShowSnake(pSnake); //显示蛇ShowBean(pBean); //显示豆DeleteDC(hmeDc);break;}case WM_CLOSE:deleteAll(&pSnake);DeleteBean(&pBean);DestroyWindow(hwnd);break;case WM_DESTROY:ReleaseDC(hwnd,dc);PostQuitMessage(0);break;case WM_QUIT:break;}return DefWindowProc(hwnd,nMsg,wParam,lParam);}/////////////////////////////////函数/////////////////////////////////////////////////////////////创建蛇Create Snake()void CreateSnake(Snake **pSnake){Snake *u = NULL,*w = NULL;int i = 3; //开始的蛇有三截int x = 0; //蛇头的初始位置int y = 0; //蛇尾的初始位置while (i--){u = (Snake *)malloc(sizeof(Snake));u->pNext = NULL;u->x = x;u->y = y;x +=20;if (NULL == *pSnake){*pSnake = u;}else{w->pNext = u;}w = u;}/*蛇的三届创建完毕*/}//创建豆void CreateBean(Bean **pBean,Snake *pSnake){Snake *ji;int x = 0; //随机的位置x坐标int y = 0; //随机的位置y坐标srand(time(NULL));x = ((unsigned)rand()%29)*20;y = ((unsigned)rand()%29)*20;ji = pSnake;while(pSnake){if ((x == pSnake->x) && (y == pSnake->y) ){x = ((unsigned)rand()%29)*20;y = ((unsigned)rand()%29)*20;pSnake = ji;}pSnake = pSnake->pNext;}Bean *u;u = (Bean *)malloc(sizeof(Bean));u->pNext = NULL;u->x = x;u->y = y;*pBean = u;}//删掉全部蛇void deleteAll(Snake **pSnake){Snake *del;while(*pSnake){del = *pSnake;(*pSnake) = (*pSnake)->pNext;free(del);}}//删掉豆void DeleteBean(Bean **pBean){free(*pBean);*pBean = NULL;}//显示蛇void ShowSnake(Snake *pSnake){while (pSnake){Rectangle(dc,pSnake->x,pSnake->y,pSnake->x+20,pSnake->y+20);pSnake = pSnake->pNext;}}//显示豆void ShowBean(Bean *pBean){Rectangle(dc,pBean->x,pBean->y,pBean->x+20,pBean->y+20);}//贪吃蛇移动void SnakeRun(Snake **pSnake){Snake *ji, //记录变化的蛇头*round; //循环遍历int x, //蛇头的当前位置x坐标y; //蛇头的当前位置y坐标ji = *pSnake;round = *pSnake;while (round->pNext){round = round->pNext;}x = round->x;y = round->y;switch(VK){case VK_UP:if (y == 0){y = 600;}y -=20;break;case VK_DOWN:if (y==600){y = 0;}y +=20;break;case VK_LEFT:if (x == 0){x = 600;}x -= 20;break;case VK_RIGHT:if (x == 600){x = 0;}x +=20;break;}*pSnake = (*pSnake)->pNext;ji->x = x;ji->y = y;ji->pNext = NULL;round->pNext = ji;}//下一步能吃到豆吗? 返回1吃到int CanEatBean(Snake *pSnake,Bean *pBean){while (pSnake->pNext){pSnake = pSnake->pNext;}if ((pSnake->x==pBean->x)&&(pSnake->y==pBean->y)) {return 1;}return 0;}//长大void SnakeGrowUp(Snake *pSnake){Snake *u;u = (Snake *)malloc(sizeof(Snake));u->pNext = NULL;u->x = pBean->x;u->y = pBean->y;while(pSnake->pNext){pSnake = pSnake->pNext;}pSnake->pNext = u;}//蛇会死吗返回1会死int CanDie(Snake *pSnake){Snake *ji = NULL;int x = 0,y = 0;ji = pSnake;while (pSnake->pNext){pSnake = pSnake->pNext;}x = pSnake->x;y = pSnake->y;switch(VK){case VK_UP:y -=20;break;case VK_DOWN:y +=20;break;case VK_LEFT:x -= 20;break;case VK_RIGHT:x +=20;break;}while(ji->pNext){if ((x == ji->x) && (y == ji->y)){return 1;}ji = ji->pNext;}return 0;}(范文素材和资料部分来自网络,供参考。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
getch();
for(i=0;i<30000;i++)
{
move(&body[0]);
getdirection();
flag=eatfood();
if(flag==TRUE){print();makefood();};
print();
body[i].y=body[i-1].y;
}
body[0].x++;
}
void down()
{int i;
for(i=snakelength-1;i>0;i--)
{body[i].x=body[i-1].x;
body[i].y=body[i-1].y;
case VK_DOWN: if(body[0].direction!=UP)body[0].direction=DOWN;break;
case VK_LEFT: if(body[0].direction!=RIGHT)body[0].direction=LEFT;break;
case VK_ESC: exit(0);
{
food.x=random(20);
food.y=random(20);
}
else break;
}
food.direction=body[0].direction;
board[food.y][food.x]=2;
}
int eatfood()
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() /*在屏幕上显示蛇*/
key=bioskey(0);
switch(key)
{case VK_UP: if(body[0].direction!=DOWN)body[0].direction=UP;break;
case VK_RIGHT: if(body[0].direction!=LEFT)body[0].direction=RIGHT;break;
for(i=snakelength-1;i>0;i--){body[i].x=body[i-1].x;body[i].y=body[i-1].y;}
body[0].x=food.x;
body[0].y=food.y;
food.x=0;
food.y=0;
for(j=0;j<second;j++)delay(200);
}
line(0,0,400,400);
getch();
}
void right()
{int i;
for(i=snakelength-1;i>0;i--)
{body[i].x=body[i-1].x;
bar(j*15,i*15,j*15+13,i*15+13);
}
}
}
main(int second=0)
{
int gdriver=CGAC0,gmode;
initgraph(&gdriver,&gmode,"c:\\tc\\bgi");/*BGI文件夹的路径,我的是c:\tc\bgi,这里得自己改下*/
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();
#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
}
if(board[i][j]==0)
{setfillstyle(SOLID_FILL,BLACK);
bar(j*15,i*15,j*15+13,i*15+13);
}
if(board[i][j]==2)
{setfillstyle(SOLID_FILL,RED);
{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].x;
y=body[i].y;
board[y][x]=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
{int i=FALSE;
int x=body[0].x,y=body[0].y;
if(body[0].direction==UP&&board[y-1][x]==2)
{ snakelength++;
for(i=snakelength-1;i>0;i--){body[i].x=body[i-1].x;body[i].y=body[i-1].y;}
i=TRUE;
}
if(body[0].direction==LEFT&&board[y][x-1]==2)
{ snakelength++;
for(i=snakelength-1;i>0;i--){body[i].x=body[i-1].x;body[i].y=body[i-1].y;}
randomize();
int i,j;
int flag;
long time=100000;
for(i=0;i<21;i++)
for(j=0;j<21;j++)
board[i][j]=0;
for(i=0;i<22;i++)
{board[0][i]=1;board[21][i]=1;board[i][0]=1;board[i][21]=1;}
i=TRUE;
}
return i;
}
snakelength=3;
body[0].x=3,body[0].y=2,body[0].direction=RIGHT;
body[1].x=2,body[1].y=2;
body[2].x=1,body[2].y=2;
makefood();
print();
{int i;
for(i=snakelength-1;i>0;i--)
{body[i].x=body[i-1].x;
body[i].y=body[i-1].y;
}
body[0].y--;
}
void getdirection()
{int key=0;
if(bioskey(1)!=0)
board[food.y][food.x]=2;
for(i=1;i<21;i++)
for(j=1;j<21;j++)
{if(board[i][j]==1)
{setfillstyle(SOLID_FILL,WHITE);
bar(j*15,i*15,j*15+13,i*15+13);
}
body[0].y++;
}
void left()
{int i;
for(i=snakelength-1;i>0;i--)
{body[i].x=body[i-1].x;
body[i].y=body[i-1].y;
}
body[0].x--;
}
void up()
void makefood();/*产生一个食物*/
int eatfood(); /*蛇吃掉食物*/
void right(); /*上下左右的函数了*/
void down();
void left();
void up();
void getdirection(); /*判断蛇的方向*/
for(i=snakelength-1;i>0;i--){body[i].x=body[i-1].x;body[i].y=body[i-1].y;}
body[0].x=food.x;
body[0].y=food.y;
food.x=0;
相关文档
最新文档