c语言贪吃蛇源代码VC运行
C语言小游戏源代码《贪吃蛇》
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语言源代码
#include <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语言代码
#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语言贪吃蛇代码适合VC6.0
#include<stdio.h>#include<stdlib.h>#include<time.h>#include<conio.h>typedef struct snake{int a;int b;struct snake *u;struct snake *n;}snake,*snake1;typedef struct food{int a;int b;}food;void main(){char c,c0 = 'd';int i,j,k,n=1,t,at;snake p,q;snake *dd,*dd0,*dd1,*dd2; food f;srand(time(NULL));p.u = NULL;p.n = &q;p.a = 5;p.b = 6;q.a = 5;q.b = 5; q.u = &p;q.n = NULL;dd=dd2= &q;f.a=(rand()%15+1);f.b=(rand()%15+1);while(1){srand(time(NULL));system("cls");for(i = 0;i < 17;i ++){for(j = 0; j < 17;j++){if(i == 0 )printf("▁");else if(i == 16)printf("▔");else if(j == 0)printf("▕");else if(j == 16)printf("▏");else if(i == p.a && j == p.b) printf("■");else if(i == f.a && j == f.b) printf("★");else{t = 0;dd = dd2;for(k = 0; k < n ;k++){if(i == dd->a && j == dd->b) {printf("□");t = 1;break;}dd = dd->u;}if(t == 0)printf(" ");}}printf("\n");}at = 0;dd =dd2;for(i=0;i<n;i++){if(p.a == dd->a && p.b == dd->b) {printf("game over!!\n");exit(0);}dd = dd->u;}if(p.a == f.a && p.b == f.b){dd = dd2;at =1;f.a = (rand()%15+1);f.b = (rand()%15+1);for(i=0;i<n;i++){if(f.a == dd->a && f.b == dd->b){f.a = dd2->a;f.b = dd2->b;break;}}n++;}if(kbhit()){c = getch();dd = dd2;if(c == 'w' && c0 != 's'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b; dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}if(p.a == 1)p.a = 15;elsep.a = (p.a-1)%15;}else if(c == 's' && c0 != 'w'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b; dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}p.a = (p.a%15)+1;}else if(c == 'a' && c0 != 'd'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake));dd0->a = dd2->a;dd0->b = dd2->b; dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}if(p.b == 1)p.b = 15;elsep.b = (p.b-1)%15;}else if(c == 'd' && c0 != 'a'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b; dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}p.b = (p.b%15)+1;}else{goto qq;}c0 = c;}else{qq: if(c0 == 'w'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b; dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}if(p.a == 1)p.a = 15;elsep.a=(p.a-1)%15;}else if(c0 == 's'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b; dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}p.a=(p.a%15)+1;}else if(c0 == 'a'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b; dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}if(p.b == 1)p.b = 15;elsep.b=(p.b-1)%15;}else if(c0 == 'd'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b;dd0->n = NULL;dd0->u = dd2; dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}p.b=(p.b%15)+1;}}fflush(stdin);dd = &q;_sleep(200);}}。
贪吃蛇的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();}。
贪吃蛇游戏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("加速将能得到更高的分数。
贪吃蛇(VC完美运行)
/*贪吃蛇小游戏,能在VC中完美运行适合C语言初学者学习参考*/# include <stdio.h># include <windows.h># include <string.h># include <conio.h># include <malloc.h># include <time.h># include <stdlib.h># define N 23char tail[2];char apple[2];int score[2];//光标移动函数void gotoxy(int x, int y){COORD pos;pos.X = x;pos.Y = y;HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);SetConsoleCursorPosition(hConsole, pos);}//数字图案颜色函数void color(int c){HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);SetConsoleTextAttribute(hConsole, c);}//产生食物函数void food(char ** snake, int * len){int i, a;while (1){a = 1;srand(time(NULL));apple[0] = rand() % (N - 2) + 1;apple[1] = rand() % (N - 2) + 1;for (i = 0; i < *len; i++)if (snake[i][0] == apple[0] && snake[i][1] == apple[1])a = 0;if (a == 1){gotoxy(apple[0] * 2, apple[1]);color(12);printf("★");gotoxy((N+7)*2, 12);printf("%d", (score[0]) * 10);gotoxy(0, N);return;}}}//读取记录的分数int File_in(){FILE *fp;fp = fopen("C:\\tcs.txt","a+");if(fp == NULL){gotoxy(N+18, N+2);printf("文件不能打开\n");exit(0);}if(fgetc(fp) != EOF)score[1] = fgetc(fp);elsescore[1] = 0;return 0;}//储存分数记录int File_out(){FILE *fp;if (score[1] > score[0] * 10){gotoxy(10,10);color(12);puts("闯关失败加油^-^");gotoxy(0,N);}else{if((fp = fopen("C:\\tcs.txt","w+")) == NULL){printf("文件不能打开\n");exit(0);}fputc(score[0]*10,fp);if(fputc(score[0]*10,fp)==EOF)printf("输出失败\n");gotoxy(10,10);color(12);puts("恭喜您打破记录!!!");gotoxy(0,N);}return 0;}//判断是否撞墙或碰到自己bool block(char ** snake, int *len){int i;if (snake[0][0] == 0 || snake[0][0] == N-1 || snake[0][1] == 0 || snake[0][1] == N-1 )return true;for (i = 2; i < *len; i++)if (snake[i][0] == snake[0][0] && snake[i][1] == snake[0][1]) return true;return false;}//初始化游戏界面void background(char **snake, int * len){int plate[N][N];int i, j;//snake数组赋值for (i = 0; i < *len; ++i)snake[i] = (char *)malloc(sizeof(char) * 2);for (i = 0; i < *len; ++i){snake[i][0] = N/2 ;snake[i][1] = N/2 + i;}//初始化游戏面板界面for (i = 0; i < N; i++)for (j = 0; j < N; j++){if (i == 0 || i == 22 || j == 0 || j == 22)*(*(plate+i)+j) = 1;else*(*(plate+i)+j) = 0;}for (i = 0; i < N; i++)for (j = 0; j < N; j++){if (*(*(plate+i)+j) == 1){gotoxy(i * 2, j);color(5);printf("□");}else if (*(*(plate+i)+j) == 0){gotoxy(i * 2, j);color(25);printf("■");}}printf("\n");//初始化蛇体位置gotoxy(snake[0][0] * 2, snake[0][1]);color(11);printf("◆");for (i = 1; i< *len; i++){gotoxy(snake[i][0] * 2, snake[i][1]);color(14);printf("●");gotoxy(0, N);}//初始化右侧积分界面File_in();score[0] = 0;gotoxy((N+2)*2, 4);color(7);printf("按键A,D,S,W控制方向");gotoxy((N+2)*2, 6);printf("按Esc 退出游戏,其他键暂停");gotoxy((N+2)*2, 10);color(10);printf("最高得分:%d", score[1]);gotoxy((N+2)*2, 12);printf("当前得分:");gotoxy(0, N);//调用函数,初始化食物food(snake, len);}//蛇体控制函数void control(char ch, char ** snake, int * len) {int i, a = 0;memcpy(tail, snake[(*len)-1], 2);for (i = (*len) - 1; i > 0; --i)memcpy(snake[i], snake[i-1], 2);switch (ch){case 'a':case 'A':--snake[0][0];break;case 'd':case 'D':++snake[0][0];break;case 'w':case 'W':--snake[0][1];break;case 's':case 'S':++snake[0][1];break;}if (snake[0][0] == apple[0] && snake[0][1] == apple[1]) {++(*len);++score[0];snake[(*len)-1] = (char *)malloc(sizeof(char) * 2);memcpy(snake[(*len)-1], tail, 2);food(snake, len);gotoxy(tail[0] * 2, tail[1]);color(14);printf("●");}else{gotoxy(tail[0] * 2, tail[1]);color(25);printf("■");}if (block(snake, len)){File_out();free(snake);getch();exit(0);}gotoxy(snake[1][0] * 2, snake[1][1]);color(14);printf("●");gotoxy(snake[0][0] * 2, snake[0][1]);color(11);printf("◆");gotoxy(0, N);}//过滤输入字符函数int judge(char ch){if (ch == 'a' || ch == 'A' || ch == 'd' || ch == 'D'|| ch == 'w' || ch == 'W'|| ch == 's' || ch == 'S')return 1;elsereturn 0;}//方向限制函数void direct(char ** snake, char * ch){if ( snake[0][1] < snake [1][1] )if (*ch == 's' || *ch == 'S')*ch ='w';if ( snake[0][1] > snake [1][1] )if (*ch == 'w' || *ch == 'W')*ch ='s';if ( snake[0][0] < snake [1][0] )if (*ch == 'd' || *ch == 'D')*ch ='a';if ( snake[0][0] > snake [1][0] )if (*ch == 'a' || *ch == 'D')*ch ='d';}//主函数int main (){char ch = 0;char ** snake;int len = 3;int a;snake = (char **)malloc(sizeof(int) * 100); //必须先赋值后使用background(snake, &len);while (ch != 27){if (kbhit()){gotoxy(0, N);ch = getche();}direct(snake, &ch);a = judge(ch);if (a){control(ch, snake, &len);if (score[0] <= 20)Sleep(200 - score[0]*8);elseSleep(40);}}File_out();free(snake);return 0;}。
彩版_贪吃蛇C语言版(VC++6.0中运行完美通过)
// (彩版——贪吃蛇代码)在vc++6.0 中运行通过~~// 本屌花了整整3天才弄透,然后自己小小改编了的贪吃蛇代码,// 特色在于可以自己输入初始蛇身长度,以及食物总数,// 二是可以加速、减速。
// 第一次挂代码,望对大家有微末帮助!!~//以下为运行效果图://好了,现在上源文件,,哈哈# include <stdio.h># include <stdlib.h># include <malloc.h># include <windows.h># include <conio.h># include <time.h># define ESC 27# define SPACE 32# define MAX_X 25# define MAX_Y 50int max_food;// 食物总数int length = 0;// 蛇身长度char sna_dir = 'd';// 蛇头方向char temp;int snaDir_x, snaDir_y;// 蛇头方向坐标clock_t now_time;// 取系统时钟double wait_time = 300;// 限制蛇的速度typedef struct Node// 结构体{int x;int y;struct Node *pNext;}NODE, *PNODE;typedef struct Queue// queue 队列{PNODE front;PNODE rear;}QUEUE, *PQUEUE;PQUEUE pSnake = (PQUEUE)malloc(sizeof(QUEUE));// 全局HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); //获取句柄void hideCursor()// 隐藏光标{CONSOLE_CURSOR_INFO cursor_info = {1, 0};SetConsoleCursorInfo(hConsole, &cursor_info);}void Setcolor(int color)// 实现彩色的函数{SetConsoleTextAttribute(hConsole, color);}void gotoxy(int x, int y)// 确定坐标{COORD loc;loc.X = y;loc.Y = x;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HAND LE), loc);}void destroy()// 销毁{PNODE p = pSnake->front;PNODE t = pSnake->front;while (NULL != p)//最后使pSnake->front 和p 都为NULL{p = p->pNext;free(t);t = p;}}void game_over()// 游戏结束{gotoxy(11, 20);destroy();printf("Game Over");system("pause>nul");exit(0);}void enqueue(int x, int y)// 进队{PNODE pNew = (PNODE)malloc(sizeof(NODE));pNew->x = x;pNew->y = y;pSnake->rear->pNext = pNew;pSnake->rear = pNew;pSnake->rear->pNext = NULL;length++;}void dequeue()// 出队{PNODE p = pSnake->front;pSnake->front = pSnake->front->pNext;pSnake->front->x = p->x;pSnake->front->y = p->y;free(p);length--;}void pri_sna_info()// 打印信息{int i;Setcolor(13);gotoxy(4, 58);printf("Length: %d",length);gotoxy(6, 58);printf("还差%d 就通关了~~!", max_food+1);for (i=51; i<80; i++){gotoxy(10, i);printf("-");}Setcolor(13);gotoxy(15, 58);printf("按1 加速");gotoxy(16, 58);printf("按2 减速");gotoxy(19, 58);printf("空格键暂停");gotoxy(20, 58);printf("ESC 退出");Setcolor(15);}void draw_wall()// 画墙{int i;for (i=1; i<MAX_Y; i++){gotoxy(0, i);printf("=");gotoxy(MAX_X, i);printf("=");}for (i=0; i<MAX_X+1; i++){gotoxy(i, 0);printf("|");gotoxy(i, MAX_Y);printf("|");}Setcolor(15);}void rand_food()// 随机产生食物并显示{PNODE p;while(1){pSnake->front->x = rand()%(MAX_X-1) + 1;pSnake->front->y = rand()%(MAX_Y-1) + 1;p = pSnake->front->pNext;while(NULL != p){if(pSnake->front->x==p->x && pSnake->front->y==p->y) break;elsep = p->pNext;}if(NULL == p)break;}max_food--;Setcolor(14);gotoxy(pSnake->front->x, pSnake->front->y);printf("@");fflush(stdout);Setcolor(15);}void judge()// 判断赢或继续或挂{PNODE p;p = pSnake->front->pNext;if (max_food+1 == 0){system("cls");Setcolor(13);gotoxy(11, 25);printf("==== 哈哈,你赢啦!!!====");system("pause>nul");exit(0);}while (pSnake->rear != p){if (pSnake->rear->x==p->x && pSnake->rear->y==p->y){game_over();}elsep = p->pNext;}if (p->x==pSnake->front->x && p->y==pSnake->front->y) {rand_food();pri_sna_info();}elsedequeue();}void clear_tail()// 清除蛇尾{PNODE p = pSnake->front->pNext;gotoxy(p->x, p->y);printf(" ");}void print_sna()// 打印蛇{PNODE p = pSnake->front->pNext;int color;Setcolor(0xe);gotoxy(p->x, p->y);printf("z");while (pSnake->rear != p){color = rand()%15 + 1;if(color == 14)color -= rand()%13 + 1;Setcolor(color);p = p->pNext;gotoxy(p->x, p->y);printf("r");}Setcolor(0xf);gotoxy(p->x, p->y);printf("o");Setcolor(15);}void head(char c)// 蛇头方向{int x;char ch = 0;PNODE p = pSnake->front->pNext;while (pSnake->rear != p)p = p->pNext;if (c == 32){x = 1;gotoxy(11, 20);printf("--Pause--");while (ch != 32){ch = getch();}c = temp;gotoxy(11, 20);printf(" ");}if (x == 1)c = temp;if (temp=='a'&&c=='d' || temp=='d'&&c=='a' || temp=='s'&&c=='w' || temp=='w'&&c=='s')// 避免按与当前方向相反的键而挂掉,也就是增强游戏健壮性了c = temp;if (c!='a' && c!='w' && c!='d' && c!='s' && c!=27)c = temp;switch (c){case 'a':sna_dir = 'a';snaDir_x = p->x;snaDir_y = p->y - 1;if (snaDir_y < 1)game_over();break;case 's':sna_dir = 's';snaDir_x = p->x + 1;snaDir_y = p->y;if (snaDir_x == MAX_X)game_over();break;case 'w':sna_dir = 'w';snaDir_x = p->x - 1;snaDir_y = p->y;if (snaDir_x < 1)game_over();break;case 'd':sna_dir = 'd';snaDir_x = p->x;snaDir_y = p->y + 1;if (snaDir_y == MAX_Y)game_over();break;default:break;}enqueue(snaDir_x, snaDir_y); if (c == 27){system("cls");gotoxy(11, 35);printf("退出成功");system("pause>nul");exit(0);}}void move_sna()// 蛇的移动,,{if (kbhit())//这个函数去百度下就知道了——判断键盘是否有输入{temp = sna_dir;sna_dir = getch();if (sna_dir == '1'){sna_dir = temp;if (wait_time >= 50)wait_time -= 50;}if (sna_dir == '2'){sna_dir = temp;if (wait_time <= 800)wait_time += 50;}head(sna_dir);}else{head(sna_dir);}judge();print_sna();}void con_sna()// 控制蛇{if (clock()-now_time >= wait_time) // 通过wait_time控制蛇的速度{clear_tail();move_sna();now_time = clock();}}void init() // 这个是初始化,大家都知道的{int i;int len;system("title orrrrrrrrrrrrz——膜拜");system("mode con: cols=80 lines=26");PNODE (pSnake->front) = (PNODE)malloc(sizeof(NODE));pSnake->rear = pSnake->front;Setcolor(13);gotoxy(11, 20);printf("You Can Set The Length Of Your Snake: ");scanf("%d", &len);system("cls");gotoxy(11, 10);printf("You Can Set The Number Of Customs Clearance Of Foods: ");scanf("%d", &max_food);system("cls");Setcolor(15);hideCursor();// 隐藏光标for (i=0; i<len; i++){enqueue(11, i+20);}draw_wall();rand_food();pri_sna_info();}int main(void){init();srand((unsigned)time(NULL));// 随机函数,为rand()函数服务的,一样的,去百度这个函数~~now_time = clock();while (1){con_sna();}return 0;}。
贪吃蛇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语言源代码
#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;}。
贪吃蛇源代码(需要easy x,vc6.0可以成功编译运行)
#include <graphics.h>#include <stdlib.h>#include <time.h>//#include <dos.h>#include <conio.h>#include <stdio.h>//#include <winnt.h>#define MAX_JOINTS 200#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011b#define MV_RIGHT 1#define MV_LEFT 2#define MV_UP 3#define MV_DOWN 4void InitGraph(void); /*图形驱动初始化函数*/void DrawFence(void); /*绘制游戏场景*/void GameOver(int score); /*结束游戏*/void GamePlay(void); /*玩游戏具体过程*/void PrScore(int score); /*输出成绩*/struct Food /*食物的结构体定义*/{int x; /*食物的横坐标*/int y; /*食物的纵坐标*/int addFood; /*判断是否要出现食物的变量*/};struct Snake /*蛇的结构体定义*/{int x[MAX_JOINTS]; /*保存蛇身每一节位于屏幕上的列坐标*/ int y[MAX_JOINTS]; /*保存蛇身每一节位于屏幕上的行坐标*/ int joint; /*蛇的节数*/int direction; /*蛇移动方向*/int life; /*蛇的生命,0活着,1死亡*/};/*主函数*/void main(void){InitGraph(); /*图形驱动*/DrawFence(); /*游戏场景*/GamePlay(); /*玩游戏具体过程*/closegraph(); /*图形结束*/}/*图形驱动初始化函数*/void InitGraph(void){int gd = DETECT, gm;initgraph(&gd, &gm, "");cleardevice();setbkcolor(BLUE);cleardevice();setcolor(WHITE);//settextstyle(DEFAULT_FONT, HORIZ_DIR, 3);setfont(32, 0, "宋体");outtextxy(170, 150, "Greedy Snake");outtextxy(219, 254, "Ready?");setcolor(BLUE);cleardevice();}/*游戏开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/ void DrawFence(void){int i;setbkcolor(LIGHTGREEN);setcolor(11);//setlinestyle(SOLID_LINE, 0, THICK_WIDTH);setlinestyle(PS_SOLID, 0, 3);/*画围墙*/for (i=50; i<=600; i+=10){rectangle(i, 40, i+10, 49); /*上边*/rectangle(i, 451, i+10, 460); /*下边*/}for (i=40; i<=450; i+=10){rectangle(50, i, 59, i+10); /*左边*/rectangle(601, i, 610, i+10); /*右边*/}}/*控制贪吃蛇吃食物*/void GamePlay(void){int i, key;//int gamespeed = 22000; /*控制游戏速度*/int gamespeed = 200;int score = 0; /*记录游戏得分*/struct Food food; /*食物结构体变量*/struct Snake snake; /*蛇结构体变量*/food.addFood = 1; /*1表示需要出现新食物,0表示已经存在食物*/ snake.life = 0; /*置蛇的生命状态为活着*/snake.direction = MV_RIGHT; /*置蛇头方向往右*/snake.x[0] = 100; snake.y[0] = 100; /*置蛇头初始位置*/snake.x[1] = 110; snake.y[1] = 100;snake.joint = 2; /*置蛇的初始节数为2*/PrScore(score); /*显示游戏得分*//*重复玩游戏,直到按Esc键结束*/srand(time(NULL));while (1){while (!kbhit())/*在没有按键的情况下,蛇自己移动身体*/{if (food.addFood == 1) /*需要出现新食物*/{food.x = rand() % 400 + 60;food.y = rand() % 350 + 60;/*食物出现后必须在整格内才能让蛇吃到*/while (food.x%10 != 0){food.x++;}while (food.y%10 != 0){food.y++;}food.addFood = 0; /*画面上有食物*/}if (food.addFood == 0) /*画面上有食物,则显示*/{setcolor(GREEN);rectangle(food.x, food.y, food.x+10, food.y-10);}for (i=snake.joint-1; i>0; i--) /*蛇的每个节往前移动*/{snake.x[i] = snake.x[i-1];snake.y[i] = snake.y[i-1];}/*1,2,3,4 表示右,左,上,下四个方向,来决定蛇头的移动*/switch(snake.direction){case MV_RIGHT: snake.x[0] += 10; break;case MV_LEFT: snake.x[0] -= 10; break;case MV_UP: snake.y[0] -= 10; break;case MV_DOWN: snake.y[0] += 10; break;}/*从蛇的第四节开始判断是否撞到自己,因为蛇头为两节,第三节不可能拐过来*/for (i=3; i<snake.joint; i++){if (snake.x[i]==snake.x[0] && snake.y[i]==snake.y[0]){GameOver(score); /*显示失败*/snake.life = 1; /*蛇死*/break;}}/*判断蛇是否撞到墙壁*/if (snake.x[0]<55 || snake.x[0]>595|| snake.y[0]<55 || snake.y[0]>455){GameOver(score); /*本次游戏结束*/snake.life = 1; /*蛇死*/}/*以上两种判断以后,如果蛇死就跳出内循环,重新开始*/if (snake.life == 1) break;if (snake.x[0]==food.x && snake.y[0]==food.y) /*吃到食物后*/{/*把画面上的食物清除*/setcolor(0);rectangle(food.x, food.y, food.x+10, food.y-10);/*新的一节先放在看不见的位置,下次循环就取前一节的位置*/snake.x[snake.joint] =-20; snake.y[snake.joint] =-20;snake.joint++; /*蛇的身体长一节*/food.addFood = 1; /*画面上需要出现新食物*/score += 10;PrScore(score); /*输出新得分*/}/*画蛇*/setcolor(4);for (i=0; i<snake.joint; i++){rectangle(snake.x[i], snake.y[i],snake.x[i]+10, snake.y[i]-10);}//delay(gamespeed); /*延时控制蛇的速度*/Sleep(gamespeed);/*去除蛇的最后一节*/setcolor(BLUE);rectangle(snake.x[snake.joint-1], snake.y[snake.joint-1],snake.x[snake.joint-1]+10,snake.y[snake.joint-1]-10);} /*end of while(!kbhit)*/if (snake.life == 1) break; /*如果蛇死,则跳出循环*///key = bioskey(0); /*接收按键*/key = getch();/*if (kbhit()){key = getch();}*//*判断按键,是否往相反方向移动,按Esc键则退出*/ /* if (key == ESC) break;else if (key==UP && snake.direction!=4)snake.direction = MV_UP;else if (key==RIGHT && snake.direction!= MV_LEFT)snake.direction = MV_RIGHT;else if (key==LEFT && snake.direction!= MV_RIGHT)snake.direction = MV_LEFT;else if (key==DOWN && snake.direction!= MV_UP)snake.direction = MV_DOWN;*/if (key == ESC) break;else if (key=='W' && snake.direction!=4)snake.direction = MV_UP;else if (key=='D' && snake.direction!= MV_LEFT)snake.direction = MV_RIGHT;else if (key=='A' && snake.direction!= MV_RIGHT)snake.direction = MV_LEFT;else if (key=='S' && snake.direction!= MV_UP)snake.direction = MV_DOWN;} /*end of while(1)*/ }/*结束游戏*/void GameOver(int score){cleardevice();PrScore(score);setcolor(RED);//settextstyle(0, 0, 4);setfont(60, 0,"黑体");outtextxy(200, 200, "GAME OVER");getch();}/*输出成绩*/void PrScore(int score){char str[10];setfillstyle(SOLID_FILL, YELLOW);bar(50, 15, 220, 35);setcolor(6);//settextstyle(0, 0, 2);setfont(16, 0,"宋体");sprintf(str, "score:%d", score);outtextxy(55, 20, str);}。
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语言编写贪吃蛇(附源码,无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语言版贪食蛇游戏源代码(我自己写的)热1已有58 次阅读2011-01-18 17:57#include <stdio.h>#include <windows.h>#include <conio.h>#include <string.h>#define UP 0#define DOWN 1#define LEFT 2#define RIGHT 3//宏定义,定义四个方向--0 1 2 3分别代表上下左右#define TURN_NUM 1000//可以保存的最多转弯次数,一条蛇同时最多只能有1000次的弯曲#define INIT_LENGTH 8#define UP_EDGE 0#define DOWN_EDGE 24#define LEFT_EDGE 0#define RIGHT_EDGE 79//定义上下左右四个边界#define X 0//初始状态下蛇的身体坐标(LEFT_EDGE+X,UP_EDGE+Y)#define Y 0//决定初始状态下蛇的身体相对于游戏界面原点(LEFT_EDGE,UP_EDGE)的位置/*定义全局变量*/char buf[1000]="@*******";//决定初始的snake_length的值:必须与INIT_LENGTH保持同步char *snake=buf;//蛇的身体,最长有1000个环节char FOOD='$';//记录食物的形状int food_num=0;//记录已经吃下的食物数量int score=0;//记录当前的得分,由food_num决定int snake_length=INIT_LENGTH;//initializer is not a constant:strlen(snake); int cursor[2]={LEFT_EDGE+20+INIT_LENGTH,UP_EDGE+10};//记录当前光标所指位置int head[2]={LEFT_EDGE+20+INIT_LENGTH-1,UP_EDGE+10};//记录头部的坐标int tail[2]={0,0};//记录尾巴的坐标int old_tail[2];//记录上一步尾巴所在位置int food[2]={0,0};//记录食物的坐标int init_position[2]={LEFT_EDGE+X,UP_EDGE+Y};//蛇的初始位置int direction=RIGHT;//记录当前蛇的头部的运动方向int turn_point[TURN_NUM][2];int head_turn_num=0;//记录头部的转弯次数int tail_turn_num=0;//记录尾巴的转弯次数int game_over=0;//判断游戏是否结束/*主方法*/void main(){//函数声名void gotoxy(int x,int y);//移动光标的位置void cur_state();//测试游戏的当前状态参数void print_introduction();//打印游戏规则void init();//初始化游戏void control();//接收键盘控制命令void move();//控制身体的运动void move_up();//向上运动void move_down();//向下运动void move_left();//向左运动void move_right();//向右运动void update_tail_position();//更新尾巴的坐标void generate_food();//随机产生食物void eat_food();//吃下食物char ch;while(!game_over){print_introduction();printf("\t\t按任意键开始游戏");getch();system("cls");//cur_state();init();control();system("cls");gotoxy(0,10);printf("\t\t您的当前得分是%d\n",score);printf("\t\t这条蛇共转了%d次弯,它的身体长度是%d\n",head_turn_num,strlen(snake));printf("\t\t游戏结束,您要再玩一局吗?(y/n)");scanf("%c",&ch);getchar();if(ch=='y'||ch=='Y'){continue;}else{system("cls");printf("\n\n\n\t\t\t谢谢您的使用,再见!");_sleep(3000);game_over=1;}}}/*打印游戏规则*/void print_introduction(){int i=0;int rule_num;char *rule[4];rule[i++]="\n\n\t\t\t欢迎您来玩贪食蛇游戏\n";rule[i++]="\t\t游戏规则如下:\n";rule[i++]="\t\t1.按上下左右键控制蛇的运动方向\n";rule[i++]="\t\t2.按Ctrl+C结束当前游戏\n";rule_num=i;system("cls");for(i=0;i<rule_num;i++){puts(rule[i]);}}/*移动光标的位置*/void gotoxy(int x,int y){COORD coord={x,y};SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord); }/*测试游戏的当前状态参数*/void cur_state(){printf("游戏的当前状态参数如下:\n");printf("snake=%s\n",snake);printf("snake_body_length=%d\n",strlen(snake));printf("head=(%d,%d)\n",head[0],head[1]);printf("tail=(%d,%d)\n",tail[0],tail[1]);printf("direction=%d\n",direction);printf("game_over=%d\n",game_over);}/*游戏进入初始状态*/void init(){int i;/*初始化游戏参数*/food_num=0;//记录已经吃下的食物数量score=0;//记录当前的得分,由food_num决定snake_length=INIT_LENGTH;cursor[0]=init_position[0]+INIT_LENGTH;cursor[1]=init_position[1];//记录当前光标所指位置head[0]=init_position[0]+INIT_LENGTH-1;head[1]=init_position[1];//记录头部的坐标tail[0]=init_position[0];tail[1]=init_position[1];//记录尾巴的坐标direction=RIGHT;//记录当前蛇的头部的运动方向head_turn_num=0;//记录头部的转弯次数tail_turn_num=0;//记录尾巴的转弯次数game_over=0;//判断游戏是否结束turn_point[0][0]=RIGHT_EDGE;turn_point[0][1]=0;/*游戏参数初始化完毕*/generate_food();//投下第一粒食物gotoxy(init_position[0],init_position[1]);//将光标移动到到初始化位置for(i=snake_length;i>0;i--){putchar(snake[i-1]);}}/*接收键盘控制命令*/void control(){char command;//存放接收到命令while(1){command=getch();if(command==-32){//F11,F12:-123,-122command=getch();if(command=='H' && (direction==LEFT || direction==RIGHT)){//光标上移direction=UP;turn_point[head_turn_num%TURN_NUM][0]=head[0];turn_point[head_turn_num%TURN_NUM][1]=head[1];head_turn_num++;}else if(command=='P' && (direction==LEFT || direction==RIGHT)){//光标下移direction=DOWN;turn_point[head_turn_num%TURN_NUM][0]=head[0];turn_point[head_turn_num%TURN_NUM][1]=head[1];head_turn_num++;}else if(command=='K' && (direction==UP || direction==DOWN)){//光标左移direction=LEFT;turn_point[head_turn_num%TURN_NUM][0]=head[0];turn_point[head_turn_num%TURN_NUM][1]=head[1];head_turn_num++;}else if(command=='M' && (direction==UP || direction==DOWN)){//光标右移direction=RIGHT;turn_point[head_turn_num%TURN_NUM][0]=head[0];turn_point[head_turn_num%TURN_NUM][1]=head[1];head_turn_num++;}else if(command==-122 || command==-123);}else if(command==0){command=getch();//接收Fn的下一个字符//F1~F10:59~68}else if(command>=1&&command<=26){//Ctrl+a~z:1~26if(command==3){break;}}else{//do nothing!}move();if(head[0]==food[0] && head[1]==food[1]){eat_food();//吃掉一粒事物generate_food();//投下新食物}}}/*蛇的身体运动*/void move(){if(direction==UP){//printf("Moving up!\n");move_up();}else if(direction==DOWN){//printf("Moving down!\n");move_down();}else if(direction==LEFT){//printf("Moving left!\n");move_left();}else if(direction==RIGHT){//printf("Moving right!\n");move_right();}}/*向上运动*/void move_up(){if(cursor[1]>=UP_EDGE){gotoxy(head[0],head[1]);putchar('*');gotoxy(head[0],head[1]-1); putchar(snake[0]);gotoxy(tail[0],tail[1]);//_sleep(1000);//查看尾部光标putchar(0);update_tail_position();head[1]-=1;cursor[0]=head[0];cursor[1]=head[1]-1; gotoxy(cursor[0],cursor[1]); }else{gotoxy(head[0],head[1]);}}/*向下运动*/void move_down(){if(cursor[1]<=DOWN_EDGE){ gotoxy(head[0],head[1]); putchar('*');gotoxy(head[0],head[1]+1); putchar(snake[0]);gotoxy(tail[0],tail[1]);//_sleep(1000);//查看尾部光标putchar(0);update_tail_position();head[1]+=1;cursor[0]=head[0];cursor[1]=head[1]+1; gotoxy(cursor[0],cursor[1]); }else{gotoxy(head[0],head[1]);}}/*向左运动*/void move_left(){if(cursor[0]>=LEFT_EDGE){ gotoxy(head[0],head[1]); putchar('*');gotoxy(head[0]-1,head[1]); putchar(snake[0]);gotoxy(tail[0],tail[1]);//_sleep(1000);//查看尾部光标putchar(0);update_tail_position();head[0]-=1;cursor[0]=head[0]-1;cursor[1]=head[1];gotoxy(cursor[0],cursor[1]);}else{gotoxy(head[0],head[1]);}}/*向右运动*/void move_right(){if(cursor[0]<=RIGHT_EDGE){gotoxy(head[0],head[1]);putchar('*');putchar(snake[0]);gotoxy(tail[0],tail[1]);//_sleep(1000);//查看尾部光标putchar(0);update_tail_position();head[0]+=1;cursor[0]=head[0]+1;cursor[1]=head[1];gotoxy(cursor[0],cursor[1]);}else{gotoxy(head[0],head[1]);}}/*更新尾巴的坐标*/void update_tail_position(){old_tail[0]=tail[0];old_tail[1]=tail[1];//保存上次尾巴的位置if(tail[0]==food[0] && tail[1]==food[1]){gotoxy(tail[0],tail[1]);putchar(FOOD);}if(tail_turn_num<head_turn_num){if(tail[0]<turn_point[tail_turn_num%TURN_NUM][0]){tail[0]+=1;}else if(tail[0]>turn_point[tail_turn_num%TURN_NUM][0]){ tail[0]-=1;}else if(tail[1]<turn_point[tail_turn_num%TURN_NUM][1]){ tail[1]+=1;}else if(tail[1]>turn_point[tail_turn_num%TURN_NUM][1]){ tail[1]-=1;}else if(tail[0]==turn_point[(tail_turn_num-1)%TURN_NUM][0] && tail[1]==turn_point[(tail_turn_num-1)%TURN_NUM][1]){if(tail[0]<turn_point[tail_turn_num%TURN_NUM][0]){tail[0]+=1;}else if(tail[0]>turn_point[tail_turn_num%TURN_NUM][0]){tail[0]-=1;}else if(tail[1]<turn_point[tail_turn_num%TURN_NUM][1]){tail[1]+=1;}else if(tail[1]>turn_point[tail_turn_num%TURN_NUM][1]){tail[1]-=1;}}if(tail[0]==turn_point[tail_turn_num%TURN_NUM][0] && tail[1]==turn_point[tail_turn_num%TURN_NUM][1]){tail_turn_num+=1;}}else if(tail_turn_num==head_turn_num){if(tail[0]<head[0]){tail[0]+=1;}else if(tail[0]>head[0]){tail[0]-=1;}else if(tail[1]<head[1]){tail[1]+=1;}else if(tail[1]>head[1]){tail[1]-=1;}}}void generate_food(){int i=0,j=0;do{i=rand()%DOWN_EDGE;}while(i<UP_EDGE || i>DOWN_EDGE);do{j=rand()%DOWN_EDGE;}while(j<LEFT_EDGE || j>RIGHT_EDGE);food[0]=i;food[1]=j;gotoxy(food[0],food[1]);//抵达食物投放点putchar(FOOD);//放置食物gotoxy(cursor[0],cursor[1]);//返回光标当前位置}void eat_food(){if(tail[0]==turn_point[(tail_turn_num-1)%TURN_NUM][0] &&tail[1]==turn_point[(tail_turn_num-1)%TURN_NUM][1]){ tail_turn_num-=1;}snake[snake_length++]=snake[1];tail[0]=old_tail[0];tail[1]=old_tail[1];//将尾巴回退到上一步所在的位置gotoxy(tail[0],tail[1]);putchar(snake[1]);food_num++;score=food_num;gotoxy(cursor[0],cursor[1]);}。
简单贪吃蛇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语言编写)
贪吃蛇游戏代码(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 <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);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)}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,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++)}/******************主场景**********************/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);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;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();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(far3);free(far4);closegraph(); return 0;}。
贪吃蛇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;}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) /***********是否开始随机产生***************/{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,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=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;}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
return 0;
}
int Eat(char snake[2]) //吃了苹果
{
if ((snake[0] == apple[0]) && (snake[1] == apple[1]))
{
color(14);
printf("★");
color(11);
putchar('\n');
}
char** Move(char **snake, char dirx, int *len) //控制方向
{
int i, full = Eat(snake[0]);
case 'd': case 'D': ++snake[0][1]; break;
default: ;
}
if (full)
{
snake = (char **)realloc(snake, sizeof(char *) * ((*len) + 1));
apple[0] = apple[1] = apple[2] = 0;
gotoxy(N+44,10);
color(13);
printf("%d",score[0]*10);
gotoxy(N+30,8);
color(11);
printf("历史最高分为: ");
color(12);
gotoxy(N+44,8);
printf("%d",score[1]*10);
color(11);
memcpy(tail, snake[(*len)-1], 2);
for (i = (*len) - 1; i > 0; --i)
memcpy(snake[i], snake[i-1], 2);
switch (dirx)
}
int File_out() //存数据
{
ห้องสมุดไป่ตู้
FILE *fp;
if(score[1] > score[0])
{gotoxy(10,10);
color(12);
puts("闯关失败 加油耶");
{
gotoxy(snake[i][1] * 2, snake[i][0]);
printf("★");
}
putchar('\n');
*snake_x = snake;
gotoxy(apple[1] * 2, apple[0]);
color(12);
printf("●");
color(11);
}
gotoxy(tail[1] * 2, tail[0]);
/*这是一个贪吃蛇代码,运行环境VC++6.0(亲测完美运行)*/
/*该程序在dos系统下运行,不需要graphics.h头文件*/
/*该程序由C语言小方贡献,谢谢您的支持*/
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#define N 21
int apple[3];
char score[3];
char tail[3];
void gotoxy(int x, int y) //输出坐标
return snake;
}
void init(char plate[N+2][N+2], char ***snake_x, int *len) //初始化
{
int i, j;
char **snake = NULL;
{
HANDLE hConsole = GetStdHandle((STD_OUTPUT_HANDLE)) ;
SetConsoleTextAttribute(hConsole,b) ;
}
int Block(char head[2]) //判断出界
{
if ((head[0] < 1) || (head[0] > N) || (head[1] < 1) || (head[1] > N))
{
case 'w': case 'W': --snake[0][0]; break;
case 's': case 'S': ++snake[0][0]; break;
case 'a': case 'A': --snake[0][1]; break;
gotoxy(0, i);
for (j = 0; j < N + 2; ++j)
{
switch (plate[i][j])
{
snake[(*len)] = (char *)malloc(sizeof(char) * 2);
memcpy(snake[(*len)], tail, 2);
++(*len);
++score[0];
{
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void color(int b) //颜色函数
}
void Manual()
{
gotoxy(N+30,2);
color(10);
printf("按 W S A D 移动方向");
gotoxy(N+30,4);
printf("按 space 键暂停");
snake[i][1] = N/2 + 1 + i;
}
for (i = 1; i <= N; ++i)
for (j = 1; j <= N; ++j)
plate[i][j] = 1;
gotoxy(N+30,12);
printf("你现在得分为: 0");
}
int File_in() //取记录的分数
{
FILE *fp;
if((fp = fopen("C:\\tcs.txt","a+")) == NULL)
{
gotoxy(N+18, N+2);
printf("文件不能打开\n");
exit(0);
}
if((score[1] = fgetc(fp)) != EOF);
else
score[1] = 0;
return 0;
gotoxy(0,N+2);
return 0;
}
if((fp = fopen("C:\\tcs.txt","w+")) == NULL)
{
printf("文件不能打开\n");
case 0:
color(12);printf("□");color(11); continue;
case 1: printf("■"); continue;
if(score[3] < 16)
++score[3];
tail[2] = 1;
}
else
tail[2] = 0;
default: ;
}
}
putchar('\n');
}
for (i = 0; i < (*len); ++i)
*len = 3;
score[0] = score[3] =3;
snake = (char **)realloc(snake, sizeof(char *) * (*len));
for (i = 0; i < *len; ++i)
apple[0] = rand()%N + 1; apple[1] = rand()%N + 1;
apple[2] = 1;
for (i = 0; i < N + 2; ++i)
{
color(11);
return 1;
}
else
return 0;
}
void Draw(char **snake, int len) //蛇移动
{
if (apple[2]) {
snake[i] = (char *)malloc(sizeof(char) * 2);
for (i = 0; i < 3; ++i)
{
snake[i][0] = N/2 + 1;