C贪吃蛇代码

合集下载

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

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

贪吃蛇 C语言代码

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

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

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

#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <string.h>#include <time.h>const int H = 8; //地图的高const int L = 16; //地图的长char GameMap[H][L]; //游戏地图int key; //按键保存int sum = 1, over = 0; //蛇的长度, 游戏结束(自吃或碰墙)int dx[4] = {0, 0, -1, 1}; //左、右、上、下的方向int dy[4] = {-1, 1, 0, 0};struct Snake //蛇的每个节点的数据类型{int x, y; //左边位置int now; //保存当前节点的方向, 0,1,2,3分别为左右上下}Snake[H*L];const char Shead = '@'; //蛇头const char Sbody = '#'; //蛇身const char Sfood = '*'; //食物const char Snode = '.'; //'.'在地图上标示为空void Initial(); //地图的初始化void Create_Food(); //在地图上随机产生食物void Show(); //刷新显示地图void Button(); //取出按键,并判断方向void Move(); //蛇的移动void Check_Border(); //检查蛇头是否越界void Check_Head(int x, int y); //检查蛇头移动后的位置情况int main(){Initial();Show();return 0;}void Initial() //地图的初始化{int i, j;int hx, hy;system("title 贪吃蛇"); //控制台的标题memset(GameMap, '.', sizeof(GameMap)); //初始化地图全部为空'.' system("cls");srand(time(0)); //随机种子hx = rand()%H; //产生蛇头hy = rand()%L;GameMap[hx][hy] = Shead;Snake[0].x = hx; Snake[0].y = hy;Snake[0].now = -1;Create_Food(); //随机产生食物for(i = 0; i < H; i++) //地图显示{for(j = 0; j < L; j++)printf("%c", GameMap[i][j]);printf("\n");}printf("\n小小C语言贪吃蛇\n");printf("按任意方向键开始游戏\n");getch(); //先接受一个按键,使蛇开始往该方向走Button(); //取出按键,并判断方向}void Create_Food() //在地图上随机产生食物{int fx, fy;while(1){fx = rand()%H;fy = rand()%L;if(GameMap[fx][fy] == '.') //不能出现在蛇所占有的位置{GameMap[fx][fy] = Sfood;break;}}}void Show() //刷新显示地图{int i, j;while(1){_sleep(500); //延迟半秒(1000为1s),即每半秒刷新一次地图Button(); //先判断按键在移动Move();if(over) //自吃或碰墙即游戏结束{printf("\n**游戏结束**\n");printf("你的得分:%d\n",sum=10*(sum-1));getchar();break;}system("cls"); //清空地图再显示刷新吼的地图for(i = 0; i < H; i++){for(j = 0; j < L; j++)printf("%c", GameMap[i][j]);printf("\n");}printf("\n小小C语言贪吃蛇\n");printf("按任意方向键开始游戏\n");}}void Button() //取出按键,并判断方向{if(kbhit() != 0) //检查当前是否有键盘输入,若有则返回一个非0值,否则返回0 {while(kbhit() != 0) //可能存在多个按键,要全部取完,以最后一个为主key = getch(); //将按键从控制台中取出并保存到key中switch(key){ //左case 75: Snake[0].now = 0;break;//右case 77: Snake[0].now = 1;break;//上case 72: Snake[0].now = 2;break;//下case 80: Snake[0].now = 3;break;}}}void Move() //蛇的移动{int i, x, y;int t = sum; //保存当前蛇的长度//记录当前蛇头的位置,并设置为空,蛇头先移动x = Snake[0].x; y = Snake[0].y; GameMap[x][y] = '.';Snake[0].x = Snake[0].x + dx[ Snake[0].now ];Snake[0].y = Snake[0].y + dy[ Snake[0].now ];Check_Border(); //蛇头是否越界Check_Head(x, y); //蛇头移动后的位置情况,参数为: 蛇头的开始位置if(sum == t) //未吃到食物即蛇身移动哦for(i = 1; i < sum; i++) //要从蛇尾节点向前移动哦,前一个节点作为参照{if(i == 1) //尾节点设置为空再移动GameMap[ Snake[i].x ][ Snake[i].y ] = '.';if(i == sum-1) //为蛇头后面的蛇身节点,特殊处理{Snake[i].x = x;Snake[i].y = y;Snake[i].now = Snake[0].now;}else //其他蛇身即走到前一个蛇身位置{Snake[i].x = Snake[i+1].x;Snake[i].y = Snake[i+1].y;Snake[i].now = Snake[i+1].now;}GameMap[ Snake[i].x ][ Snake[i].y ] = '#'; //移动后要置为'#'蛇身}}void Check_Border() //检查蛇头是否越界{if(Snake[0].x < 0 || Snake[0].x >= H|| Snake[0].y < 0 || Snake[0].y >= L)over = 1;}void Check_Head(int x, int y) //检查蛇头移动后的位置情况{if(GameMap[ Snake[0].x ][ Snake[0].y ] == '.') //为空GameMap[ Snake[0].x ][ Snake[0].y ] = '@';elseif(GameMap[ Snake[0].x ][ Snake[0].y ] == '*') //为食物{GameMap[ Snake[0].x ][ Snake[0].y ] = '@';Snake[sum].x = x; //新增加的蛇身为蛇头后面的那个Snake[sum].y = y;Snake[sum].now = Snake[0].now;GameMap[ Snake[sum].x ][ Snake[sum].y ] = '#';sum++;Create_Food(); //食物吃完了马上再产生一个食物}elseover = 1;}。

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

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

