c语言贪吃蛇最简单代码(c语言贪吃蛇最简单代码图片)
贪吃蛇游戏的C语言编程
#include windows.h
#include ctime
#include iostream
#include vector
#include queue
using namespace std;
#ifndef SNAKE_H
#define SNAKE_H
class Cmp
{
friend class Csnake;
int rSign; //横坐标
int lSign; //竖坐标
public:
// friend bool isDead(const Cmp cmp);
Cmp(int r,int l){setPoint(r,l);}
Cmp(){}
void setPoint(int r,int l){rSign=r;lSign=l;}
Cmp operator-(const Cmp m)const
{
return Cmp(rSign-m.rSign,lSign-m.lSign);
}
Cmp operator+(const Cmp m)const
{
return Cmp(rSign+m.rSign,lSign+m.lSign);
}
};
const int maxSize = 5; //初始蛇身长度
class Csnake
{
Cmp firstSign; //蛇头坐标
Cmp secondSign;//蛇颈坐标
Cmp lastSign; //蛇尾坐标
Cmp nextSign; //预备蛇头
int row; //列数
int line; //行数
int count; //蛇身长度
vectorvectorchar snakeMap;//整个游戏界面
queueCmp snakeBody; //蛇身
public:
int GetDirections()const;
char getSymbol(const Cmp c)const
//获取指定坐标点上的字符
{
return snakeMap[c.lSign][c.rSign];
}
Csnake(int n)
//初始化游戏界面大小
{
if(n20)line=20+2;
else if(n30)line=30+2;
else line=n+2;
row=line*3+2;
}
bool isDead(const Cmp cmp)
{
return ( getSymbol(cmp)=='@' || cmp.rSign == row-1
|| cmp.rSign== 0 || cmp.lSign == line-1 ||
cmp.lSign == 0 );
}
void InitInstance(); //初始化游戏界面
bool UpdataGame(); //更新游戏界面
void ShowGame(); //显示游戏界面
};
#endif // SNAKE_H
using namespace std;
//测试成功
void Csnake::InitInstance()
{
snakeMap.resize(line); // snakeMap[竖坐标][横坐标]
for(int i=0;iline;i++)
{
snakeMap[i].resize(row);
for(int j=0;jrow;j++)
{
snakeMap[i][j]=' ';
}
}
for(int m=1;mmaxSize+1;m++)
{
//初始蛇身
snakeMap[line/2][m]='@';
//将蛇身坐标压入队列
snakeBody.push(Cmp(m,(line/2)));
//snakeBody[横坐标][竖坐标]
}
//链表头尾
firstSign=snakeBody.back();
secondSign.setPoint(maxSize-1,line/2);
}
//测试成功
int Csnake::GetDirections()const
{
if(GetKeyState(VK_UP)0) return 1; //1表示按下上键
if(GetKeyState(VK_DOWN)0) return 2; //2表示按下下键
if(GetKeyState(VK_LEFT)0) return 3; //3表示按下左键
if(GetKeyState(VK_RIGHT)0)return 4; //4表示按下右键
return 0;
}
bool Csnake::UpdataGame()
{
//-----------------------------------------------
//初始化得分0
static int score=0;
//获取用户按键信息
int choice;
choice=GetDirections();
cout"Total score: "scoreendl;
//随机产生食物所在坐标
int r,l;
//开始初始已经吃食,产生一个食物
static bool eatFood=true;
//如果吃了一个,才再出现第2个食物
if(eatFood)
{
do
{
//坐标范围限制在(1,1)到(line-2,row-2)对点矩型之间
srand(time(0));
r=(rand()%(row-2))+1; //横坐标
l=(rand()%(line-2))+1;//竖坐标
//如果随机产生的坐标不是蛇身,则可行
//否则重新产生坐标
if(snakeMap[l][r]!='@')
{snakeMap[l][r]='*';}
}while (snakeMap[l][r]=='@');
}
switch (choice)
{
case 1://向上
//如果蛇头和社颈的横坐标不相同,执行下面操作
if(firstSign.rSign!=secondSign.rSign)nextSign.setPoint(firstSign.rSign,firstSign.lSign-1);
//否则,如下在原本方向上继续移动
else nextSign=firstSign+(firstSign-secondSign);
break;
case 2://向下
if(firstSign.rSign!=secondSign.rSign)nextSign.setPoint(firstSign.rSign,firstSign.lSign+1);
else nextSign=firstSign+(firstSign-secondSign);
break;
case 3://向左
if(firstSign.lSign!=secondSign.lSign)nextSign.setPoint(firstSign.rSign-1,firstSign.lSign);
else nextSign=firstSign+(firstSign-secondSign);
break;
case 4://向右
if(firstSign.lSign!=secondSign.lSign)nextSign.setPoint(firstSign.rSign+1,firstSign.lSign);
else nextSign=firstSign+(firstSign-secondSign);
break;
default:
nextSign=firstSign+(firstSign-secondSign);
}
//----------------------------------------------------------
if(getSymbol(nextSign)!='*' !isDead(nextSign))
//如果没有碰到食物(且没有死亡的情况下),删除蛇尾,压入新的蛇头
{
//删除蛇尾
lastSign=snakeBody.front();
snakeMap[lastSign.lSign][lastSign.rSign]=' ';
snakeBody.pop();
//更新蛇头
secondSign=firstSign;
//压入蛇头
snakeBody.push(nextSign);
firstSign=snakeBody.back();
snakeMap[firstSign.lSign][firstSign.rSign]='@';
//没有吃食
eatFood=false;
return true;
}
//-----吃食-----
else if(getSymbol(nextSign)=='*' !isDead(nextSign))
{
secondSign=firstSign;
snakeMap[nextSign.lSign][nextSign.rSign]='@';
//只压入蛇头
snakeBody.push(nextSign);
firstSign=snakeBody.back();
eatFood=true;
//加分
score+=20;
return true;
}
//-----死亡-----
else {cout"Dead"endl;cout"Your last total score is "scoreendl; return false;}
}
void Csnake::ShowGame()
{
for(int i=0;iline;i++)
{
for(int j=0;jrow;j++)
coutsnakeMap[i][j];
coutendl;
}
Sleep(1);
system("cls");
}
int main()
{
Csnake s(20);
s.InitInstance();
//s.ShowGame();
int noDead;
do
{
s.ShowGame();
noDead=s.UpdataGame();
}while (noDead);
system("pause");
return 0;
}
这个代码可以运行的,记得给分啦
求 贪吃蛇C语言代码
#include windows.h
#include stdlib.h
#include time.h
#include stdio.h
#include string.h
#include conio.h
#define N 21
int apple[3],num;
char score[3];
char tail[3];
void gotoxy(int x, int y) //输出坐标
{
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void color(int b) //颜色函数
{
HANDLE hConsole = GetStdHandle((STD_OUTPUT_HANDLE)) ;
SetConsoleTextAttribute(hConsole,b) ;
}
int Block(char head[2]) //判断出界
{
if ((head[0] 1) || (head[0] N) || (head[1] 1) || (head[1] N))
return 1;
return 0;
}
int Eat(char snake[2]) //吃了苹果
{
if ((snake[0] == apple[0]) (snake[1] == apple[1]))
{
apple[0] = apple[1] = apple[2] = 0;
gotoxy(N+44,10);
color(13);
printf("%d",score[0]*10);
color(11);
return 1;
}
return 0;
}
void Draw(char **snake, int len) //蛇移动
{
if (apple[2])
{
gotoxy(apple[1] * 2, apple[0]);
color(12);
printf("●");
color(11);
}
gotoxy(tail[1] * 2, tail[0]);
if (tail[2])
{
color(num);
printf("★");
color(num);
}
else
printf("■");
gotoxy(snake[0][1] * 2, snake[0][0]);
color(num);
printf("★");
color(num);
putchar('\n');
}
char** Move(char **snake, char dirx, int *len) //控制方向
{
int i, full = Eat(snake[0]);
memcpy(tail, snake[(*len)-1], 2);
for (i = (*len) - 1; i 0; --i)
memcpy(snake[i], snake[i-1], 2);
switch (dirx)
{
case 'w': case 'W': --snake[0][0]; break;
case 's': case 'S': ++snake[0][0]; break;
case 'a': case 'A': --snake[0][1]; break;
case 'd': case 'D': ++snake[0][1]; break;
default: ;
}
if (full)
{
snake = (char **)realloc(snake, sizeof(char *) * ((*len) + 1));
snake[(*len)] = (char *)malloc(sizeof(char) * 2);
memcpy(snake[(*len)], tail, 2);
++(*len);
++score[0];
if(score[3] 16)
++score[3];
tail[2] = 1;
}
else
tail[2] = 0;
return snake;
}
void init(char plate[N+2][N+2], char ***snake_x, int *len) //初始化
{
int i, j;
char **snake = NULL;
*len = 3;
score[0] = score[3] =3;
snake = (char **)realloc(snake, sizeof(char *) * (*len));
for (i = 0; i *len; ++i)
snake[i] = (char *)malloc(sizeof(char) * 2);
for (i = 0; i 3; ++i)
{
snake[i][0] = N/2 + 1;
snake[i][1] = N/2 + 1 + i;
}
for (i = 1; i = N; ++i)
for (j = 1; j = N; ++j)
plate[i][j] = 1;
apple[0] = rand()%N + 1; apple[1] = rand()%N + 1;
apple[2] = 1;
for (i = 0; i N + 2; ++i)
{
gotoxy(0, i);
for (j = 0; j N + 2; ++j)
{
switch (plate[i][j])
{
case 0:
color(12);printf("□");color(11); continue;
case 1: printf("■"); continue;
default: ;
}
}
putchar('\n');
}
for (i = 0; i (*len); ++i)
{
gotoxy(snake[i][1] * 2, snake[i][0]);
printf("★");
}
putchar('\n');
*snake_x = snake;
}
void Manual()
{
gotoxy(N+30,2);
color(10);
printf("按 W S A D 移动方向");
gotoxy(N+30,4);
printf("按 space 键暂停");
gotoxy(N+30,8);
color(11);
printf("历史最高分为: ");
color(12);
gotoxy(N+44,8);
printf("%d",score[1]*10);
color(11);
gotoxy(N+30,12);
printf("你现在得分为: 0");
}
int File_in() //取记录的分数
{
FILE *fp;
if((fp = fopen("C:\\tcs.txt","a+")) == NULL)
{
gotoxy(N+18, N+2);
printf("文件不能打开\n");
exit(0);
}
if((score[1] = fgetc(fp)) != EOF);
else
score[1] = 0;
return 0;
}
int File_out() //存数据
{
FILE *fp;
if(score[1] score[0])
{gotoxy(10,10);
color(12);
puts("闯关失败 加油耶");
gotoxy(0,N+2);
return 0;
}
if((fp = fopen("C:\\tcs.txt","w+")) == NULL)
{
printf("文件不能打开\n");
exit(0);
}
if(fputc(--score[0],fp)==EOF)
printf("输出失败\n");
gotoxy(10,10);
color(12);
puts("恭喜您打破记录");
gotoxy(0,N+2);
return 0;
}
void Free(char **snake, int len) //释放空间
{
int i;
for (i = 0; i len; ++i)
free(snake[i]);
free(snake);
}
int main(void)
{
int len;
char ch = 'g';
char a[N+2][N+2] = {{0}};
char **snake;
srand((unsigned)time(NULL));
color(11);
File_in();
init(a, snake, len);
Manual();
while (ch != 0x1B) // 按 ESC 结束
{
Draw(snake, len);
if (!apple[2]) {
apple[0] = rand()%N + 1;
apple[1] = rand()%N + 1;
apple[2] = 1;
num++;
if(num8)
num=0;
}
Sleep(200-score[3]*10);
setbuf(stdin, NULL);
if (kbhit())
{
gotoxy(0, N+2);
ch = getche();
}
snake = Move(snake, ch, len);
if (Block(snake[0])==1)
{
gotoxy(N+2, N+2);
puts("你输了");
File_out();
Free(snake, len);
getche();
exit(0);
}
}
Free(snake, len);
exit(0);
}
C语言的贪吃蛇源代码
?
//******友情提示:如想速度快点,请改小_sleep(500)函数中参数*****??
#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("?????_\n");??
???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?]?=?'@';??
?else?
??if(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();??//食物吃完了马上再产生一个食物??
??}??
??else?
???over?=?1;??
}
如何用C语言写贪吃蛇
#includeconio.h #includegraphics.h #includetime.h #includestring.h #includemalloc.h #includestdio.h int grade=5,point=0,life=3; void set(),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.xhead_f-y==food.y) { Sleep(100); crate(); food.judge=0; point=point+(6-grade)*10; if(food.x30||food.y30||food.x570||food.y570) life++; menu(); } if(head_f-x5||head_f-x595||head_f-y5||head_f-y595) { 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-xhead_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; case '3': outtextxy(700,90,":1 2 3 4 5");grade=getch()-48;set();break; case '4': food.judge=0,grade=5;point=0;life=3;init_insect();menu();break; default: outtextxy(250,300,"输入错误!"); set();break; } } void menu() { char str[20],str1[]={"分数:"},str2[]={"难度:"},str3[]={"生命值:"}; init_graph(); sprintf(str,"%d",point); strcat(str1,str); outtextxy(640,50,str1); sprintf(str,"%d",grade); strcat(str2,str); outtextxy(640,70,str2); sprintf(str,"%d",life); strcat(str3,str); outtextxy(640,90,str3); outtextxy(640,110,"设置:ESC"); } void init_insect() { head_f=(struct bug *)malloc(sizeof(struct bug)); head_f-last=NULL; head_f-x=300; head_f-y=300; p2=head_f-next=p1=(struct bug *)malloc(sizeof(struct bug)); p1-last=head_f; p1-x=295; p1-y=300; p1=p1-next=(struct bug *)malloc(sizeof(struct bug)); p1-next=NULL; p1-x=290; p1-y=300; p1-last=p2; head_l=p1; } void move() { for(p1=head_f;p1!=NULL;p1=p1-next) { circle(p1-x,p1-y,2); } } void move_head() { } void move_body() { for(p1=head_l,p2=p1-last;p2!=NULL;p1=p2,p2=p2-last) { p1-x=p2-x; p1-y=p2-y; } } void ahead() { p1=head_f; p2=p1-next; p2=p2-next; if(p1-x==p2-x) { if(p1-yp2-y) head_f-y+=5; else head_f-y-=5; } else { if(p1-xp2-x) { head_f-x+=5; } else head_f-x-=5; } } void upon() { p1=head_f-next; p1=p1-next; head_f-y-=5; if(p1-x==head_f-xp1-y==head_f-y) { head_f-y+=5; ahead(); } } void down() { p1=head_f-next; p1=p1-next; head_f-y+=5; if(p1-x==head_f-xp1-y==head_f-y) { head_f-y-=5; ahead(); } } void left() { p1=head_f-next; p1=p1-next; head_f-x-=5; if(p1-x==head_f-xp1-y==head_f-y) { head_f-x+=5; ahead(); } } void right() { p1=head_f-next; p1=p1-next; head_f-x+=5; if(p1-x==head_f-xp1-y==head_f-y) { head_f-x-=5; ahead(); } } void food_f() { if(!food.judge) { food.x=(rand()%117+1)*5; food.y=(rand()%117+1)*5; food.judge=1; if(food.x30||food.y30||food.x570||food.y570) { setcolor(RED); circle(f
贪吃蛇c语言代码
#includestdio.h
#includestdlib.h
#includeWindows.h
#includeconio.h
#includetime.h
char gamemap[20][40];//游戏地图大小 20*40
int score=0;//当前分数
//记录蛇的结点
int x[800];//每个结点的行编号
int y[800];//每个结点的列编号
int len = 0;//蛇的长度
//记录水果信息
int fx=0;//食物的横坐标
int fy=0;//食物的纵坐标
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;ilen;i++)
{
for(j=0;jlen;j++)
{
if(x[i]==fxy[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(fcountfx==ify==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;ilen;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(fcountx[0]==fxy[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);
}
else
continue;
if(kbhit())//判断是否按下按键
{
s=getch();
}
}
}
C语言 的 贪吃蛇 代码 谢谢 大家啦。。。。。。。
你好,很荣幸回答你的问题,我这里是一个c的贪吃蛇源代码,希望对你有帮助,不过运行这个时需要你的软件包含惊蛰EasyX图形函数,比如vc++6.0,如遇到问题问题可以联系我,希望对你有帮助。
#include graphics.h
#include stdlib.h
#include conio.h
#include time.h
#include stdio.h
#define LEFT 'a'
#define RIGHT 'd'
#define DOWN 's'
#define UP 'w'
#define ESC 27
#define N 200 /*蛇的最大长度*/
int i;
char key;
int score=0; /*得分*/
int gamespeed=100; /*游戏速度自己调整*/
struct Food
{
int x; /*食物的横坐标*/
int y; /*食物的纵坐标*/
int yes; /*判断是否要出现食物的变量*/
}food; /*食物的结构体*/
struct Snake
{
int x[N];
int y[N];
int node; /*蛇的节数*/
int direction; /*蛇移动方向*/
int life; /* 蛇的生命,0活着,1死亡*/
}snake;
void Init(void); /*图形驱动*/
void Close(void); /*图形结束*/
void DrawK(void); /*开始画面*/
void GameOver(void); /*结束游戏*/
void GamePlay(void); /*玩游戏具体过程*/
void PrScore(void); /*输出成绩*/
/*主函数*/
void main(void)
{
Init(); /*图形驱动*/
DrawK(); /*开始画面*/
GamePlay(); /*玩游戏具体过程*/
Close(); /*图形结束*/
}
/*图形驱动*/
void Init(void)
{
int gd=9,gm=2;
initgraph(gd,gm," ");
cleardevice();
}
/*开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/
void DrawK(void)
{
/*setbkcolor(LIGHTGREEN);*/
setcolor(LIGHTCYAN);
setlinestyle(PS_SOLID,0,1); /*设置线型*/
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)
{
srand(time(NULL)); /*随机数发生器*/
food.yes=1; /*1表示需要出现新食物,0表*/
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) /*可以重复玩游戏,压ESC键*/
{
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;i0;i--) /*蛇的每个环节往前移动,也法/
{
snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1];
}
/*1,2,3,4表示右,左,上,下四个方向,通过这个判断来移动蛇头*/
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;isnake.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.xsnake.y[0]==food.y)/*吃到食物以后*/
{
setcolor(BLACK); /*把画面上的食物东西去*/
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(RED); /*画出蛇*/
for(i=0;isnake.node;i++)
rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);
Sleep(gamespeed);
setcolor(BLACK); /*用黑色去除蛇的的最后*/
rectangle(snake.x[snake.node-1],snake.y[snake.node-1],
snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);
} /*endwhile(!kbhit)*/
if(snake.life==1) /*如果蛇死就跳出循环*/
break;
key=getch(); /*接收按键*/
if (key == ESC) break; /*按ESC键退出*/
switch(key)
{
case UP:
if(snake.direction!=4) /*判断是否往相反的方向移动*/
snake.direction=3;
break;
case RIGHT:
if(snake.direction!=2)
snake.direction=1;
break;
case LEFT:
if(snake.direction!=1)
snake.direction=2;
break;
case DOWN:
if(snake.direction!=3)
snake.direction=4;
break;
}
}/*endwhile(1)*/
}
/*游戏结束*/
void GameOver(void)
{
cleardevice();
PrScore();
setcolor(RED);
setfont(56,0,"黑体");
outtextxy(200,200,"GAME OVER");
getch();
}
/*输出成绩*/
void PrScore(void)
{
char str[10];
setfillstyle(YELLOW);
bar(50,15,220,35);
setcolor(BROWN);
setfont(16,0,"宋体");
sprintf(str,"score:%d",score);
outtextxy(55,16,str);
}
/*图形结束*/
void Close(void)
{
closegraph();
}