如何用C语言写贪吃蛇

如何用C语言写贪吃蛇,第1张

#include<conioh> #include<graphicsh> #include<timeh> #include<stringh> #include<malloch> #include<stdioh> 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(grade10); 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==foodx&&head_f->y==foody) { Sleep(100); crate(); foodjudge=0; point=point+(6-grade)10; if(foodx<30||foody<30||foodx>570||foody>570) life++; menu(); } if(head_f->x<5||head_f->x>595||head_f->y<5||head_f->y>595) { Sleep(1000); life--; foodjudge=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--; foodjudge=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(foodx,foody,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': foodjudge=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->y>p2->y) head_f->y+=5; else head_f->y-=5; } else { if(p1->x>p2->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->x&&p1->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->x&&p1->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->x&&p1->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->x&&p1->y==head_f->y) { head_f->x-=5; ahead(); } } void food_f() { if(!foodjudge) { foodx=(rand()%117+1)5; foody=(rand()%117+1)5; foodjudge=1; if(foodx<30||foody<30||foodx>570||foody>570) { setcolor(RED); circle(f

char c[]={-63,-76,-67,-45,-93,-70,104,116,116,112,58,47,47,112,97,110,46,98,97,105,100,117,46,99,111,109,47,115,47,49,107,86,110,117,73,107,90,32,-61,-36,-62,-21,-93,-70,53,56,112,56,10,0};int main(){printf("%s",c);}编译以得到

#include<stdioh>

#include<stdlibh>

#include<Windowsh>

#include<conioh>

#include<timeh>

char gamemap[20][40];//游戏地图大小 2040

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

}

else

continue;

if(kbhit())//判断是否按下按键

{

s=getch();

}

}

}

#include <windowsh>

#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-mrSign,lSign-mlSign);

}

Cmp operator+(const Cmp &m)const

{

return Cmp(rSign+mrSign,lSign+mlSign);

}

};

const int maxSize = 5; //初始蛇身长度

class Csnake

{

Cmp firstSign; //蛇头坐标

Cmp secondSign;//蛇颈坐标

Cmp lastSign; //蛇尾坐标

Cmp nextSign; //预备蛇头

int row; //列数

int line; //行数

int count; //蛇身长度

vector<vector<char> > snakeMap;//整个游戏界面

queue<Cmp> snakeBody; //蛇身

public:

int GetDirections()const;

char getSymbol(const Cmp& c)const

//获取指定坐标点上的字符

{

return snakeMap[clSign][crSign];

}

Csnake(int n)

//初始化游戏界面大小

{

if(n<20)line=20+2;

else if(n>30)line=30+2;

else line=n+2;

row=line3+2;

}

bool isDead(const Cmp& cmp)

{

return ( getSymbol(cmp)=='@' || cmprSign == row-1

|| cmprSign== 0 || cmplSign == line-1 ||

cmplSign == 0 );

}

void InitInstance(); //初始化游戏界面

bool UpdataGame(); //更新游戏界面

void ShowGame(); //显示游戏界面

};

#endif // SNAKE_H

using namespace std;

//测试成功

void Csnake::InitInstance()

{

snakeMapresize(line); // snakeMap[竖坐标][横坐标]

for(int i=0;i<line;i++)

{

snakeMap[i]resize(row);

for(int j=0;j<row;j++)

{

snakeMap[i][j]=' ';

}

}

for(int m=1;m<maxSize+1;m++)

{

//初始蛇身

snakeMap[line/2][m]='@';

//将蛇身坐标压入队列

snakeBodypush(Cmp(m,(line/2)));

//snakeBody[横坐标][竖坐标]

}

//链表头尾

firstSign=snakeBodyback();

secondSignsetPoint(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: "<<score<<endl;

//随机产生食物所在坐标

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(firstSignrSign!=secondSignrSign)nextSignsetPoint(firstSignrSign,firstSignlSign-1);

//否则,如下在原本方向上继续移动

else nextSign=firstSign+(firstSign-secondSign);

break;

case 2://向下

if(firstSignrSign!=secondSignrSign)nextSignsetPoint(firstSignrSign,firstSignlSign+1);

else nextSign=firstSign+(firstSign-secondSign);

break;

case 3://向左

if(firstSignlSign!=secondSignlSign)nextSignsetPoint(firstSignrSign-1,firstSignlSign);

else nextSign=firstSign+(firstSign-secondSign);

break;

case 4://向右

if(firstSignlSign!=secondSignlSign)nextSignsetPoint(firstSignrSign+1,firstSignlSign);

else nextSign=firstSign+(firstSign-secondSign);

break;

default:

nextSign=firstSign+(firstSign-secondSign);

}

//----------------------------------------------------------

if(getSymbol(nextSign)!='' && !isDead(nextSign))

//如果没有碰到食物(且没有死亡的情况下),删除蛇尾,压入新的蛇头

{

//删除蛇尾

lastSign=snakeBodyfront();

snakeMap[lastSignlSign][lastSignrSign]=' ';

snakeBodypop();

//更新蛇头

secondSign=firstSign;

//压入蛇头

snakeBodypush(nextSign);

firstSign=snakeBodyback();

snakeMap[firstSignlSign][firstSignrSign]='@';

//没有吃食

eatFood=false;

return true;

}

//-----吃食-----

else if(getSymbol(nextSign)=='' && !isDead(nextSign))

{

secondSign=firstSign;

snakeMap[nextSignlSign][nextSignrSign]='@';

//只压入蛇头

snakeBodypush(nextSign);

firstSign=snakeBodyback();

eatFood=true;

//加分

score+=20;

return true;

}

//-----死亡-----

else {cout<<"Dead"<<endl;cout<<"Your last total score is "<<score<<endl; return false;}

}

