C语言贪吃蛇源程序代码双人对抗

合集下载

创新C语言双人贪吃蛇小游戏

创新C语言双人贪吃蛇小游戏
snake[1]._COLOR = 2;
}
delimage(img);
}
void setfoodcrd()
{
food.crd.x = rand() % (600 / SNAKELEN) * SNAKELEN;
food.crd.y = rand() % (480 / SNAKELEN) * SNAKELEN;
void showfood();//在相应的坐标画出食物
void snakemove(struct SNAKE *p);//移动蛇,实际就是改变蛇各节的坐标
void judgeslod(struct SNAKE *p);//判断蛇是否撞墙或者撞到自己
void judgesef(struct SNAKE *p);//判断蛇是否吃到食物了
int _COLOR; //标记蛇的颜色
}snake[2];
int speed = SPEED;//方便以后在程序中改变速度
int mode_num;
int wall_1 = 100 , wall_2 = -165;
void init();//初始化游戏
void setfoodcrd();//设置食物要出现的坐标
putimage(0, 0, img);
if (!food.flag)
{
setfoodcrd();
}
for(p = snake, i = 0; i < mode_num; i++, p++)
snakemove(p);
PIMAGE img1 = newimage();
getimage(img1, "pic\\pool.jpg");
{

C语言小游戏源代码《贪吃蛇》

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

贪吃蛇游戏c语言源代码

贪吃蛇游戏c语言源代码

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

vc贪吃蛇c语言代码

vc贪吃蛇c语言代码

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

C语言贪吃蛇源程序代码双人对抗

C语言贪吃蛇源程序代码双人对抗

C语言贪吃蛇源程序代码双人对抗.txt第一次笑是因为遇见你,第一次哭是因为你不在,第一次笑着流泪是因为不能拥有你。

#include <stdio.h>#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdlib.h>#include <bios.h>#include <time.h>#include <malloc.h>#define LEFT 100#define TOP 30#define RIGHT 538#define BOTTOM 468#define SIZE 20#define SL 100 /*SL表示产生食物的个数*/typedef struct Snake/*表示蛇的结点*/{int bx,by;struct Snake *next;}Snake,*SnakeList;SnakeList createsnake(int cx,int cy)/*创建一个蛇头。

*/{SnakeList l;l=(SnakeList)malloc(sizeof(Snake));l->next=NULL;l->bx=cx;l->by=cy;return l;}void paintsnake(SnakeList l,int scoler,int tcoler)/*输出蛇身的函数,也可作为消去蛇身的函数。

*/{SnakeList p;int x,y;p=l;setfillstyle(SOLID_FILL,scoler);for(;p->next;){p=p->next;x=p->bx;y=p->by;bar(x,y,x+SIZE,y+SIZE);}if(scoler==2)setfillstyle(SOLID_FILL,scoler);elsesetfillstyle(SOLID_FILL,tcoler);x=l->bx;y=l->by;bar(x,y,x+SIZE,y+SIZE);}void changsnake(SnakeList l,int fx,int fy,int s) /*fx,fy表示蛇头移动方向,分别取值为1,-1;s表示是否吃到食物,1表示吃到,0表示没有。

vc贪吃蛇c语言代码

vc贪吃蛇c语言代码

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

贪吃蛇的c语言源程序

贪吃蛇的c语言源程序

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

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

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

C语言最简洁的贪吃蛇源代码.txt每天早上起床都要看一遍“福布斯”富翁排行榜,如果上面没有我的名字,我就去上班。

谈钱不伤感情,谈感情最他妈伤钱。

我诅咒你一辈子买方便面没有调料包。

#include〈graphics.h>#include<conio。

h〉#include〈dos.h〉#include<bios。

h>#include<stdlib。

h〉#define STATIC 0#define TRUE 1#define FALSE 0#define UP 1#define RIGHT 2#define DOWN 3#define LEFT 4#define VK_LEFT 0x4b00 /*上下左右键的值*/#define VK_RIGHT 0x4d00#define VK_DOWN 0x5000#define VK_UP 0x4800#define VK_ESC 0x011bint board[22][22];int snakelength=0;struct snake{public:int x=0;int y=0;int direction;}body[20];snake food;void makefood();/*产生一个食物*/int eatfood(); /*蛇吃掉食物*/void right(); /*上下左右的函数了*/void down();void left();void up();void getdirection(); /*判断蛇的方向*/move(snake *body)/*让蛇动起来*/{int x=body[0].x,y=body[0].y;if(body—>direction==RIGHT&&board[y][x+1]!=1)right();else if(body—>direction==DOWN&&board[y+1][x]!=1)down(); else if(body->direction==LEFT&&board[y][x—1]!=1)left(); else if(body—>direction==UP&&board[y-1][x]!=1)up();return 0;}void print() /*在屏幕上显示蛇*/{int i,j,x=0,y=0;for(i=1;i〈21;i++)for(j=1;j<21;j++)board[i][j]=0;for(i=0;i〈20;i++){x=body[i]。

贪吃蛇代码(C 实现)

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

基于C语言实现的贪吃蛇游戏完整实例代码

基于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语言实现双人贪吃蛇游戏实例代码

C语⾔实现双⼈贪吃蛇游戏实例代码贪吃蛇双⼈⼩游戏,每局游戏两分钟,死亡则直接失败,若时间结束,则分⾼者获胜。

上源代码:1234567891011121314151617181920212223242526272829303132 33 34 35#include <stdio.h>#include <stdlib.h>#include <Windows.h> #include <time.h>#include<stdbool.h>35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99#include<stdbool.h>#include <conio.h>#define SNAKESIZE 100#define MAPWIDTH 118#define MAPHEIGHT 29struct{ //保存⾷物坐标int x;int y;}food;struct{int len;int x[SNAKESIZE];int y[SNAKESIZE];}snake;struct{int len;int x[SNAKESIZE];int y[SNAKESIZE];}snake1;char key = '8';//初始⽅向向上char key1 = 'w';int changeFlag = 0 , changeFlag1 = 0;int speed=150 , sorce = 0 , sorce1 = 0 , sec=0 , min=2;void gotoxy(int x, int y)//移动光标到指定位置{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }void MAP()//打印边框和两条蛇的起始位置{for(int i = 0; i <= MAPWIDTH; i += 2)//打印最上⾯和最下⾯两横边框{gotoxy(i, 0);printf("■");gotoxy(i, MAPHEIGHT);printf("■");}for(int i = 1; i < MAPHEIGHT; i++)//打印最左⾯和最右⾯{gotoxy(0, i);printf("■");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 = snake1.len = 4;//给两条蛇的长度赋初值snake.x[0] = MAPWIDTH / 2 + 31;//然后分别打印两条蛇⾝部分snake.y[0] = MAPHEIGHT / 2;snake1.x[0] = MAPWIDTH / 2 -31;snake1.y[0] = MAPHEIGHT / 2;gotoxy(snake.x[0], snake.y[0]);99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 gotoxy(snake.x[0], snake.y[0]);printf("■");gotoxy(snake1.x[0], snake1.y[0]);printf("●");for(int i = 1; i < snake.len; i++){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.y[i - 1]+1;gotoxy(snake.x[i], snake.y[i]);printf("■");snake1.x[i] = snake1.x[i - 1];snake1.y[i] = snake1.y[i - 1]+1;gotoxy(snake1.x[i], snake1.y[i]);printf("●");}gotoxy(MAPWIDTH , 0);//把光标移⾛return;}void OPERATION()//操作函数{char pre_key = key , pre_key1 = key1 , s;//保存两条蛇上⼀次的⽅向if(_kbhit()){s = getch();if(s=='w'||s=='s'||s=='a'||s=='d'||s=='W'||s=='S'||s=='A'||s=='D')key1=s;else if(s=='8'||s=='5'||s=='4'||s=='6')key=s;}if(changeFlag == 0)//没吃到⾷物{gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}if(changeFlag1 == 0){gotoxy(snake1.x[snake1.len - 1], snake1.y[snake1.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}//将蛇的每⼀节依次向前移动⼀节(蛇头除外)for(int i = snake.len - 1; i > 0; i--){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.y[i - 1];}for(int i = snake1.len - 1; i > 0; i--){snake1.x[i] = snake1.x[i - 1];snake1.y[i] = snake1.y[i - 1];}//蛇当前移动的⽅向不能和前⼀次的⽅向相反,⽐如蛇往左⾛的时候不能直接按右键往右⾛ //如果当前移动⽅向和前⼀次⽅向相反的话,把当前移动的⽅向改为前⼀次的⽅向if(pre_key == '8'&& key == '5')key = '8';if(pre_key == '5'&& key == '8')key = '5';if(pre_key == '4'&& key == '6')key = '4';if(pre_key == '6'&& key == '4')key = '6';if(pre_key1 == 'w'&& key1 == 's')key1 = 'w';if(pre_key1 == 's'&& key1 == 'w')key1 = 's';if(pre_key1 == 'a'&& key1 == 'd')key1 = 'a';if(pre_key1 == 'd'&& key1 == 'a')key1 = 'd';163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 key1 = 'd';//判断蛇头应该往哪个⽅向移动switch(key){case'4':snake.x[0] -= 2;//往左break;case'6':snake.x[0] += 2;//往右break;case'8':snake.y[0]--;//往上break;case'5':snake.y[0]++;//往下break;}gotoxy(snake.x[0], snake.y[0]);printf("■");changeFlag = 0;switch(key1){case'a':case'A':snake1.x[0] -= 2;//往左break;case'd':case'D':snake1.x[0] += 2;//往右break;case'w':case'W':snake1.y[0]--;//往上break;case's':case'S':snake1.y[0]++;//往下break;}gotoxy(snake1.x[0], snake1.y[0]);printf("●");changeFlag1 = 0;gotoxy(MAPWIDTH, 0);return;}void createFood(){if(snake.x[0] == food.x && snake.y[0] == food.y)//蛇头碰到⾷物{//蛇头碰到⾷物即为要吃掉这个⾷物了,因此需要再次⽣成⼀个⾷物 while(1){int a = 1 , b=1;srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//随机⽣成的⾷物不能在蛇的⾝体上for(int i = 0; i < snake.len; i++){if(snake.x[i] == food.x && snake.y[i] == food.y){a = 0;break;}}for(int i = 0; i < snake1.len; i++){if(snake1.x[i] == food.x && snake1.y[i] == food.y){b = 0;break;}226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 }//随机⽣成的⾷物不能横坐标为奇数,也不能在蛇⾝,否则重新⽣成if(a==1&&b==1 && food.x % 2 == 0)break;}//绘制⾷物gotoxy(food.x, food.y);printf("★");snake.len++;//吃到⾷物,蛇⾝长度加1sorce += 10;speed -= 5;//随着吃的⾷物越来越多,速度会越来越快changeFlag = 1;//很重要,因为吃到了⾷物,就不⽤再擦除蛇尾的那⼀节,以此来造成蛇⾝体增长的效果 }return;}void createFood1(){if(snake1.x[0] == food.x && snake1.y[0] == food.y)//蛇头碰到⾷物{//蛇头碰到⾷物即为要吃掉这个⾷物了,因此需要再次⽣成⼀个⾷物while(1){int a = 1 , b=1;srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//随机⽣成的⾷物不能在蛇的⾝体上for(int i = 0; i < snake.len; i++){if(snake.x[i] == food.x && snake.y[i] == food.y){a = 0;break;}}for(int i = 0; i < snake1.len; i++){if(snake1.x[i] == food.x && snake1.y[i] == food.y){b = 0;break;}}//随机⽣成的⾷物不能横坐标为奇数,也不能在蛇⾝,否则重新⽣成if(a==1&&b==1&& food.x % 2 == 0)break;}//绘制⾷物gotoxy(food.x, food.y);printf("★");snake1.len++;//吃到⾷物,蛇⾝长度加1sorce1 += 10;speed -= 5;//随着吃的⾷物越来越多,速度会越来越快changeFlag1 = 1;//很重要,因为吃到了⾷物,就不⽤再擦除蛇尾的那⼀节,以此来造成蛇⾝体增长的效果 }return;}bool check(){//蛇头碰到上下边界,游戏结束if(snake.y[0] == 0 || snake.y[0] == MAPHEIGHT)return true;//蛇头碰到左右边界,游戏结束if(snake.x[0] == 0 || snake.x[0] == MAPWIDTH)return true;//蛇头碰到蛇⾝,游戏结束for(int i = 1; i < snake.len; i++){290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 {if(snake.x[i] == snake.x[0] && snake.y[i] == snake.y[0])return true;}for(int i = 0; i < snake1.len; i++){if(snake1.x[i] == snake.x[0]&&snake1.y[i] == snake.y[0])return true;}return false;}bool check1(){//蛇头碰到上下边界,游戏结束if(snake1.y[0] == 0 || snake1.y[0] == MAPHEIGHT)return true;//蛇头碰到左右边界,游戏结束if(snake1.x[0] == 0 || snake1.x[0] == MAPWIDTH)return true;//蛇头碰到蛇⾝,游戏结束for(int i = 1; i < snake1.len; i++){if(snake1.x[i] == snake1.x[0] && snake1.y[i] == snake1.y[0])return true;}for(int i = 0; i < snake.len; i++){if(snake.x[i] == snake1.x[0] && snake.y[i] == snake1.y[0])return true;}return false;}void MENU ()//打印菜单界⾯{printf("\n\n\n\n\t\t\t\t ╔═══════════════════════════════════════╗\n");printf("\t\t\t\t ║║\n");printf("\t\t\t\t ║欢迎来到贪吃蛇║\n");printf("\t\t\t\t ║║\n");printf("\t\t\t\t ║║\n");printf("\t\t\t\t ║┏━━┓┏━━┓┏━━┓║\n");printf("\t\t\t\t ║开始:┃ 1┃规则:┃ 2┃退出:┃ 3┃║\n");printf("\t\t\t\t ║┗━━┛┗━━┛┗━━┛║\n");printf("\t\t\t\t ║║\n");printf("\t\t\t\t ║║\n");printf("\t\t\t\t ╚═══════════════════════════════════════╝\n");switch(getch()){case'1':system("cls");START();break;case'2':system("cls");RULE();MENU();break;case'3':exit(0);break;default:system("cls");printf("error");MENU();}}void RULE (){system("cls");//清屏printf("\t╔══════════════════════════════════════════════════════════════════════════════════════════════════╗\n"); printf("\t║本游戏玩家⼀(左侧)通过按键W、S、A、D(不区分⼤⼩写)四个键分别控制snake1上移、下移、左移和右移。

贪吃蛇大作战双人版完整代码,不懂问博主。

贪吃蛇大作战双人版完整代码,不懂问博主。

贪吃蛇⼤作战双⼈版完整代码,不懂问博主。

1. using System;2. using System.Collections.Generic;3. using System.Linq;4. using System.Text;5. using System.Threading.Tasks;6. using System.Windows;7. using System.Windows.Controls;8. using System.Windows.Data;9. using System.Windows.Documents;10. using System.Windows.Input;11. using System.Windows.Media;12. using System.Windows.Media.Imaging;13. using System.Windows.Navigation;14. using System.Windows.Shapes;15. using System.Windows.Threading;16.17. namespace 贪吃蛇18. {19. /// <summary>20. /// MainWindow.xaml 的交互逻辑21. /// </summary>22. public partial class MainWindow : Window23. {24. public MainWindow()25. {26. InitializeComponent();27. this.Background = Brushes.Pink;28. }29. Random ra = new Random();30. Border food;31. Border bd1;32. DispatcherTimer dt;33. string s = "";34. string s1 = "";35. List<Border> snack = new List<Border>();36. List<Border> snakeback = new List<Border>();37. List<Border> snack1 = new List<Border>();38. List<Border> snakeback1 = new List<Border>();39. //创建⼀个放⾷物的集合40. List<Border> foodback = new List<Border>();41. private void Window_Loaded(object sender, RoutedEventArgs e)42. {43. this.Left = 0;44. this.Top = 0;45. //this.Width = SystemParameters.FullPrimaryScreenWidth;46. //this.Height = SystemParameters.FullPrimaryScreenHeight;47. this.Width = 800;48. this.Height = 600;49. for (int i = 0; i < 5; i++)50. {51. Border bd = new Border();52. if (i == 0)53. {54. bd.Background = Brushes.Red;55. }56. else57. {58. bd.Background = Brushes.Black;59. }60. bd.Height = bd.Width = 10;61. bd.CornerRadius = new CornerRadius(5);62. Canvas.SetLeft(bd, 200);63. Canvas.SetTop(bd, 200 + i * bd.Height);64. back.Children.Add(bd);65. snack.Add(bd);66. //存储蛇的位置的border67. Border bdback = new Border();68. Canvas.SetLeft(bdback, 200);69. Canvas.SetTop(bdback, 200 + i * bd.Height);70. snakeback.Add(bdback);71. }72. for (int i = 0; i < 5; i++)74. bd1 = new Border();75. bd1.Width = bd1.Height = 10;76. bd1.CornerRadius = new CornerRadius(5);77. if (i == 0)78. bd1.Background = Brushes.Chocolate;79. else80. bd1.Background = Brushes.DarkBlue;81. Canvas.SetTop(bd1, 400 + i * bd1.Height);82. Canvas.SetLeft(bd1, 400);83. back.Children.Add(bd1);84. snack1.Add(bd1);85.86. //创建蛇的位置border87. Border bdback1 = new Border();88. bdback1.Height = bdback1.Width = 10;89. Canvas.SetTop(bdback1, 400 + i * bd1.Height);90. Canvas.SetLeft(bdback1, 400);91. snakeback1.Add(bdback1);92. }93. this.KeyDown += MainWindow_KeyDown;94. dt = new DispatcherTimer();95. dt.Tick += Dt_Tick;96. dt.Interval = TimeSpan.FromMilliseconds(80);97. dt.Start();98. for (int i = 0; i < 30; i++)99. {100. //创建⾷物101. food = new Border();102. food.Width = food.Height = 10;103. food.Background = Brushes.Yellow;104. Canvas.SetTop(food, ra.Next(60) * 10);105. Canvas.SetLeft(food, ra.Next(80) * 10);106. food.CornerRadius = new CornerRadius(10);107. back.Children.Add(food);108. foodback.Add(food);109. }110. }111.112. private void Dt_Tick(object sender, EventArgs e)113. {114. if (s == "up")115. {116. Canvas.SetTop(snack[0], Canvas.GetTop(snack[0]) - snack[0].Height); 117. Run();118.119. }120. if (s == "down")121. {122. Canvas.SetTop(snack[0], Canvas.GetTop(snack[0]) + snack[0].Height); 123. Run();124.125. }126. if (s == "left")127. {128. Canvas.SetLeft(snack[0], Canvas.GetLeft(snack[0]) - snack[0].Width); 129. Run();130.131. }132. if (s == "right")133. {134. Canvas.SetLeft(snack[0], Canvas.GetLeft(snack[0]) + snack[0].Width); 135. Run();136.137. }138. if (s1 == "w")139. {140. Canvas.SetTop(snack1[0], Canvas.GetTop(snack1[0]) - snack1[0].Height); 141. Run1();142. }143. if (s1 == "s")144. {145. Canvas.SetTop(snack1[0], Canvas.GetTop(snack1[0]) + snack1[0].Height); 146. Run1();147. }148. if (s1 == "a")150. Canvas.SetLeft(snack1[0], Canvas.GetLeft(snack1[0]) - snack1[0].Width);151. Run1();152. }153. if (s1 == "d")154. {155. Canvas.SetLeft(snack1[0], Canvas.GetLeft(snack1[0]) + snack1[0].Width);156. Run1();157. }158. for (int i = 0; i < 30; i++)159. {160. if (Canvas.GetTop(snack1[0]) == Canvas.GetTop(foodback[i]) && Canvas.GetLeft(snack1[0]) == Canvas.GetLeft(foodback[i]))161. {162. Canvas.SetTop(foodback[i], ra.Next(60) * 10);163. Canvas.SetLeft(foodback[i], ra.Next(80) * 10);164.165. //创建⼀个border添加到尾部166. Border bdfood1 = new Border();167. bdfood1.Width = bdfood1.Height = 10;168. bdfood1.Background = Brushes.DarkBlue;169. bdfood1.CornerRadius = new CornerRadius(5);170. Canvas.SetTop(bdfood1, Canvas.GetTop(snack[snack.Count - 1]));171. Canvas.SetLeft(bdfood1, Canvas.GetLeft(snack[snack.Count - 1]));172. snack1.Add(bdfood1);173. back.Children.Add(bdfood1);174.175. //创建⼀个border,存放加到后⾯的蛇⾝的位置176. Border br1 = new Border();177. Canvas.SetTop(br1, Canvas.GetTop(bdfood1));178. Canvas.SetLeft(br1, Canvas.GetLeft(bdfood1));179. snakeback1 .Add(br1);180. }181. }182. for (int i = 0; i < 30; i++)183. {184. if (Canvas.GetTop(snack[0]) == Canvas.GetTop(foodback[i]) && Canvas.GetLeft(snack[0]) == Canvas.GetLeft(foodback[i]))185. {186. Canvas.SetTop(foodback[i], ra.Next(60) * 10);187. Canvas.SetLeft(foodback[i], ra.Next(80) * 10);188.189. //创建⼀个border添加到尾部190. Border bdfood = new Border();191. bdfood.Width = bdfood.Height = 10;192. bdfood.Background = Brushes.Black;193. bdfood.CornerRadius = new CornerRadius(5);194. Canvas.SetTop(bdfood, Canvas.GetTop(snack[snack.Count - 1]));195. Canvas.SetLeft(bdfood, Canvas.GetLeft(snack[snack.Count - 1]));196. snack.Add(bdfood);197. back.Children.Add(bdfood);198.199. //创建⼀个border,存放加到后⾯的蛇⾝的位置200. Border br = new Border();201. Canvas.SetTop(br, Canvas.GetTop(bdfood));202. Canvas.SetLeft(br, Canvas.GetLeft(bdfood));203. snakeback.Add(br);204. }205. }206. for (int i = 1; i < snack.Count; i++)207. {208. if (Canvas.GetTop(snack[0]) == Canvas.GetTop(snack[i]) && Canvas.GetLeft(snack[0]) == Canvas.GetLeft(snack[i]))209. {210. dt.Stop();211. MessageBox.Show("GAME OVER!");212. }213. }214. if (Canvas.GetTop(snack[0]) == 0 || Canvas.GetLeft(snack[0]) == 0 || Canvas.GetTop(snack[0]) == 560 || Canvas.GetLeft(snack[0]) == 780) 215. {216. dt.Stop();217. MessageBox.Show("GAME OVER!");218. }219. for (int i = 1; i < snack1.Count; i++)220. {221. if (Canvas.GetTop(snack1[0]) == Canvas.GetTop(snack1[i]) && Canvas.GetLeft(snack1[0]) == Canvas.GetLeft(snack1[i]))222. {223. dt.Stop();224. MessageBox.Show("GAME OVER!");226. }227. if (Canvas.GetTop(snack1[0]) == 0 || Canvas.GetLeft(snack1[0]) == 0 || Canvas.GetTop(snack1[0]) == 560 || Canvas.GetLeft(snack1[0]) == 780) 228. {229. dt.Stop();230. MessageBox.Show("GAME OVER!");231. }232. }233. private void Run()234. {235. for (int i = 1; i < snack.Count; i++)236. {237. Canvas.SetTop(snack[i], Canvas.GetTop(snakeback[i - 1]));238. Canvas.SetLeft(snack[i], Canvas.GetLeft(snakeback[i - 1]));239. }240. for (int i = 0; i < snack.Count; i++)241. {242. Canvas.SetTop(snakeback[i], Canvas.GetTop(snack[i]));243. Canvas.SetLeft(snakeback[i], Canvas.GetLeft(snack[i]));244. }245. }246. private void Run1()247. {248. for (int i = 1; i < snack1.Count; i++)249. {250. Canvas.SetTop(snack1[i], Canvas.GetTop(snakeback1[i - 1]));251. Canvas.SetLeft(snack1[i], Canvas.GetLeft(snakeback1[i - 1]));252. }253. for (int i = 0; i < snack1.Count; i++)254. {255. Canvas.SetTop(snakeback1[i], Canvas.GetTop(snack1[i]));256. Canvas.SetLeft(snakeback1[i], Canvas.GetLeft(snack1[i]));257. }258. }259. private void MainWindow_KeyDown(object sender, KeyEventArgs e)260. {261. if (e.Key == Key.Up && s != "down")262. {263. s = "up";264. }265. if (e.Key == Key.Down && s != "up")266. {267. s = "down";268. }269. if (e.Key == Key.Left && s != "right")270. {271. s = "left";272. }273. if (e.Key == Key.Right && s != "left")274. {275. s = "right";276. }277. if (e.Key == Key.W && s1 != "s")278. {279. s1 = "w";280. }281. if (e.Key == Key.S && s1 != "w")282. {283. s1 = "s";284. }285. if (e.Key == Key.A && s1 != "d")286. {287. s1 = "a";288. }289. if (e.Key == Key.D && s1 != "a")290. {291. s1 = "d";292. }293. }294. }295. }296.。

贪吃蛇 C++源代码

贪吃蛇 C++源代码
if ((cmd & CMD_A_LEFT) && g_offset_a.y != 0) { g_offset_a.x = -1; g_offset_a.y = 0; }
if ((cmd & CMD_A_RIGHT) && g_offset_a.y != 0) { g_offset_a.x = 1; g_offset_a.y = 0; }
#define CMD_B_RIGHT 0x80 控制命令:游戏者 B 向右
#define CMD_QUIT um ITEM { EMPTY = 0, WALL, PLAYER_A, PLAYER_B, PLAYER_DEAD, PLAYER_A_NEXT, PLAYER_B_NEXT };
case 'D' case 'd' if (PLAYER_A_CMD.size() 16) PLAYER_A_CMD.push(CMD_A_RIGHT); break;
case 0 case 0xE0
switch(_getch())
{
case 72 if (PLAYER_B_CMD.size() 16) PLAYER_B_CMD.push(CMD_B_UP); break;
按确定开始游戏
MessageBox(GetHWnd(), _T(对战贪吃蛇 游戏说明:nn)
_T(游戏目标:两条蛇,先碰到墙壁或碰到任何蛇的身体就算输。n)
_T(Player A 使用 A S D W 控制蓝色小蛇移动方向。n)
_T(Player B 使用上下左右控制红色小蛇移动方向。nn)
}
for(y = 1; y HEIGHT - 1; y++)

C语言贪吃蛇源代码

C语言贪吃蛇源代码

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

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

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

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

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

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

C语言程序贪吃蛇代码#include<stdio.h>#include<windows.h>#include<time.h>#include<stdlib.h>#include<conio.h>#define N 21FILE *fp;int S;void boundary(void);//开始界面void end(void); //结束void gotoxy(int x,int y)//位置函数{COORD pos;pos.X=x;pos.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); }void color(int a)//颜色函数{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);}void init(int food[2])//初始化函数(初始化围墙、显示信息、苹果){system("cls");int i,j;//初始化围墙int wall[N+2][N+2]={{0}};//初始化围墙的二维数组for(i=1;i<=N;i++){for(j=1;j<=N;j++)wall[i][j]=1;}color(10);for(i=0;i<N+2;i++)//畵围墙{for(j=0;j<N+2;j++){if(wall[i][j])printf(" ");else printf("#") ;}printf("\n") ;}gotoxy(N+3,3);//显示信息color(14);printf("\t\t按a,b,c,d改变方向\n");gotoxy(N+3,1);color(14);printf("\t\t按任意键暂停,按1返回,按2退出\n"); gotoxy(N+5,3);color(14);printf("score:\n");food[0]=rand()%N+1;//随机出现食物food[1]=rand()%N+1;gotoxy(food[0],food[1]);color(12);printf("*\n");}void play()//具体玩的过程{system("cls");int i,j;int** snake=NULL;//定义蛇的二维指针int food[2];//食物的数组,food[0]代表横坐标,food[1]代表纵坐标int score=0;//为得分int tail[2];//此数组为了记录蛇的头的坐标int node=3;//蛇的节数char ch='p';srand((unsigned)time(NULL));//随机数发生器的初始化函数init(food);snake=(int**)realloc(snake,sizeof(int*)*node);//改变snake所指内存区域的大小为node长度for(i=0;i<node;i++)snake[i]=(int*)malloc(sizeof(int)*2);for(i=0;i<node;i++)//初始化蛇的长度{snake[i][0]=N/2;snake[i][1]=N/2+i;gotoxy(snake[i][0],snake[i][1]);color(14);printf("*\n");}while(1)//进入消息循环{gotoxy(5,0);color(10);printf("#");gotoxy(0,5);color(10);printf("#");gotoxy(0,7);color(10);printf("#");gotoxy(0,9);color(10);printf("#");tail[0]=snake[node-1][0];//将蛇的后一节坐标赋给tail数组tail[1]=snake[node-1][1];gotoxy(tail[0],tail[1]);color(0);printf(" ");for(i=node-1;i>0;i--)//蛇想前移动的关键算法,后一节的占据前一节的地址坐标{snake[i][0]=snake[i-1][0];snake[i][1]=snake[i-1][1];gotoxy(snake[i][0],snake[i][1]);color(14);printf("*\n");}if(kbhit())//捕捉输入信息gotoxy(0,N+2);ch=getche();}switch(ch){case 'w':snake[0][1]--;break;case 's':snake[0][1]++;break;case 'a':snake[0][0]--;break;case 'd':snake[0][0]++;break;case '1':boundary() ;break;case '2':end();break;default: break;}gotoxy(snake[0][0],snake[0][1]);color(14);printf("*\n");Sleep(abs(200-0.5*score));//使随着分数的增长蛇的移动速度越来越快if(snake[0][0]==food[0]&&snake[0][1]==food[1])//吃掉食物后蛇分数加1,蛇长加1 {score++;//分数增加S=score;node++;//节数增加snake=(int**)realloc(snake,sizeof(int*)*node);snake[node-1]=(int*)malloc(sizeof(int)*2);food[0]=rand()%N+1;//产生随机数且要在围墙内部food[1]=rand()%N+1;gotoxy(food[0],food[1]);color(12);printf("*\n");gotoxy(N+12,3);color(14);printf("%d\n",score);//输出得分}if(snake[0][1]==0||snake[0][1]==N+1||snake[0][0]==0||snake[0][0]==N+1)//撞到围墙后失败{gotoxy(N/2,N/2);color(30);printf("GAME OVER\n");for(i=0;i<node;i++)free(snake[i]);Sleep(INFINITE);exit(0);}}//从蛇的第四节开始判断是否撞到自己,因为蛇头为两节,第三节不可能拐过来for (i=3; i<node; i++){for(j=0;j<node;j++){if (snake[i][0]==snake[j][0] && snake[i][1]==snake[j][1]){gotoxy(N/2,N/2);color(30);printf("GAME OVER\n");for(i=0;i<node;i++)free(snake[i]);Sleep(INFINITE);exit(0);;}}}}void end()//结束函数{system("cls");system("cls");printf("EXIT\n");}void grade()//成绩记录函数{system("cls");int i=0;char s;if( (fp=fopen("f:\\贪吃蛇\\贪吃蛇.txt","ar") )==NULL)//打开文件{printf("\nCannot open file!\n");exit(0);}if(i<S)i=S;color(14);fwrite(&i,sizeof(i),1,fp);fclose(fp);printf("最高的分为:%d\n\n",i);printf("\t按1返回\n\n");printf("\t按2退出\n\n");s=getche();switch(s){case '1':boundary();break;case '2': end();break;}}void boundary()//开始界面{system("cls");char s;color(14);printf("\t\t欢迎来玩!!\n\n");printf("\t\t1:开始\n\n");printf("\t\t2:查看成绩\n\n");printf("\t\t3:退出\n\n");printf("\t\t请选择:");s=getche();switch(s){case '1': play();break;case '2': grade();break;case '3': end();break;}}int main(){boundary();getchar();return 0;}。

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

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

简单贪吃蛇c语⾔代码,⼀个C语⾔写简单贪吃蛇源代码.doc ⼀个C语⾔写简单贪吃蛇源代码#include#include#include#include#include#includeint grade=5,point=0,life=3;voidset(),menu(),move_head(),move_body(),move(),init_insect(),left(),upon(),right(),down(),init_graph(),food_f(),ahead(),crate(); struct bug{int x;int y;struct bug *last;struct bug *next;};struct fd{int x;int y;int judge;}food={0,0,0};struct bug *head_f=NULL,*head_l,*p1=NULL,*p2=NULL;void main(){char ch;initgraph(800,600);set();init_insect();while(1){food_f();Sleep(grade*10);setcolor(BLACK);circle(head_l->x,head_l->y,2);setcolor(WHITE);move_body();if(kbhit()){ch=getch();if(ch==27){ahead();set();}else if(ch==-32){switch(getch()){case 72:upon();break;case 80:down();break;case 75:left();break;case 77:right();break;}}else ahead();}else{ahead();}if(head_f->x==food.x&&head_f->y==food.y) {Sleep(100);crate();food.judge=0;point=point+(6-grade)*10;if(food.x<30||food.y<30||food.x>570||food.y>570)life++;menu();}if(head_f->x<5||head_f->x>595||head_f->y<5||head_f->y>595) {Sleep(1000);life--;food.judge=0;init_graph();init_insect();menu();}for(p1=head_f->next;p1!=NULL;p1=p1->next){if(head_f->x==p1->x&&head_f->y==p1->y){Sleep(1000);life--;food.judge=0;init_graph();init_insect();menu();break;}}if(life==0){outtextxy(280,300,"游戏结束!");getch();return;}move();};}void init_graph(){clearviewport();setlinestyle(PS_SOLID,1,5);rectangle(2,2,600,598);setlinestyle(PS_SOLID,1,1);}void set(){init_graph();outtextxy(640,50,"1、开始 / 返回");outtextxy(640,70,"2、退出");outtextxy(640,90,"3、难度");outtextxy(640,110,"4、重新开始");switch(getch()){case '1': menu();setcolor(GREEN);circle(food.x,food.y,2);setcolor(WHITE);return; case '2': exit(0);break;。

基于VC的贪吃蛇游戏的C语言代码

基于VC的贪吃蛇游戏的C语言代码

基于VC的贪吃蛇游戏的C语言代码#include#include#include#include#define U 1#define D 2#define L 3#define R 4 //蛇的状态,U:上;D:下;L:左 R:右typedef struct SNAKE //蛇身的一个节点{int x;int y;struct SNAKE *next;}snake;//全局变量//int score=0,add=10;//总得分与每次吃食物得分。

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

//声明全部函数//void Pos();void creatMap();void initsnake();int biteself();void createfood();void cantcrosswall();void snakemove();void pause();void gamecircle();void welcometogame();void endgame();void gamestart();void Pos(int x,int y)//设置光标位置{COORD pos;HANDLE hOutput;pos.X=x;pos.Y=y;hOutput=GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hOutput,pos);}void creatMap()//创建地图{int i;for(i=0;i<58;i+=2)//打印上下边框{Pos(i,0);printf("■");Pos(i,26);printf("■");}for(i=1;i<26;i++)//打印左右边框{Pos(0,i);printf("■");Pos(56,i);printf("■");}}void initsnake()//初始化蛇身{snake *tail;int i;tail=(snake*)malloc(sizeof(snake));//从蛇尾开始,头插法,以x,y设定开始的位置//tail->x=24;tail->y=5;tail->next=NULL;for(i=1;i<=4;i++){head=(snake*)malloc(sizeof(snake));head->next=tail;head->x=24+2*i;head->y=5;tail=head;}while(tail!=NULL)//从头到为,输出蛇身{Pos(tail->x,tail->y);printf("■");tail=tail->next;}}int biteself()//判断是否咬到了自己{snake *self;self=head->next;while(self!=NULL){if(self->x==head->x && self->y==head->y){return 1;}self=self->next;}return 0;}void createfood()//随机出现食物{snake *food_1;srand((unsigned)time(NULL));food_1=(snake*)malloc(sizeof(snake));while((food_1->x%2)!=0) //保证其为偶数,使得食物能与蛇头对其 {food_1->x=rand()%52+2;}food_1->y=rand()%24+1;q=head;while(q->next==NULL){if(q->x==food_1->x && q->y==food_1->y) //判断蛇身是否与食物重合{free(food_1);createfood();}q=q->next;}Pos(food_1->x,food_1->y);food=food_1;printf("■");}void cantcrosswall()//不能穿墙{if(head->x==0 || head->x==56 ||head->y==0 || head->y==26) {endgamestatus=1;endgame();}}void snakemove()//蛇前进,上U,下D,左L,右R{snake * nexthead;cantcrosswall();nexthead=(snake*)malloc(sizeof(snake));if(status==U){nexthead->x=head->x;nexthead->y=head->y-1;if(nexthead->x==food->x && nexthead->y==food->y)//如果下一个有食物//{nexthead->next=head;head=nexthead;q=head;while(q!=NULL){Pos(q->x,q->y);printf("■");q=q->next;}score=score+add;createfood();}else //如果没有食物//{nexthead->next=head;head=nexthead;q=head;while(q->next->next!=NULL){Pos(q->x,q->y);printf("■");q=q->next;}Pos(q->next->x,q->next->y);printf(" ");free(q->next);q->next=NULL;}}if(status==D){nexthead->x=head->x;nexthead->y=head->y+1;if(nexthead->x==food->x && nexthead->y==food->y) //有食物{nexthead->next=head;head=nexthead;q=head;while(q!=NULL){Pos(q->x,q->y);printf("■");q=q->next;}score=score+add;createfood();}else //没有食物{nexthead->next=head;head=nexthead;q=head;while(q->next->next!=NULL){Pos(q->x,q->y);printf("■");q=q->next;}Pos(q->next->x,q->next->y);printf(" ");free(q->next);q->next=NULL;}if(status==L){nexthead->x=head->x-2;nexthead->y=head->y;if(nexthead->x==food->x && nexthead->y==food->y)//有食物{nexthead->next=head;head=nexthead;q=head;while(q!=NULL){Pos(q->x,q->y);printf("■");q=q->next;}score=score+add;createfood();}else //没有食物{nexthead->next=head;head=nexthead;q=head;while(q->next->next!=NULL){Pos(q->x,q->y);printf("■");q=q->next;}Pos(q->next->x,q->next->y);printf(" ");free(q->next);q->next=NULL;}}if(status==R){nexthead->x=head->x+2;nexthead->y=head->y;if(nexthead->x==food->x && nexthead->y==food->y)//有食物nexthead->next=head;head=nexthead;q=head;while(q!=NULL){Pos(q->x,q->y);printf("■");q=q->next;}score=score+add;createfood();}else //没有食物 {nexthead->next=head;head=nexthead;q=head;while(q->next->next!=NULL){Pos(q->x,q->y);printf("■");q=q->next;}Pos(q->next->x,q->next->y);printf(" ");free(q->next);q->next=NULL;}}if(biteself()==1) //判断是否会咬到自己{endgamestatus=2;endgame();}}void pause()//暂停{while(1){Sleep(300);if(GetAsyncKeyState(VK_SPACE)) {}}}void gamecircle()//控制游戏{Pos(64,15);printf("不能穿墙,不能咬到自己\n");Pos(64,16);printf("用↑.↓.←.→分别控制蛇的移动.");Pos(64,17);printf("F1 为加速,F2 为减速\n");Pos(64,18);printf("ESC :退出游戏.space:暂停游戏.");Pos(64,20);printf("C语言研究中心/doc/1d5620851.html,");status=R;while(1){Pos(64,10);printf("得分:%d ",score);Pos(64,11);printf("每个食物得分:%d分",add);if(GetAsyncKeyState(VK_UP) && status!=D){status=U;}else if(GetAsyncKeyState(VK_DOWN) && status!=U) {status=D;}else if(GetAsyncKeyState(VK_LEFT)&& status!=R) {status=L;}else if(GetAsyncKeyState(VK_RIGHT)&& status!=L) {status=R;}else if(GetAsyncKeyState(VK_SPACE))}else if(GetAsyncKeyState(VK_ESCAPE)) {endgamestatus=3;break;}else if(GetAsyncKeyState(VK_F1)) {if(sleeptime>=50){sleeptime=sleeptime-30;add=add+2;if(sleeptime==320){add=2;//防止减到1之后再加回来有错}}}else if(GetAsyncKeyState(VK_F2)) {if(sleeptime<350){sleeptime=sleeptime+30;add=add-2;if(sleeptime==350){add=1; //保证最低分为1}}Sleep(sleeptime);snakemove();}}void welcometogame()//开始界面{Pos(40,12);system("title C语言研究中心/doc/1d5620851.html,");printf("欢迎来到贪食蛇游戏!");Pos(40,25);printf(" C语言研究中心/doc/1d5620851.html,.\n");system("pause");system("cls");Pos(25,12);printf("用↑.↓.←.→分别控制蛇的移动, F1 为加速,2 为减速\n"); Pos(25,13);printf("加速将能得到更高的分数。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C语言贪吃蛇源程序代码双人对抗#include &lt;conio.h&gt;#include &lt;dos.h&gt;#include &lt;graphics.h&gt;#include &lt;stdlib.h&gt;#include &lt;bios.h&gt;#include &lt;time.h&gt;#include &lt;malloc.h&gt;#define LEFT 100#define TOP 30#define RIGHT 538#define BOTTOM 468#define SIZE 20#define SL 100 /*SL表示产生食物的个数*/typedef struct Snake/*表示蛇的结点*/{int bx,by;struct Snake *next;}Snake,*SnakeList;SnakeList createsnake(int cx,int cy)/*创建一个蛇头。

*/{SnakeList l;l=(SnakeList)malloc(sizeof(Snake));l-&gt;next=NULL;l-&gt;bx=cx;l-&gt;by=cy;return l;}void paintsnake(SnakeList l,int scoler,int tcoler)/*输出蛇身的函数,也可作为消去蛇身的函数。

*/{SnakeList p;int x,y;p=l;setfillstyle(SOLID_FILL,scoler);for(;p-&gt;next;)p=p-&gt;next;x=p-&gt;bx;y=p-&gt;by;bar(x,y,x+SIZE,y+SIZE);}if(scoler==2)setfillstyle(SOLID_FILL,scoler);elsesetfillstyle(SOLID_FILL,tcoler);x=l-&gt;bx;y=l-&gt;by;bar(x,y,x+SIZE,y+SIZE);}void changsnake(SnakeList l,int fx,int fy,int s) /*fx,fy表示蛇头移动方向,分别取值为1,-1;s 表示是否吃到食物,1表示吃到,0表示没有。

*/{SnakeList p=l;int x,y,t;x=p-&gt;bx;y=p-&gt;by;p-&gt;bx=x+fx*(SIZE+2);p-&gt;by=y+fy*(SIZE+2);for(;p-&gt;next;){p=p-&gt;next;t=p-&gt;bx;p-&gt;bx=x;x=t;t=p-&gt;by;p-&gt;by=y;y=t;}if(s){p-&gt;next=(SnakeList)malloc(sizeof(Snake));p-&gt;next-&gt;bx=x;p-&gt;next-&gt;by=y;p-&gt;next-&gt;next=NULL;}}void setfood(int *fx,int *fy,SnakeList al,SnakeList bl)/*设置随机食物*/ {int a,b,s=1,s2;SnakeList slist1;SnakeList slist2;setfillstyle(SOLID_FILL,6);srand(time(NULL));for(;s;){slist1=al;slist2=bl;a=rand()%(SIZE);b=rand()%(SIZE);a=LEFT+(a)*22;b=TOP+(b)*22;s2=1;for(;slist1&amp;&amp;s2;){if(a==slist1-&gt;bx&amp;&amp;b==slist1-&gt;by)s2=0;elseslist1=slist1-&gt;next;}s2=1;for(;slist2&amp;&amp;s2;){if(a==slist2-&gt;bx&amp;&amp;b==slist2-&gt;by)s2=0;elseslist2=slist2-&gt;next;}if(slist1==NULL&amp;&amp;slist2==NULL)s=0;}*fx=a;*fy=b;bar(*fx,*fy,*fx+20,*fy+20);}void qufood(int fx,int fy)/*消去食物*/setfillstyle(SOLID_FILL,2);bar(fx,fy,fx+20,fy+20);}void freesnake(SnakeList psnake)/*释放蛇的空间。

*/{SnakeList p;p=psnake-&gt;next;psnake-&gt;next=NULL;for(;p;){p=psnake-&gt;next;free(psnake);psnake=p;}}int nothit(SnakeList snake1,SnakeList snake2,int x,int y)/*检查snake1是否撞击snake2。

*/ {int a1,a2,b1,b2,bj=1;a1=snake1-&gt;bx;b1=snake1-&gt;by;a1=a1+x*(SIZE+2);b1=b1+y*(SIZE+2);a2=snake2-&gt;bx;b2=snake2-&gt;by;for(;snake2&amp;&amp;bj;){if(a1==a2&amp;&amp;b1==b2){bj=0;}else{snake2=snake2-&gt;next;a2=snake2-&gt;bx;b2=snake2-&gt;by;}return bj;}void paintpig()/*画一个猪头。

*/{setwritemode(1);/*设置绘制线条的模式,1表示异或模式*/setfillstyle(1,2);/*设置图片填充模式和颜色,1表示实色填充,2表示绿色*/pieslice(220,140,0,360,80);/*画耳朵*/pieslice(420,140,0,360,80);setfillstyle(1,6);pieslice(320,240,0,360,150);/*画脸*/arc(260,180,30,160,30);/*画眉毛*/arc(380,180,30,160,30);setfillstyle(1,4);sector(320,260,0,360,50,40);/*画鼻子*/setfillstyle(1,8);pieslice(300,260,0,360,5);/*鼻孔*/pieslice(340,260,0,360,5);arc(320,260,230,310,60);/*画嘴*/}void numtostr(int n,char a[3])/*把一个数字n转换成字符串,并存储在a中。

*/{int w;w=n%10;a[1]=w+&#39;0&#39;;w=n/10;a[0]=w+&#39;0&#39;;a[2]=&#39;\0&#39;;}void main(){int gr=DETECT,gm;int s1=0,s2=0,fx1=0,fy1=1,fx2=0,fy2=1;/*s1表示snake1的身长,s2表示snake2的身长;fx*,fy*表示蛇头运动方向;*/int dx,dy,add1,add2,k,k1=1,k2=1;/*dx,dy表示食物的位置;add*=1表示是否吃到食物;k*=1表示蛇头越界*/int i=1,j=0,q=1;/*j=0表示只有一条蛇,j=1表示有两条蛇,j=2表示没有蛇退出游戏*/ unsigned long t;/*t表示延迟的时间*/char w[3];SnakeList lsnake1,lsnake2;/*registerbgidriver(EGAVGA_driver);*//*detectgraph(*gr, *gm);*/initgraph(&amp;gr,&amp;gm,&quot;&quot;);/*设置屏幕为图形模式*/ cleardevice();/*清屏函数*/for(;q;){cleardevice();paintpig();settextstyle(0,0,3);outtextxy(100,10,&quot; I like pigs!&quot;);settextstyle(1,0,2);outtextxy(300,400,&quot;One snake!&quot;);outtextxy(300,420,&quot;Two snakes!&quot;);outtextxy(300,440,&quot;Quit Game&quot;);outtextxy(450,420,&quot;Producer:Chen Chen&quot;);outtextxy(450,440,&quot;Time:May 23 2012&quot;);outtextxy(30,370,&quot;Keys used:Arrow keys&quot;);outtextxy(30,380,&quot;&#39;W&#39;&#39;A&#39;&#39;S&#39;D&#39;&quot;);outtextxy(30,390,&quot; &#39;enter&#39;&quot;); setfillstyle(1,4);pieslice(280,400+j*20,0,360,5);i=1;for(;i;){k=bioskey(0);/*获取按键的扫描码*/sound(1300);/*响声函数*/delay(10000);/*延迟函数*/nosound();/*关闭响声函数*/switch (k){case 20480:/*向下键的扫描码*/setfillstyle(1,0);pieslice(280,400+j*20,0,360,5);j=(j+1)%3;setfillstyle(1,4);pieslice(280,400+j*20,0,360,5);break;case 7181:/*enter键的扫描码*/if(j==0||j==1){i=0;}else{closegraph();/*关闭图形模式的函数*/exit(0); /*退出程序函数*/}break;default : break;}}cleardevice();setfillstyle(SOLID_FILL,2);/*设置填充图案的模式和颜色*/ bar(LEFT,TOP,RIGHT,BOTTOM);/*绘画屏幕*/lsnake1=createsnake(496,140);/*生成lsnake1的蛇头*/ lsnake2=createsnake(144,140);/*生成lsnake2的蛇头*/ setfood(&amp;dx,&amp;dy,lsnake1,lsnake2);k1=1,k2=1;fx1=0,fy1=1,fx2=0,fy2=1;s1=0,s2=0;t=100000;for(;(k1||k2)&amp;&amp;(s1+s2&lt;SL);){add1=0;add2=0;if(kbhit())/*kbhit()函数检测是否有按键*/{sound(1200);delay(10000);k=bioskey(0);/*获取按键的扫描码*/delay(1000);nosound();switch(k){case 19200: /*按向左键*/if(fx1==0){fx1=-1;fy1=0;}break;case 19712: /*按向右键*/ if(fx1==0){fx1=1;fy1=0;}break;case 18432: /*按向上键*/ if(fy1==0){fx1=0;fy1=-1;} break;case 20480: /*按向下键*/ if(fy1==0){fx1=0;fy1=1;}break;case 7777: /*按向左键*/ if(fx2==0){fx2=-1;fy2=0;}break;case 8292: /*按向右键*/ if(fx2==0){fx2=1;fy2=0;}break;case 4471: /*按向上键*/ if(fy2==0)fx2=0;fy2=-1;}break;case 8051: /*按向下键*/if(fy2==0){fx2=0;fy2=1;}break;default: break;}}if(j==1){if((lsnake2-&gt;bx)&gt;=LEFT&amp;&amp;(lsnake2-&gt;bx+SIZE)&lt;=RIGHT&amp;&amp;(lsn ake2-&gt;by)&gt;=TOP&amp;&amp;(lsnake2-&gt;by+SIZE)&lt;=BOTTOM)/*检测snake2的蛇头是否出界*/{if((lsnake2-&gt;bx==dx)&amp;&amp;(lsnake2-&gt;by==dy))/*检测snake2是否吃到食物*/ {t=t-800;setfillstyle(1,0);bar(48,60,88,100);qufood(dx,dy);add2=1;s2++;setfillstyle(1,1);bar(48,60,88,100);numtostr(s2,w);outtextxy(58,70,w);outtextxy(58,80,&quot;Blue&quot;);}}else{k2=0;/*freesnake(lsnake2);*/}if(k2&amp;&amp;nothit(lsnake2,lsnake1,fx2,fy2))paintsnake(lsnake2,2,2);/*消去蛇*/changsnake(lsnake2,fx2,fy2,add2);/*蛇身坐标移动*/paintsnake(lsnake2,14,1);/*绘制蛇*/}}else{k2=0;paintsnake(lsnake2,14,9);}if((lsnake1-&gt;bx)&gt;=LEFT&amp;&amp;(lsnake1-&gt;bx+SIZE)&lt;=RIGHT&amp;&amp;(lsn ake1-&gt;by)&gt;=TOP&amp;&amp;(lsnake1-&gt;by+SIZE)&lt;=BOTTOM){if((lsnake1-&gt;bx==dx)&amp;&amp;(lsnake1-&gt;by==dy)){t=t-800;/*t减小表示延迟减小,即表示蛇移动速度加快*/setfillstyle(1,0);bar(540,60,600,100);qufood(dx,dy);add1=1;s1++;setfillstyle(1,4);bar(560,60,600,100);numtostr(s1,w);outtextxy(570,70,w);outtextxy(570,80,&quot;Red&quot;);}}else{k1=0;/*freesnake(lsnake1);*/}if(k1&amp;&amp; nothit(lsnake1,lsnake2,fx1,fy1)){paintsnake(lsnake1,2,2);changsnake(lsnake1,fx1,fy1,add1);paintsnake(lsnake1,5,4);}if(add1==1||add2==1)/*当两条蛇有一条吃到食物是,重新设置食物*/ setfood(&amp;dx,&amp;dy,lsnake1,lsnake2);/*产生食物*/delay(t);delay(t);delay(t);delay(t);delay(t);}if(j==0){if(s1==SL){settextstyle(0,0,3);outtextxy(100,200,&quot;You are Win!&quot;);getch();settextstyle(1,0,1);}else{settextstyle(0,0,5);outtextxy(100,200,&quot;GAME OVER !&quot;);getch();settextstyle(1,0,1);}}else{if(s1&gt;s2){settextstyle(0,0,5);outtextxy(100,200,&quot;Red Win!&quot;);getch();settextstyle(1,0,1);}else if(s1&lt;s2){settextstyle(0,0,5);outtextxy(100,200,&quot;Blue Win!&quot;); getch();settextstyle(1,0,1);}else{settextstyle(0,0,5);outtextxy(100,200,&quot;A draw!&quot;); getch();settextstyle(1,0,1);}}}}。

相关文档
最新文档