VC贪吃蛇源码

合集下载

C贪吃蛇代码

C贪吃蛇代码
break;
case "S":
case "Down":
iKeyDirection = 0x0010;
break;
case "A":
case "Left":
iKeyDirection = 0x0100;
break;
for (int i=0 ; i {
alSnake.Insert(0 , new SnakeNode(DcControl , CurrentHeadX , CurrentHeadY , Radius));
CurrentHeadX += 2 * Radius;
}
}
public int CurrentHeadX
{
set { iCurrentHeadX = value; }
get { return iCurrentHeadX; }
}
public int CurrentHeadY
{
set { iCurrentHeadY = value; }
{
set { iCurrentTrailY = value; }
get { return iCurrentTrailY; }
}
public int NextHeadX
{
set { iNextHeadX = value; }
get { return iNextHeadX; }
else
MoveDirection = iKeyDirection; // 运动方向等于按键方向
((SnakeNode)alSnake[i]).Draw();

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语言贪吃蛇源码

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

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

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

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语言编写)

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

贪吃蛇(VC完美运行)

贪吃蛇(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语言源代码

贪吃蛇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可以成功编译运行)

贪吃蛇源代码(需要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代码(贪吃蛇)

C代码(贪吃蛇)

C代码(贪吃蛇)C代码(贪吃蛇)#include <stdio.h>#include <bios.h>#include <conio.h>#include <stdlib.h> /*调用randomize()函数*/ #include <time.h>#define SPACE 0X3920#define ESC 0x011b#define UP 0x4800#define DOWN 0x5000#define LEFT 0x4b00#define RIGHT 0x4d00typedef struct{int x;int y;}point;DrawBody(int x, int y){gotoxy(x, y);printf("%c\b", 3);}DrawHead(int x, int y){gotoxy(x, y);printf("%c\b", 2);}DrawSpace(int x, int y){gotoxy(x, y);printf(" ");}void bring_food(point man[],int n,point *food) /*随机产生食物*/{int x,y;int i,k = 0;randomize();while (k == 0){k = 1;x = rand() % 58;y = rand() % 23;if (x < 3 || y < 3) /*产生的食物不在框内*/{k = 0;continue;}for (i = 0; i < n; ++i)if ((x == man[i].x) && (y == man[i].y)) /*如果产生的食物坐标和蛇身的某个坐标相同,则不符合条件*/{ k = 0;break;}}food->x = x;food->y = y;gotoxy(x,y);/*在x,y出产生食物*/printf("*");}void DrawWall()/*画边框函数*/{ int i,j;for (j = 2, i = 2; i < 60; ++i)textcolor(GREEN);putch(219);gotoxy(i, j+22);textcolor(GREEN);putch(219);}for (j = 2, i = 2; i < 25; ++i){ gotoxy(j, i);textcolor(GREEN);putch(219);gotoxy(j+57, i);textcolor(GREEN);putch(219);}}void message(int score) /*该函数输出信息*/ {if (score == 10 || score == 20 || score == 35){gotoxy(65,6);printf("Score: %d",score);textattr(5);cprintf(" You Win ");gotoxy(20,12);cprintf("Thank you baby!");getch();return ;}gotoxy(65,6);printf("Score: %d",score);gotoxy(65,7);printf("Space: pause");}int main() /*该程序运行将用方向键控制蛇的移动*/{point man[60]; /*记录蛇坐标*/point food; /*记录食物坐标*/int key = DOWN,keyb,key1 = DOWN;int i;int n = 10;int score = 0;long j,time;clrscr();for (i = 0; i < 10; ++i)man[i].x = 12 - i;for (i = 0; i < 10; ++i)man[i].y = 3;DrawWall();/*画边框*/for (i = 9; i > 0; --i)DrawBody(man[i].x, man[i].y); /*画蛇身*/ DrawHead(man[i].x, man[i].y); /*画蛇头*/ message(score);bring_food(man,10,&food); /*产生食物*/ while (key != ESC){if (bioskey(1) != 0) /*如果有键按下就接收键盘值*/keyb = bioskey(0);if ((keyb == SPACE) || (keyb == ESC) || (keyb == UP) || (keyb == DOWN) || (keyb == LEFT) || (keyb == RIGHT))key = keyb;switch (key){case UP:if (key1 == DOWN)key = key1;break;case DOWN:if (key1 == UP)key = key1;break;case LEFT:if (key1 == RIGHT)key = key1;break;case RIGHT:if (key1 == LEFT)key = key1;break;case SPACE:sleep(3);if (man[0].x == man[1].x)/*暂停前沿y方向移动*/{if (man[0].y < man[1].y)key = UP;elsekey = DOWN;}else{if (man[0].x < man[1].x)key = LEFT;elsekey = RIGHT;}break;defualt:break;}switch (key){case UP:DrawSpace(man[n-1].x, man[n-1].y);for (i = n-1; i > 0 ; --i){man[i].x = man[i-1].x;man[i].y = man[i-1].y;}--man[0].y;for (i = n-1; i > 0; --i)DrawBody(man[i].x, man[i].y);DrawHead(man[i].x, man[i].y);break;case DOWN:DrawSpace(man[n-1].x, man[n-1].y);for (i = n-1; i > 0 ; --i){man[i].x = man[i-1].x;man[i].y = man[i-1].y;}++man[0].y;for (i = n-1; i > 0; --i)DrawBody(man[i].x, man[i].y);DrawHead(man[i].x, man[i].y);break;case LEFT:DrawSpace(man[n-1].x, man[n-1].y);for (i = n-1; i > 0 ; --i){man[i].x = man[i-1].x;man[i].y = man[i-1].y;}--man[0].x;for (i = n-1; i > 0; --i)DrawBody(man[i].x, man[i].y);DrawHead(man[i].x, man[i].y);break;case RIGHT:DrawSpace(man[n-1].x, man[n-1].y);for (i = n-1; i > 0 ; --i){man[i].x = man[i-1].x;man[i].y = man[i-1].y;}++man[0].x;for (i = n-1; i > 0; --i)DrawBody(man[i].x, man[i].y);DrawHead(man[i].x, man[i].y);break;/* defualt:break; */}if ((man[0].x < 3) || (man[0].x > 58) || (man[0].y < 3) || (man[0].y > 23)) /*碰到边框*/break;for (i = 2; i < n; ++i)if (man[0].x == man[i].x && man[0].y == man[i].y)/*碰到自己身体*/{key = ESC;break;}if ((man[0].x == food.x) && (man[0].y == food.y))/*吃到食物*/{ score ++;message(score);n ++;/*蛇身长度加1*/bring_food(man,n,&food); /*再产生一个食物*/}time = (score < 10) ? 500000 : ((score < 20) ? 400000 : ((score <30) ? 300000 : 200000));for (j = 1; j < time ; ++j) /*该循环用来控制时间*/if ((j != 0) && (j % 8 == 0))j = j + 2 - 1*2;else if ((j != 0) && (j % 9 != 1))j = j + 1 - 1 * 1 * 1;else j = j+1;key1 = key; /*记录下本次的有效按键*/}if (score != 10 && score != 20 && score != 35){ gotoxy(20,10);textattr(2);cprintf(" Game Over ");gotoxy(20,12);cprintf("Thank you baby!");getch();}return 0;}。

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语言版贪食蛇游戏源代码(我自己写的)热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语言源代码

Ì°³ÔÉßÓÎÏ·cÓïÑÔÔ´´úÂë.txtÊÀÉÏ×îÕä¹óµÄ²»ÊÇÓÀÔ¶µÃ²»µ½»òÒѾ-µÃµ½µÄ£¬¶øÊÇÄãÒѾ-µÃµ½²¢ÇÒËæʱ¶¼ÓпÉÄÜʧȥµÄ¶«Î÷£¡°®ÇéÊǵƣ¬ÓÑÇéÊÇÓ°×Ó¡£µÆÃðʱ£¬Äã»á·¢ÏÖÖÜΧ¶¼ÊÇÓ°×Ó¡£ÅóÓÑ£¬ÊÇÔÚ×îºó¿ÉÒÔ¸øÄãÁ¦Á¿µÄÈË¡£#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);}。

简单贪吃蛇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("加速将能得到更高的分数。

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

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

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

贪吃蛇C语言编码

贪吃蛇C语言编码

#include<bios.h>#include<conio.h>#include<stdio.h>#include<process.h>#include<stdlib.h>#define MAX_LENGTH 100#define LEFT 0x4b00#define RIGHT 0x4d00#define UP 0x4800#define DOWN 0x5000#define PAUSE 0x1970 /* p key */#define ESC 0x11b#define TIME_LIMIT 4 /*Òƶ¯ËÙ¶È*/#define SNAKE 2#define WALL 1#define WCOLOR WHITE#define BKCOLOR BLACK#define SCOLOR WHITE#define FOOD 15#define FCOLOR RED#define X 20#define Y 2struct snake{int x;int y;}snk[MAX_LENGTH];int bkey;int box[22][22];int begin ,end,where_x,where_y,eat;int direction = 0,dead=0,pre_direction;void initbox(){int i,j;for(i=0;i<22;i++)for(j=0;j<22;j++)box[i][j]=0;for(i=0;i<22;i++)box[i][21] = box[21][i] = box[0][i] = box[i][0] = 1;textbackground(BKCOLOR);textcolor(WCOLOR);for(i=0;i<22;i++)for(j=0;j<22;j++)if( box[i][j]==1 ) { gotoxy(X+i,Y+j); putch(W ALL); }}int timeover(){static long int tm1,tm2;tm1=biostime(0,0l);if(tm1 - tm2 >TIME_LIMIT ) { tm2 = tm1; return 1;}return 0;}void go_ahead(){int mid = begin;if(direction == 0 )return;if(begin == 0 ) begin = MAX_LENGTH-1;else begin -= 1;if(direction == UP) { snk[begin].x = snk[mid].x ; snk[begin].y = snk[mid].y-1; }else if(direction == DOWN ){snk[begin].x = snk[mid].x ; snk[begin].y = snk[mid].y+1; } else if(direction == LEFT){snk[begin].x = snk[mid].x-1 ; snk[begin].y = snk[mid].y; } else if(direction == RIGHT){snk[begin].x = snk[mid].x+1 ; snk[begin].y = snk[mid].y; } if(box[snk[begin].x][snk[begin].y] == 1) dead=1;gotoxy(X+snk[begin].x,Y+snk[begin].y);textcolor(SCOLOR);putch(SNAKE);box[snk[begin].x][snk[begin].y] = 1;if(eat != 1){ gotoxy(X+snk[end].x,Y+snk[end].y);textcolor(BKCOLOR);putch('');if(end == 0) end = MAX_LENGTH-1;else end -= 1;box[snk[end].x][snk[end].y] = 0;}}void do_action(){switch(bkey){case UP : if(direction != DOWN) direction = UP; break;case DOWN : if(direction != UP ) direction = DOWN; break;case LEFT : if(direction != RIGHT) direction = LEFT; break;case RIGHT: if(direction != LEFT ) direction = RIGHT; break;case PAUSE : getch();bkey = direction; break;case ESC : exit(0);break;default : return;}}do_eat(){if((snk[begin].x == where_x) && (snk[begin].y == where_y) ) {eat = 1;if(begin == 0 ) begin = MAX_LENGTH -1 ;else begin -= 1;snk[begin].x = where_x ;snk[begin].y = where_y;}}void putfood(){do{where_x = random(20)+1;where_y = random(20)+1;}while(box[where_x][where_y]==1);textcolor(FCOLOR);gotoxy(X+where_x,Y+where_y);putch(FOOD);}main(){do{dead= 0;bkey= 0;direction = 0;clrscr();textcolor(WHITE);gotoxy(1,1);printf("press direction keys for start\n");printf("press p for PAUSE\n");printf("press ESC for EXIT\n ");initbox();begin = end = MAX_LENGTH-1;box[9][9] = 0;snk[begin].x = 9;snk[begin].y = 9;gotoxy(X+snk[begin].x,Y+snk[begin].y);textcolor(SCOLOR);putch(SNAKE);putfood();eat = 0;do{ do_eat();if(eat == 1 ) { putfood(); eat = 0; }while( !timeover() )if( bioskey(1) )bkey = bioskey(0);do_action();go_ahead();}while( !dead );textcolor(RED);gotoxy(1,24);printf("dou you want to try again y/n");do { bkey = bioskey(0); }while(bkey!=0x1579 && bkey!=0x316e); if(bkey == 0x316e )break;}while(1);}。

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

int m=1;
int sum=0;// 分数
int b[17][29];
typedef struct line //一字形,竖着
{
int x,y; //coordinates
}line ,*l;
void gotoxy(int a,int b) //获取光标位置
{
s[0].x=x;s[0].y=y;
for(int i=1;i<4;i++)
{
s[i].x=s[i-1].x+1;
s[i].y=y;
}
}
void exportdown(int x,int y,l &a) //处理竖着1的函数
{
a[0].x=x;a[0].y=y;
s[0].x++; exportdown(s[0].x,s[0].y,s);
if(judgement(s)) s[0].x--;
exportdown(s[0].x,s[0].y,s); print(s); //清掉左边的1,令尾的横坐标加一,输出往右移一位的1
if(b[j][d]) {b[j+1][d]=1;b[j][d]=0;gotoxy(d,j);cout<<' ';}
}
}
for(i=3;i<=16;i++)
for(j=2;j<=13;j++)
if(b[i][j]) {gotoxy(j,i);cout<<'a';}
for(int i=1;i<4;i++)
{
a[i].y=a[i-1].y-1;
a[i].x=x;
}
}
int judgement(l &s) // b[16][29] //3-16 1-23
{
int n=0;
if(s[0].y==17||s[0].x<=1||s[3].x>=14||b[s[0].y][s[0].x]||b[s[1].y][s[1].x]||b[s[2].y][s[2].x]||b[s[3].y][s[3].x])
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
GetConsoleCursorInfo(hOut,&cci);
cci.bVisible=0;//赋1为显示,赋0为隐藏
l s=(l)malloc (4*sizeof(line));
while(j)
{
i=1;
n1=rand()%2;
k='s';
if(n1) exportdown(5,6,s);
else exportacross(5,3,s);
if(judgement(s))
{
s[0].y--;
exportdown(s[0].x,s[0].y,s);
else {print(s); n1=0; } // 从1变一,变形成功
break;
}
Sleep(100);
}//if(n2)
else
{
switch(k)
{
break;
case 'w':clear(s);
exportdown(s[1].x,s[1].y+1,s);
if(judgement(s)) { exportacross(s[1].x-1,s[1].y,s); print(s);} //没变形成功,没空间
// judgement(s);
// if(!m) break;
if(n1)
{
gotoxy(s[3].x,s[3].y); cout<<' ';
s[0].y++;
exportdown(s[0].x,s[0].y,s);
print(s);
while(i)
{
if(n1)
{
switch(k)
{
// case 's':s[1].y++;break;
case 'd':clear(s); //将左边的清空
cout<<'a';
}
}
void clear(l &s)
{
for(int i=0;i<4;i++)
{
gotoxy(s[i].x,s[i].y);
cout<<' ';
}
}
void exportacross(int x,int y,l &s) //处理横着1的函数
printf("║ ║\n");
printf("╠══════╣\n");
printf("║ ║\n");//29,3-16
printf("║ ║\n");
printf("║ ║\n");
break;
case 'a':clear(s);
s[0].x--; exportacross(s[0].x,s[0].y,s);
if(judgement(s)) s[0].x++;
exportacross(s[0].x,s[0].y,s); print(s);
for(i=3;i<=16;i++) //行
{
n=0;
for(j=2;j<=13;j++) //列
if(b[i][j]!=1) {n=1; break;}
if(!n) a[c++]=i;
}
for(i=0;i<=3;i++)
break;
case 'w':clear(s);
exportacross(s[1].x-1,s[1].y,s);
if(judgement(s)) {exportdown(s[1].x,s[1].y+1,s); print(s);} //没变形成功,没空间
printf("║ ║\n");
printf("║ ║\n");
printf("║ ║\n");
printf("║ ║\n");
printf("║ ║\n");
switch(c)
{
case 1: gotoxy(11,1);sum+=1; cout<<sum;break;
case 2: gotoxy(11,1);sum+=4;cout<<sum;break;
case 3: gotoxy(11,1);sum+=6;cout<<sum;break;
#ine<windows.h>
#include<stdio.h>
#include <conio.h>
#include<time.h>
using namespace std;
//extern up();extern right();extern down();extern left();
n=1;
return n;
}
int gameover(l &s)
{
int i=0;
if(s[3].y<=2) i=1;
return i;
}
void getscore()
{
int i,j,n=0,a[4],c=0,d;
for(j=0;j<=3;j++) a[j]=0;
printf("║ ║\n");
printf("╚══════╝\n");
gotoxy(3,1);cout<<"分数:";
}
void print(l &s)
{
for(int i=0;i<4;i++)
{
gotoxy(s[i].x,s[i].y);
case 4: gotoxy(11,1);sum+=10;cout<<sum;break;
}
Sleep(100);
}
void main() //输出函数全部要重新写
{
char k,n1,i=1,c,j=1;
create_window();
hidden();
{
COORD pos;
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
pos.X=a;
pos.Y=b;
SetConsoleCursorPosition(hOut, pos);
}
void hidden()//隐藏光标
printf("║ ║\n");
printf("║ ║\n");
printf("║ ║\n");
printf("║ ║\n");
相关文档
最新文档