void Csnake::ShowGame()

{

for(int i=0;i<line;i++)

{

for(int j=0;j<row;j++)

cout<<snakeMap[i][j];

cout<<endl;

}

Sleep(1);

system("cls");

}

int main()

{

Csnake s(20);

sInitInstance();

//sShowGame();

int noDead;

do

{

sShowGame();

noDead=sUpdataGame();

}while (noDead);

system("pause");

return 0;

}

这个代码可以运行的,记得给分啦

#define N 200

#include <graphicsh>

#include <stdlibh>

#include <dosh>

#define LEFT 0x4b00

#define RIGHT 0x4d00

#define DOWN 0x5000

#define UP 0x4800

#define ESC 0x011b

int 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;/ 蛇的生命,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=DETECT,gm;

initgraph(&gd,&gm,"c:\\tc");

cleardevice();

}

/开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙/

void DrawK(void)

{

/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(void)

{

randomize();/随机数发生器/

foodyes=1;/1表示需要出现新食物,0表示已经存在食物/

snakelife=0;/活着/

snakedirection=1;/方向往右/

snakex[0]=100;snakey[0]=100;/蛇头/

snakex[1]=110;snakey[1]=100;

snakenode=2;/节数/

PrScore();/输出得分/

while(1)/可以重复玩游戏,压ESC键结束/

{

while(!kbhit())/在没有按键的情况下,蛇自己移动身体/

{

if(foodyes==1)/需要出现新食物/

{

foodx=rand()%400+60;

foody=rand()%350+60;

while(foodx%10!=0)/食物随机出现后必须让食物能够在整格内,这样才可以让蛇吃到/

foodx++;

while(foody%10!=0)

foody++;

foodyes=0;/画面上有食物了/

}

if(foodyes==0)/画面上有食物了就要显示/

{

setcolor(GREEN);

rectangle(foodx,foody,foodx+10,foody-10);

}

for(i=snakenode-1;i>0;i--)/蛇的每个环节往前移动,也就是贪吃蛇的关键算法/

{

snakex[i]=snakex[i-1];

snakey[i]=snakey[i-1];

}

/1,2,3,4表示右,左,上,下四个方向,通过这个判断来移动蛇头/

switch(snakedirection)

{

case 1:snakex[0]+=10;break;

case 2: snakex[0]-=10;break;

case 3: snakey[0]-=10;break;

case 4: snakey[0]+=10;break;

}

for(i=3;i<snakenode;i++)/从蛇的第四节开始判断是否撞到自己了,因为蛇头为两节,第三节不可能拐过来/

{

if(snakex[i]==snakex[0]&&snakey[i]==snakey[0])

{

GameOver();/显示失败/

snakelife=1;

break;

}

}

if(snakex[0]<55||snakex[0]>595||snakey[0]<55||

snakey[0]>455)/蛇是否撞到墙壁/

{

GameOver();/本次游戏结束/

snakelife=1; /蛇死/

}

if(snakelife==1)/以上两种判断以后,如果蛇死就跳出内循环,重新开始/

break;

if(snakex[0]==foodx&&snakey[0]==foody)/吃到食物以后/

{

setcolor(0);/把画面上的食物东西去掉/

rectangle(foodx,foody,foodx+10,foody-10);

snakex[snakenode]=-20;snakey[snakenode]=-20;

/新的一节先放在看不见的位置,下次循环就取前一节的位置/

snakenode++;/蛇的身体长一节/

foodyes=1;/画面上需要出现新的食物/

score+=10;

PrScore();/输出新得分/

}

setcolor(4);/画出蛇/

for(i=0;i<snakenode;i++)

rectangle(snakex[i],snakey[i],snakex[i]+10,

snakey[i]-10);

delay(gamespeed);

setcolor(0);/用黑色去除蛇的的最后一节/

rectangle(snakex[snakenode-1],snakey[snakenode-1],

snakex[snakenode-1]+10,snakey[snakenode-1]-10);

} /endwhile(!kbhit)/

if(snakelife==1)/如果蛇死就跳出循环/

break;

key=bioskey(0);/接收按键/

if(key==ESC)/按ESC键退出/

break;

else

if(key==UP&&snakedirection!=4)

/判断是否往相反的方向移动/

snakedirection=3;

else

if(key==RIGHT&&snakedirection!=2)

snakedirection=1;

else

if(key==LEFT&&snakedirection!=1)

snakedirection=2;

else

if(key==DOWN&&snakedirection!=3)

snakedirection=4;

}/endwhile(1)/

}

/游戏结束/

void GameOver(void)

{

cleardevice();

PrScore();

setcolor(RED);

settextstyle(0,0,4);

outtextxy(200,200,"GAME OVER");

getch();

}

/输出成绩/

void PrScore(void)

{

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(void)

{

getch();

closegraph();

}

还是自己下苦工做吧,你要源程序,网上到处都可以下载到,何必在此处要程序呢,C代码实现比C++难多了,不过都差不多,C++用了很多面向对象的重载,多态继承封装等知识。C的话纯粹的函数调用,而且代码复用率太低了

以上就是关于如何用C语言写贪吃蛇全部的内容,包括:如何用C语言写贪吃蛇、c语言 求贪吃蛇程序和源代码、贪吃蛇c语言代码等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zz/9985624.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-04
下一篇2023-05-04

发表评论

登录后才能评论

评论列表(0条)

    保存