贪吃蛇c语言代码

贪吃蛇c语言代码

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

贪吃蛇游戏c语言源代码

贪吃蛇游戏c语言源代码
settextstyle(0,0,4);
outtextxy(160,220,"Game Over");
loop1:key=bioskey(0);
if(key==Enter)
{cleardevice();
TheFirstBlock();
}
else
if(key==ESC)
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);
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);
{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)
void Snake_Bodyadd(void);

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

C语言贪吃蛇代码

C语言贪吃蛇代码
x=y=17;
head->x=17;
head->y=17;
score=0;
ms=300;
for(int i=0;i<35;++i)
outtextxy(i,35,"▓");
outtextxy(2,41,"游戏速度");
outtextxy(4,42,"300");
outtextxy(8,42,"得分");
ontimer(tally[2],ms*2,AI());
}
}
void kmsg(UINT ch)
{
switch(ch)
{
case 72:
if(x&&!map[x-1][y])
move(--x,y);
else if(map[x-1][y]==2)
add(--x,y);
else
end();
break;
case 80:
break;
case 77:
if(ch!=75)
ch=77;
break;
}
if(GetKeyState(VK_SPACE)&0x80)//如果空格键是按下状态,将速度临时调整至60ms
ontimer(tally[0],60,kmsg(ch));
else
ontimer(tally[1],ms,kmsg(ch));//否则按照变量ms的速度运行游戏
head=head->n;
head->x=x;
head->y=y;
map[x][y]=1;
outtextxy(x,y,"■");

贪吃蛇c语言代码

贪吃蛇c语言代码

#include<stdio.h>#include<stdlib.h>#include<Windows.h>#include<conio.h>#include<time.h>char gamemap[20][40];//游戏地图大小20*40 int score=0;//当前分数//记录蛇的结点int x[800];//每个结点的行编号int y[800];//每个结点的列编号int len = 0;//蛇的长度//记录水果信息int fx=;//食物的横坐标int fy=00;//食物的纵坐标int fcount=0;//食物的数目//主要函数操作void createfood();//生成食物void PrintgameMap(int x[],int y[]);//画游戏地图void move(int x[],int y[]);//移动蛇int main(){srand(time(NULL));//初始化蛇头和身体的位置,默认刚开始蛇长为2 x[len] = 9;y[len] = 9;len++;x[len] = 9;y[len] = 8;len++;createfood();PrintgameMap(x,y);move(x,y);return 0;}void createfood(){if(0==fcount){int tfx=rand()%18+1;int tfy=rand()%38+1;int i,j;int have=0;//为0表示食物不是食物的一部分for(i=0;i<len;i++){for(j=0;j<len;j++){if(x[i]==fx&&y[j]==fy){have=1;break;}else{have=0;}}if(1==have)//若为蛇的一部分,执行下一次循环{continue;}else//否则生成新的水果{fcount++;fx=tfx;fy=tfy;break;}}}}//游戏地图void PrintgameMap(int x[],int y[]){int snake = 0,food=0;int i, j;//画游戏地图,并画出蛇的初始位置for (i = 0; i < 20; i++){for (j = 0; j < 40; j++){if (i == 0 && j >= 1 && j <= 38){gamemap[i][j] = '=';}else if (i == 19 && j >= 1 && j <= 38){gamemap[i][j] = '=';}else if (j == 0 || j == 39){gamemap[i][j] = '#';}else{gamemap[i][j] = ' ';}//判断蛇是否在当前位置int k;for ( k = 0; k < len; k++){if (i == x[k]&&j == y[k]){snake = 1;break;}else{snake = 0;}}{if(fcount&&fx==i&&fy==j){food=1;}else{food=0;}}//若蛇在当前位置if (1==snake ){printf("*");}else if(1==food){printf("f");}//若蛇不在当前位置并且当前位置没有水果else{printf("%c", gamemap[i][j]);}}printf("\n");}printf("score:%d",score);}//移动void move(int x[],int y[]){char s;s=getch();int move=0,beat=0;while (1){int cx[800];int cy[800];memcpy(cx, x, sizeof(int)*len); memcpy(cy, y, sizeof(int)*len); //头if (s=='w'){x[0]--;move=1;if(x[0]<=0){printf("Game over\n"); break;}}else if (s=='s'){x[0]++;move=1;if(x[0]>=19){printf("Game over\n"); break;}}else if (s=='a'){y[0] --;move=1;if(y[0]<=0){printf("Game over\n");break;}}else if (s=='d'){y[0]++;move=1;if(y[0]>=39){printf("Game over\n");break;}}//身体int i;for ( i = 1; i < len; i++){x[i] = cx[i - 1];y[i] = cy[i - 1];}for(i=1;i<len;i++)//要是咬到了自己{if(x[0]==x[i]&&y[0]==y[i]){beat=1;}else{beat=0;}}if(1==beat){printf("Game over\n");break;}if(1==move){if(fcount&&x[0]==fx&&y[0]==fy)//如果吃到了果子{//拷贝当前蛇头地址到第二个结点memcpy(x+1,cx,sizeof(int)*len); memcpy(y+1,cy,sizeof(int)*len); len++;fcount--;fx=0;fy=0;score++;createfood();}Sleep(70);system("cls");PrintgameMap( x, y);}elsecontinue;if(kbhit())//判断是否按下按键{s=getch();}}}。

贪吃蛇C语言源代码

贪吃蛇C语言源代码

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

贪吃蛇代码(C 实现)

贪吃蛇代码(C  实现)
system("CLS"); printf("¹ž¹ž£¬ÄćŹäĮĖ!×īŗóµĆ·Ö:%d\n",T.length*10-10); break; } } else if (order=='s') { jud=order; //printf("-->s\n"); if(map[sum/100+1][sum%100]!=-1) { for(i=T.tail;i!=T.head;) { temp=T.body[i]; map[temp/100][temp%100]=0; i++; i%=ML;
static int n=0; n++; n%=400+1; return card[n]; }
void www() {
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;) {
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 ddd() { int sum,i; sum=T.body[(T.head-1+ML)%ML]+1; 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++; i%=ap[sum/100][sum%100]=-1; i++; i%=ML; } while(1) { sum=getnum(); if(map[sum/100][sum%100]==0) {

贪吃蛇(C语言)

贪吃蛇(C语言)

贪吃蛇(C语言)#include#include#include#include#include//蛇头移动方向#define UP 1#define DOWN 2#define LEFT 3#define RIGHT 4〃死亡判定(葱墙或葱自己)#define KISSASS 1#define KISSWALL 2//坐标转化#define POINT(x,y) ((y)*80+(x)+1)// 将(x,y)坐标转化为一个int 类数值#define GETX(x) (((x)-1)%80)// 将int 类数值提取出原先的x#define GETY(y) (((y)-1)/80)// 同理,提取出yHANDLE Console;void Position(int x, int y); // 移动光标到(x,y) //Windows.hvoid DrawMap();// 画墙void ShowText(char *text);//根据字符串的长短智能打印出包围字符串的笑脸void ResetSnake();// 初始化贪吃蛇int RefreshSnake();// 更新蛇的移动void CreatFood();// 生成食物void Draw();//画出蛇身和食物void RefreshScreen();// 屏幕刷新void GameOver(int Type);// 游戏结束条件int Gaming();//代码跑起来char play = 0; ////值为1则继续游戏,值为0游戏退出char pause = 0; //值为1则暂停,值为0游戏继续char direction; // 蛇头方向int snake[500]; //snake[0]为蛇头int body; //蛇身体长度int newbody;//吃完食物新长的蛇身int addHead,deleteTail;//增加蛇头擦去蛇尾,使贪吃蛇动起来int food = 0; // 食物void main()(CONSOLE_CURSOR_INFO CurrInfo = { sizeof(CONSOLE_CURSOR_INFO), 0 };Console = GetStdHandle(STD_OUTPUT_HANDLE);DrawMap();ShowT ext("Copyright reserve by 博元");while(Gaming()){if (play)DrawMap();};return 0;}void Position(int x, int y)// 移动光标到(x,y) //Windows.h{COORD coors = { x, y };SetConsoleCursorPosition(Console, coors);}void DrawMap() // 画墙{int i;for (i = 3; i < 70; i = i + 12){Position(i, 0);printf("===我是墙===");}for (i = 0; i < 25; i = i + 1){Position(0, i);printf("|| ");}for (i = 3; i < 70; i = i + 12){Position(i, 24);printf("============");}for (i = 0; i < 25; i = i + 1){Position(76, i); printf("|| ");void ShowText(char *text) //根据字符串的长短智能打印出包围字符串的笑脸(int i;int strLength = strlen(text); // 得到字符串长度Position(40 - (strLength / 2)-1, 11);printf("%c”, 1);for (i = 0; i < strLength + 2; i++)(printf("%c", 1);}printf("%c", 1);Position(40 - (strLength / 2)-1, 12);printf("%c ", 1);printf(text);printf(" %c", 1);Position(40 - (strLength / 2)-1, 13);printf("%c", 1);for (i = 0; i < strLength + 2; i++)(printf("%c", 1);}printf("%c", 1);}void ResetSnake() //初始化贪吃蛇(int x, y;for (x = 39, y = 0; y < 2; y++)(snake[y] = POINT(x, 7 - y);}body = 2; //设定蛇身初始长度为2newbody = 6;addHead = 0;deleteTail = 0;direction = LEFT;}int RefreshSnake() 〃更新蛇的移动〃返回值为1游戏结束( int x, y;memcpy(snake + 1, snake, sizeof(int)*body);if (!newbody){deleteTail = snake[body];snake[body] = 0;}else{body++;newbody--;}x = GETX(snake[0]);y = GETY(snake[0]);switch (direction) //控制蛇头移动方向{case UP:y -= 1; //蛇头向上移动一格(对应坐标y-1 ) snake[0] = POINT(x, y);break;case DOWN:y += 1;snake[0] = POINT(x, y); break;case LEFT:x -= 1;snake[0] = POINT(x, y); break;case RIGHT:x += 1;snake[0] = POINT(x, y); break;}addHead = snake[0];if (x > 75 || x < 3 ||y > 23 || y < 1) // 检测是否撞墙(GameOver(KISSWALL);return 1;}int i;for (i = 1; i < body; i++)if (snake[0] == snake[i]) // 检测是否撞到自己身体(GameOver(KISSASS);return 1;}if (snake[0] == food)(while (1) //食物的位置不与蛇身重合(food = (rand() % (75 * 23));for (i = 0; snake[i]; i++)if (food == snake[i])// 检测是否吃到食物,吃到则reset食物food = 0;if (food) 〃如果food==0 则重新建立一个食物坐标break;}CreatFood(); // 吃了?再来一个!newbody = (rand() % 6) + 1; // 吃完食物蛇身增长一节}return 0;}void CreatFood() // 生成食物(if (GETX(food) > 75 || GETX(food) < 3 || GETY(food) > 23 || GETY(food) < 1) CreatFood;elsePosition(GETX(food), GETY(food));printf("%c”,4);}void Draw() //画出蛇身和食物(system("cls");int i;for (i = 0; snake[i]; i++)(Position(GETX(snake[i]), GETY(snake[i])); printf("%c”,1);}CreatFood();}void RefreshScreen() // 屏幕刷新(if (deleteTail)(Position(GETX(deleteTail), GETY(deleteTail)); printf("");}if (addHead)(Position(GETX(addHead), GETY(addHead)); printf("%c",1);}addHead = deleteTail = 0;}void GameOver(int Type) // 游戏结束条件(switch (Type)(case KISSASS://? 至ij 自己身体ShowT ext("NOOB !当你以光速绕着一棵树奔跑就会发现自己在葱自己!");break;case KISSWALL://撞墙ShowT ext("NOOB !你有考虑过墙的感受吗");}food = 0;play = 0;memset(snake, 0, sizeof(int) * 500); // 存初始化} int Gaming() // 执行int Keyboardinput;Sleep(60);// 速度if (kbhit())(Keyboardinput = getch();if (Keyboardi nput == 0 || Keyboardinput == 0xE0) (Keyboardinput = getch();switch (Keyboardi nput) // 方向控制(case 72:if (direction != DOWN) direction = UP;break;case 80:if (direction != UP)direction = DOWN;break;case 75:if (direction != RiGHT)direction = LEFT;break;case 77:if (direction != LEFT)direction = RiGHT;break;}}if (Keyboardi nput == '\r') // 暂停(if (!play)(play = 1;if (pause)(Draw();pause = 0;}}else(ShowT ext("不许暂停,继续葱!!");play = 0;pause =1;}}else if (KeyboardI nput == 0x1B) // 退出return 0; } if (play)(if (!food)(srand(clock());food = (rand() % (75 * 23)); ResetSnake();Draw();}else(if (!RefreshSnake())(RefreshScreen();}}}。

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语言简单贪吃蛇游戏代码

#include <stdio.h>#include <stdlib.h>#include <time.h>#include <CONIO.H>#include <AFX.H>intx[10]={0},y[10]={0},xx[20]={0},yy[20]={0},xxx[20],yyy[20],actx=0,acty=1,eggx[10]={13,2,11 },eggy[10]={5,4,4};time_t time1,time2;void eogame(){int i;system("cls");for(i=0;i<10;i++)printf("\n");printf(" game over !!");getch();system("exit");}void show(){int i,j,tempx,tempy,max=0,ifget=0;time(&time1);system("cls");for(i=0;i<10;i++){xx[i]=x[i];yy[i]=y[i];}for(i=0;i<10;i++){xx[10+i]=eggx[i];yy[10+i]=eggy[i];}for (j=0;j<19;j++)for (i=0;i<19-j;i++){if (yy[i]>yy[i+1]){tempy=yy[i];yy[i]=yy[i+1];yy[i+1]=tempy;tempx=xx[i];xx[i]=xx[i+1];xx[i+1]=tempx;}else if(yy[i]==yy[i+1]&&xx[i]>xx[i+1]){tempx=xx[i];xx[i]=xx[i+1];xx[i+1]=tempx;}}yyy[0]=yy[0];xxx[0]=xx[0];for (i=0;i<19;i++){yyy[i+1]=yy[i+1]-yy[i];if(yy[i+1]==yy[i])xxx[i+1]=xx[i+1]-xx[i];else xxx[i+1]=xx[i+1];}for(i=0;i<20;i++){for(j=0;j<yyy[i];j++)printf("\n");for (j=1;j<xxx[i];j++)printf(" ");if(xxx[i]>0||yyy[i]>0)printf("@ ");}time(&time2);while(time2-time1<1)time(&time2);for(i=0;i<10;i++)if(x[0]+actx==eggx[i]&&y[0]+acty==eggy[i]){ifget++;eggx[i]=0;eggy[i]=0;} for(i=0;i<9;i++){if(x[i+1]!=0||y[i+1]!=0||ifget!=0){xx[i+1]=x[i];yy[i+1]=y[i];}else{xx[i+1]=0;yy[i+1]=0;}}if(ifget>0)ifget--;x[0]=x[0]+actx;y[0]=y[0]+acty;for(i=1;i<10;i++){x[i]=xx[i];y[i]=yy[i];}if(x[0]==0||x[0]>20||y[0]==0||y[0]>20)eogame();for(i=1;i<10;i++)if(x[0]==x[i]&&y[0]==y[i])eogame();}DWORD WINAPI KEYBOARD(LPVOID IpParam) {char key,guard=2,ch;insert:key=getch();if(key==-32)guard=0;else guard++;if(guard==1)switch(key){case 72: actx=0;acty=-1;break;case 80: actx=0;acty=1;break;case 75: actx=-1;acty=0;break;case 77: actx=1;acty=0;break;default: break;}goto insert;}void main(){x[0]=1;y[0]=1;system("mode con:cols=40 lines=20");CreateThread(NULL,0,KEYBOARD,NULL,0,NULL);while (1)show();}。

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

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

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

C语言版贪吃蛇代码

C语言版贪吃蛇代码

C语言版贪食蛇游戏源代码(我自己写的)热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为什么我们在讲故事的时候总要加上从前?开了一夏的花,终落得粉身碎骨,却还笑着说意义。

#define N 200#include<graphics.h>#include<stdlib.h>#include<dos.h>#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define Esc 0x011bint i,key;int score=0;int gamespeed=50000;struct Food{int x;int y;int yes;}food;struct Snake{int x[N];int y[N];int node;int direction;int life;}snake;void Init();void Close();void DrawK();void GamePlay();void GameOver();void PrScore();void main(){ Init();DrawK();GamePlay();Close();}void Init(){int gd=DETECT,gm;initgraph(&gd,&gm,"C:\\tc");cleardevice();}void DrawK(){setbkcolor(LIGHTGREEN);setcolor(11);setlinestyle(SOLID_LINE,0,THICK_WIDTH);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(){randomize();food.yes=1;snake.life=0;snake.direction=1;snake.x[0]=100;snake.y[0]=100;snake.x[1]=110;snake.y[1]=100 ;snake.node=2;PrScore();while(1){while(!kbhit()){ if(food.yes==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.yes=0;}if(food.yes==0){setcolor(GREEN);rectangle(food.x,food.y,food.x+10,food.y-10); }for(i=snake.node-1;i>0;i--){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}switch(snake.direction){case 1:snake.x[0]+=10;break;case 2:snake.x[0]-=10;break;case 3:snake.y[0]-=10;break;case 4:snake.y[0]+=10;break;}for(i=3;i<snake.node;i++){if(snake.x[i]==snake.x[0]&&snake.y[i]==snake.y[0]){ GameOver();snake.life=1;break;}}if(snake.x[0]<55||snake.x[0]>595||snake.y[0]<55||snake.y[0]>455){GameOver();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.node]=-20;snake.y[snake.node]=-20;snake.node++;food.yes=1;score+=10;PrScore();}setcolor(4);for(i=0;i<snake.node;i++)rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);delay(gamespeed);setcolor(0);rectangle(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+10,s nake.y[snake.node-1]-10);}if(snake.life==1)break;key=bioskey(0);if(key==Esc)break;else if(key==UP&&snake.direction!=4)snake.direction=3;else if(key==RIGHT&&snake.direction!=2) snake.direction=1;else if(key==LEFT&&snake.direction!=1) snake.direction=2;else if(key==DOWN&&snake.direction!=3) snake.direction=4;}}void GameOver(){cleardevice();PrScore();setcolor(RED);settextstyle(3,0,4);outtextxy(100,100,"Mengmeng,i love you!"); getch();}void PrScore(){char str[10];setfillstyle(SOLID_FILL,YELLOW);bar(50,15,220,35);setcolor(6);settextstyle(0,0,2);sprintf(str,"score:%d",score);outtextxy(55,20,str);}void Close(){ getch();closegraph();}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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();
}
}
// 清除整条蛇
public void Clear()
{
for (int i=0; i {
((SnakeNode)alSnake[i]).Clear();
}
}
// 重设运动方向
}
public bool IsOutOfRange
{
set { bIsOutOfRange = value; }
get { return bIsOutOfRange;}
}
public Snake() : this(null , 20 , 5)
{
//
// TODO: 在此处添加构造函数逻辑
Count++;
((SnakeNode)alSnake[Count - 1]).Draw();
}
// 去尾
public void RemoveTrail()
{
if (alSnake.Count>1)
{
PreTrailX = ((SnakeNode)alSnake[Count - 1]).CenterX;
}
public int NextHeadY
{
set { iNextHeadY = value; }
get { return iNextHeadY; }
}
public int PreTrailX
{
set { iPreTrailX = value; }
get { return iPreTrailX; }
PreTrailY = ((SnakeNode)alSnake[Count - 1]).CenterY;
alSnake.RemoveAt(alSnake.Count - 1);
Count--;
CurrentTrailX = ((SnakeNode)alSnake[Count - 1]).CenterX;
alSnake.Clear();
}
// 清除非受控资源
}
// 加头
public void AddHead()
{
alSnake.Insert(0 , new SnakeNode(DcControl , NextHeadX , NextHeadY , Radius));
//
}
public Snake(Control control , int iCount , int iRadius)
{
DcControl = control;
Count = iCount;
Ra CurrentTrailX = PreTrailX = 5;
private int iCount; // 骨节的总数
private int iRadius; // 骨节的半径
private static int iCurrentHeadX; // 当前蛇头的中心坐标 X
private static int iCurrentHeadY; // 当前蛇头的中心坐标 Y
get { return iCurrentHeadY; }
}
public int CurrentTrailX
{
set { iCurrentTrailX = value; }
get { return iCurrentTrailX; }
}
public int CurrentTrailY
}
public int Count
{
set { iCount = value; }
get { return iCount; }
}
public int Radius
{
set { iRadius = value; }
get { return iRadius; }
CurrentHeadX -= 2 * Radius;
NextHeadX = CurrentHeadX + 2 * Radius;
NextHeadY = CurrentHeadY;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose( bool bDisposing )
{
if (bDisposing)
{
// 调用 Dispose 处理受控资源中的字段
MoveDirection = 0x1000;
CurrentHeadX = CurrentHeadY = NextHeadX = NextHeadY = 5;
}
public int PreTrailY
{
set { iPreTrailY = value; }
get { return iPreTrailY; }
}
public bool IsEatself
{
set { bIsEatself = value; }
get { return bIsEatself; }
private static int iCurrentTrailX; // 当前蛇尾的中心坐标 X
private static int iCurrentTrailY; // 当前蛇尾的中心坐标 Y
private static int iNextHeadX; // 下一时刻蛇头的中心坐标 X
public void ResetMoveDirection(string strKeyData)
{
// 获取键盘输入
int iKeyDirection;
switch (strKeyData)
{
case "W":
case "Up":
iKeyDirection = 0x0001;
// 清除尾(将蛇尾用背景色填充)
((SnakeNode)alSnake[Count-1]).Clear();
// 去尾(将蛇尾从 ArrayList 中删除)
RemoveTrail();
}
// 画整条蛇
public void Draw()
{
for (int i=0; i {
{
set { dcControl = value; }
get { return dcControl;}
}
public int MoveDirection
{
set { iMoveDirection = value; }
get { return iMoveDirection; }
{
#region Snake 蛇身
///
/// Snake 的摘要说明。
///
public class Snake
{
private Control dcControl;
private static int iMoveDirection = 0x1000; // 蛇的运动方向 , 初始化为 right - 0x1000
// Snake.cs Begin
//
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Timers;
namespace GreedySnake
CurrentHeadX = NextHeadX;
CurrentHeadY = NextHeadY;
Count++;
}
// 加尾
相关文档
最新文档