贪吃蛇(C语言),“程序已停止工作”的问题

贪吃蛇(C语言),“程序已停止工作”的问题,第1张

你好,我是一名高中生,你所说的贪吃蛇程序我也写了一个,不知道能否对你有帮助。

不过因为指针和结构体我还没学到,所以只用了数组和循环。

#define S 100

#define M 23

#define MM 80

#include<stdioh>

#include<windowsh>

#include<conioh>

#include<timeh>

int a[MMM]={5,5,5,5};

int b[MMM]={5,6,7,8};

int l=4,x,y,n=0;

void gotoxy(int y , int x)

{

 COORD pos = {x,y};

 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);

 SetConsoleCursorPosition(hOut, pos);

}

void move(char ch)

{

 int i,j;

 for(i=0;i<l-1;i++)

 {

  a[i]=a[i+1];

  b[i]=b[i+1];

 }

 if(ch=='w'||ch=='W')

  a[l-1]--;

  if(ch=='s'||ch=='S')

  a[l-1]++;

  if(ch=='a'||ch=='A')

  b[l-1]--;

  if(ch=='d'||ch=='D')

  b[l-1]++;

 if(out())

 {

  for(j=1;j<l-1;j++)

  {

  gotoxy(a[j],b[j]);

  printf("");

  }

  gotoxy(a[j],b[j]);

  putchar('#');

  gotoxy(a[0],b[0]);

  putchar(' '); 

  Sleep(S);

 }

 else

 {

  gotoxy(M/2,MM/2-12);

  printf("You Lose! Score:%d",n);

  getch(); 

  exit(0); 

 } 

}

int out(void)

{

 int i;

 if(a[l-1]>=M-1||b[l-1]>=MM-1||a[l-1]<=0||b[l-1]<=0)

  return 0;

 for(i=0;i<l-1;i++)

  if(a[i]==a[l-1]&&b[i]==b[l-1])

   return 0;

 return 1;

void sweet(void)

 int f=1,i;

 while(f--)

 {

  x=rand()%M;

  y=rand()%MM;

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

   if(x==a[i]&&y==b[i]||x==0||y==0||x==M-1||y==MM-1)

    f=1;

   else

   {

    gotoxy(x,y);

    putchar('&');

   }

 }

}

int eat(void)

{

 int i,j,k;

 if(a[l-1]==x&&b[l-1]==y)

 {

  l++;

  n++;

  gotoxy(M,MM/2-8);

  printf("Your Score:%d",n);

  a[l-1]=x;

  b[l-1]=y;

  for(i=l-2;i>0;i--)

  {

   a[i]=a[i-1];

   b[i]=b[i-1];

  }

  for(j=1;j<l-1;j++)

  {

  gotoxy(a[j],b[j]);

  printf("");

  }

  gotoxy(a[j],b[j]);

  putchar('#');

  sweet();

  return 1; 

 }

 return 0; 

}

void start(void)

{

 int i,j,k;

 gotoxy(M,MM/2-8);

 printf("Your Score:%d",n);

 gotoxy(M,0+5);

 printf("Ver V10");

 gotoxy(M,MM-20);

 printf("Made By Lxbs");

 sweet();

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

 {

  gotoxy(0,i);

  putchar('@');

  gotoxy(M-1,i);

  putchar('@');

 }

 for(j=0;j<M;j++)

 {

  gotoxy(j,0);

  putchar('@');

  gotoxy(j,MM-1);

  putchar('@');

 }

}

int main(void)

{

 srand((unsigned)time(NULL));

 char ch='d';

 start();

 for(;;)

 { 

  if(kbhit())

   ch=getch();

  switch(ch)

  {

   case 'W':

   case 'w':

   case 'S':

   case 's':

   case 'A':

   case 'a':

   case 'D':

   case 'd':if(!eat())move(ch);break;

   default:break;

  }

 } 

}

字符版

#include<graphicsh>

#include<windowsh>

#include<timeh>

void move(char ch);

int a[100]={60,80,100,120};

int b[100]={60,60,60,60};

int c[100]={75,95,115,135};

int d[100]={75,75,75,75};

int l=4;

int aa,bb,cc,dd;

char str[4]={'0','0','0','0'};

int s=0;

int out(void)

{

 int i;

 if(a[l-1]>=335||b[l-1]>=335||a[l-1]<=0||b[l-1]<=0)

  return 0;

 for(i=0;i<l-1;i++)

  if(a[i]==a[l-1]&&b[i]==b[l-1]&&c[i]==c[l-1]&&d[i]==d[l-1])

   return 0;

 return 1;

void sweet(void)

 int f=1,i;

 while(f--)

 {

  bb=rand()%200+20;

  aa=rand()%200+20;

  for(;bb%20!=0;)

   bb++;

  for(;aa%20!=0;)

   aa++;

  cc=aa+15;

  dd=bb+15;

  setcolor(GREEN);

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

   if(aa==a[i]&&bb==b[i]&&cc==c[i]&&dd==d[i])

    f=1;

   else

   rectangle(aa,bb,cc,dd);

 }

}

int eat(void)

 int i,j=3,k;

 if(a[l-1]==aa&&b[l-1]==bb&&c[l-1]==cc&&d[l-1]==dd)

 {

  l++;

  s++;

  k=s;

  while(k)

  {

  str[j]=k%10+48;

  k/=10;

  j--;

  }

  outtextxy(380,235,str);

  a[l-1]=aa;

  b[l-1]=bb;

  c[l-1]=cc;

  d[l-1]=dd;

  for(i=l-2;i>0;i--)

  {

   a[i]=a[i-1];

   b[i]=b[i-1];

   c[i]=c[i-1];

   d[i]=d[i-1];

  }

  setcolor(YELLOW);

  for(i=1;i<l-1;i++)

  rectangle(a[i],b[i],c[i],d[i]);

  setcolor(RED);

  rectangle(a[i],b[i],c[i],d[i]);

  sweet();

  return 1; 

 }

 return 0; 

}

void start()

{

 int M=475,N=355,S=20,T=15,lx=0,rx=15,ly=0,ry=15;

 int i,j;

 char ch[3][8][15]=

 {

  {"游戏说明","  版本:Ver20","    A 左移","    D 右移","    W 上移","    S 下移"},

  {"当前分数"},

  {"游戏作者","    流星不死"}

 };

 initgraph(M, N);

 setcolor(WHITE);

 setbkcolor(BLACK);

 for(i=0;i<=N;i+=S)

  rectangle(lx,i,rx,T+i);

 lx=M-15;

 rx=M;

 for(i=0;i<=N;i+=S)

  rectangle(lx,i,rx,T+i);

 for(j=0;j<=M;j+=S)

  rectangle(j,ly,T+j,ry);

 ly=N-15;

 ry=N;

 for(j=0;j<=M;j+=S)

  rectangle(j,ly,T+j,ry);

 lx=M-135;

 rx=M-120;

 for(i=0;i<=N;i+=S)

  rectangle(lx,i,rx,T+i);

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

  rectangle(lx+iS,180,rx+i20,195);

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

  rectangle(lx+iS,260,rx+i20,275);

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

  outtextxy(360,30+i25,ch[0][i]);

  outtextxy(360,210,ch[1][0]);

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

  outtextxy(360,290+i25,ch[2][i]);

 outtextxy(380,235,str);

 sweet();

}

void gotoxy(int y , int x)

{

 COORD pos = {x,y};

 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);

 SetConsoleCursorPosition(hOut, pos);

}

void main()

{

 srand((unsigned)time(NULL));

 int i;

 char ch='d';

 start();

 setcolor(WHITE);

 for(i=1;i<4;i++)

  rectangle(a[i],b[i],c[i],d[i]);

 for(;;)

 { 

  if(kbhit())

   ch=getch();

  switch(ch)

  {

   case 'W':

   case 'w':

   case 'S':

   case 's':

   case 'A':

   case 'a':

   case 'D':

   case 'd':if(!eat())move(ch);break;

   default:break;

  }

 }

}

void move(char ch)

{

 int i,j;

 for(i=0;i<l-1;i++)

  {

   a[i]=a[i+1];

   b[i]=b[i+1];

   c[i]=c[i+1];

   d[i]=d[i+1];

  }

 if(ch=='w'||ch=='W')

  {b[l-1]-=20;d[l-1]-=20;}

  if(ch=='s'||ch=='S')

  {b[l-1]+=20;d[l-1]+=20;}

  if(ch=='a'||ch=='A')

  {a[l-1]-=20;c[l-1]-=20;}

  if(ch=='d'||ch=='D')

  {a[l-1]+=20;c[l-1]+=20;}

 if(out())

  {

   setcolor(RED);

   rectangle(a[i],b[i],c[i],d[i]);

   for(j=1;j<l-1;j++)

   {

   setcolor(YELLOW);

   rectangle(a[j],b[j],c[j],d[j]);

   }

   setcolor(BLACK);

   rectangle(a[0],b[0],c[0],d[0]);

   setcolor(WHITE);

   Sleep(100);

  }

 else

 {

  

  outtextxy(180,180,"你输了!");

  outtextxy(380,235,str);

  getch(); 

  closegraph();

 } 

}

ege图形库版本

C语言贪吃蛇源代码必须经过相应的C/C++编译器编译成EXE文件后才能运行。

由于我们通常使用的 *** 作系统是Windows系统,而在该系统下最长用的C/C++编译器是VC++编译器,目前在大专院校常用的版本还是VC++60

下面就以VC++60来说明编译过程:

1在VC++60中通过“File”菜单下的 “Open”子菜单打开贪吃蛇代码

2在VC++60中通过“Build”菜单下的 “Compile xxxxxx”子菜单编译贪吃蛇代码

3在VC++60中通过“Build”菜单下的 “Execute xxxxexe”子菜单运行贪吃蛇程序

附:在VC++6环境下可运行的C/C++贪吃蛇源代码(无版权,自己编写,欢迎任意修改拷贝)

/

C/C++贪吃蛇游戏,zjlj,2015316

/

#define DEBUG 0 //当程序在调试阶段时 DEBUG为 1

#include<iostream>

#include<windowsh>

#include<timeh>

#include<conioh>

using namespace std;

void readini(FILE fphead, int score, char argv[]) //创建或打开一个和运行文件对应的ini文件,读取最高纪录

{

 char filename[200],pfilename;

 int flag=-1,i;

    

    strcpy(filename,argv[0]);

    for(i=0;filename[i]!='\0';i++)

 {

  if (''==filename[i])flag=1;

 }

 

 if(1==flag)

 {

 filename[i-1]='i';

    filename[i-2]='n';

 filename[i-3]='i';

 }

 else

 {

  filename[i]='';

 filename[i+1]='i';

 filename[i+2]='n';

    filename[i+3]='i';

    filename[i+4]='\0';

 }

 for(;filename[i]!='\\'&&i>=0;i--)pfilename=&filename[i];

    if ( (fphead=fopen(pfilename, "rb+"))==NULL)

 {

        if ( (fphead=fopen(pfilename, "wb+"))==NULL)

  {

    printf("无法创建或打开\"%s\"文件\n",pfilename);

    system("pause");

       exit(0);

  }

    }

 else

 {

  fread(score,sizeof(int),1,fphead);

 }

}

void writeini(FILE fphead, int score, char argv[])  //打开一个和运行文件对应的ini文件,写入最高纪录

{

 char filename[200],pfilename;

 int flag=-1,i;

   

    strcpy(filename,argv[0]);

    for(i=0;filename[i]!='\0';i++)

 {

  if (''==filename[i])flag=1;

 }

 

 if(1==flag)

 {

 filename[i-1]='i';

    filename[i-2]='n';

 filename[i-3]='i';

 }

 else

 {

  filename[i]='';

 filename[i+1]='i';

 filename[i+2]='n';

    filename[i+3]='i';

    filename[i+4]='\0';

 }

 for(;filename[i]!='\\'&&i>=0;i--)pfilename=&filename[i];

    if ( (fphead=fopen(pfilename, "wb+"))==NULL)

 {

          printf("无法写入\"%s\"文件,磁盘写保护!\n",pfilename);

    system("pause");

       exit(0);

 }

 else

 {

  rewind(fphead);

  fwrite(score,sizeof(int),1,fphead);

  fclose(fphead);

 }

}

void gotoxy(int x,int y)//光标定位,光标定位函数SetConsoleCursorPosition是左上角位置是0,0然后向左向下延伸

{

COORD pos;

posX=2y;

posY=x;

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);

}

void color(int a)//颜色函数

{

SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);

}

void Refresh(int q[][22], int grade, int gamespeed, int length,int score) //  输出贪吃蛇棋盘

{

 int i,j;

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

 {

  for(j=0;j<22;j++)

  {

   if(q[i][j]==0)//输出棋盘空白

   {

    gotoxy(i,j);

    color(11);

    cout<<"■";

   }

   if(q[i][j]==1||q[i][j]==2)//输出棋盘墙壁

   {  

    gotoxy(i,j);

    color(11);

    cout<<"□";

   }

   if(q[i][j]==3)//输出蛇头

   {  

    gotoxy(i,j);

    color(14);

    cout<<"★";

   }

   if(q[i][j]==4)//输出蛇身

   {  

    gotoxy(i,j);

    color(12);

    cout<<"◆";

   }

     if(q[i][j]==5)//输出果子

   {  

    gotoxy(i,j);

    color(12);

    cout<<"●";

   }

  }

  if(i==0) cout << "\t";

  if(i==1) cout << "\t等级为:" << grade;//显示等级

  if(i==3) cout << "\t自动前进时间";

  if(i==4) cout << "\t间隔为:" << gamespeed << "ms";//显示时间

     if(i==6) cout << "\t历史最高分为:" << score << "分";

  if(i==7) cout << "\t你现在得分为:" << (length+(grade-1)8)10 << "分";

  if(i==8) cout << "\t";

     if(i==9) cout << "\t游戏说明:";

     if(i==10) cout << "\t(1)用小键盘方向键控制";

  if(i==11) cout << "\t蛇头运动方向;";

  if(i==12) cout << "\t(2)蛇每吃一个果子蛇身";

  if(i==13) cout << "\t增加一节;";

  if(i==14) cout << "\t(3)蛇咬到自己或碰到墙";

  if(i==15) cout << "\t壁游戏结束。";

  if(i==18) cout << "\t";

     if(i==19) cout << "\tC/C++语言作业:";

     if(i==20) cout << "\tzjlj,20150316 ";

 }

}

 

int main(int argc, char argv[]){

    int tcsQipan[22][22];     //  贪吃蛇棋盘是一个二维数组(如2222,包括墙壁)

    int i,j,score,directiontemp;

 FILE  fpini;//fpini 信息文件

 readini(&fpini, &score, argv);//读取ini文件的最高纪录

 if (score<0)//最高成绩小于零设置为零,初建文件会是负数

  score=0;

 while(1)

 {

  for(i=1;i<=20;i++)

   for(j=1;j<=20;j++)

    tcsQipan[i][j]=0;    //贪吃蛇棋盘相应坐标标上中间空白部分的标志0

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

   tcsQipan[0][i] = tcsQipan[21][i] = 1;      //贪吃蛇棋盘相应坐标标上上下墙壁的标志1

  for(i=1;i<=20;i++)

   tcsQipan[i][0] = tcsQipan[i][21] = 2;      //贪吃蛇棋盘相应坐标标上左右墙壁的标志2

  int tcsZuobiao[2][500];     //蛇的坐标数组

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

  {

   tcsZuobiao[0][i] = 1;//蛇身和蛇头的x坐标

   tcsZuobiao[1][i] = i + 1;//蛇身和蛇头的y坐标

  }

  int head = 3,tail = 0;//标示蛇头和蛇尾的数组偏移量

  for(i=1;i<=3;i++)

   tcsQipan[1][i]=4;    //蛇身

  tcsQipan[1][4]=3;       //蛇头

  int x1, y1;           // 随机出果子

  srand(time(0));//设置随机种子

  do

  {

   x1=rand()%20+1;

   y1=rand()%20+1;

  }

  while(tcsQipan[x1][y1]!=0);//如果不是在空白处重新出果子

  tcsQipan[x1][y1]=5;//贪吃蛇棋盘相应坐标标上果子的标志5

  color(12);

  cout<<"\n\n\t\t\t\t贪吃蛇游戏即将开始 !"<<endl;//准备开始

  long start,starttemp;

  int grade = 1, length = 4;  //设置初始等级和蛇的初始长度

  int gamespeed = 500;  //设置初始前进时间间隔

  for(i=3;i>=0;i--)

  {

   start=clock();

   while(clock()-start<=1000);

   system("cls");

   if(i>0)

    cout << "\n\n\t\t\t\t进入倒计时:" << i << endl;  //倒计时显示

   else

    Refresh(tcsQipan,grade,gamespeed,length,score);  //初始棋盘显示

  }

  int timeover=1,otherkey=1;//初始化超时时间和按键判断参数

  char direction = 77;  // 设置初始情况下,向右运动

  int x=tcsZuobiao[0][head],y=tcsZuobiao[1][head];//保存蛇头坐标到x,y变量

  while(1)//运行一局游戏

  {

   start = clock();

   while((timeover=((starttemp=clock())-start<=gamespeed))&&!kbhit());//如果有键按下或时间超过自动前进时间间隔则终止循环

   if(direction==72||direction==80||direction==75 ||direction==77)

   directiontemp=direction;//保留上一次方向按键

            //starttemp=gamespeed+start-starttemp;//保留停留时间

   if(timeover)

   {

    #if (DEBUG==1)

    direction = getch();//调试代码

             #else

    if((direction =getch())==-32)

     direction = getch();

       #endif

   }

             #if (DEBUG==1)//调试代码

       start=clock();

    while(clock()-start<=2000);

    gotoxy(24,4);

    cout << "\t按键ASCII代码"<<(int)direction<<"    "<<endl;

             #endif

    if(!(direction==72||direction==80||direction==75 ||direction==77))

    {   

     otherkey=0;//  按键非方向键,otherkey设置为0

    }

    else

    {

     otherkey=1;//  按键为方向键,otherkey设置为1

    }

             if(direction==72 && directiontemp==80)//忽略反方向按键

    {

        direction=32;

     otherkey=0;

                 //start = clock();

        //while(clock()-start<=starttemp);

    }

    else if(direction==80 && directiontemp==72)

   {

        direction=32;//设置按键为非方向键

      otherkey=0;//  按键为非方向键,otherkey设置为0

                // start = clock();

       //while(clock()-start<=starttemp);//补偿等待时间

    }

    else if(direction==75 && directiontemp==77)

    {

        direction=32;

     otherkey=0;

                 //start = clock();

        //while(clock()-start<=starttemp);

    }

    else if(direction==77 && directiontemp==75)

    {

        direction=32;

     otherkey=0;

                 //start = clock();

        //while(clock()-start<=starttemp);

    }

    

    

    switch(direction)//判断方向键

    {

     case 72: x= tcsZuobiao[0][head]-1; y= tcsZuobiao[1][head];break;      // 向上

     case 80: x= tcsZuobiao[0][head]+1; y= tcsZuobiao[1][head];break;      // 向下

     case 75: x= tcsZuobiao[0][head]; y= tcsZuobiao[1][head]-1;break;      // 向左

     case 77: x= tcsZuobiao[0][head]; y= tcsZuobiao[1][head]+1;break;      // 向右

     default: break;

    }

   

 

    if(x==0 || x==21 ||y==0 || y==21)      // 蛇头碰到墙壁,结束本局游戏

    {  

     gotoxy(22,12);

     cout << "\t游戏已结束!" << endl;

     if(score>=(length+(grade-1)8)10)//判断是否破记录

     {

      gotoxy(10,7);

      color(12);

      cout << "闯关失败 加油耶!" << endl;

      fclose(fpini);//关闭ini文件

     }

     else

     {

      gotoxy(10,7);

      color(12);

      cout << "恭喜您打破记录" << endl;

      score=(length+(grade-1)8)10;

      writeini(&fpini, &score, argv);//写入ini文件的最高纪录

     }

     gotoxy(23,12);

        cout << "按回车键重新开始,按ESC退出游戏" << endl;//显示的提示

     break;//退出该局游戏

    }

    if(tcsQipan[x][y]!=0&&!(x==x1&&y==y1)&&tcsQipan[x][y]!=3) //   蛇头碰到蛇身,结束本局游戏

    {

     gotoxy(22,12);

     cout << "\t游戏已结束!" << endl;

     if(score>=(length+(grade-1)8)10)//判断是否破记录

     {

      gotoxy(10,7);

      color(12);

      cout << "闯关失败 加油耶!" << endl;

      fclose(fpini);//关闭ini文件

     }

     else

     {

      gotoxy(10,7);

      color(12);

      cout << "恭喜您打破记录" << endl;

      score=(length+(grade-1)8)10;

      writeini(&fpini, &score, argv);//写入ini文件的最高纪录

     }

     gotoxy(23,12);

     cout << "按回车键重新开始,按ESC退出游戏" << endl;//显示的提示

     break;//退出该局游戏

    }

    /

    游戏运行时的核心算法开始

    /

    if(x==x1 && y==y1) //  吃果子,长度加1

    {   

     length ++;

     if(length>=8)//长度大于等于8重新计算长度,等级加1

     {

      length -= 8;//重新计算长度

      grade ++;//等级加1

      if(gamespeed>50)//控制最快速度为50

       gamespeed = 550 - grade  50; // 改变自动前进时间间隔

     }

     tcsQipan[x][y]= 3;//贪吃蛇棋盘相应坐标现在蛇头标志改为蛇头标志3

     tcsQipan[tcsZuobiao[0][head]][tcsZuobiao[1][head]] = 4;//贪吃蛇棋盘相应坐标原来蛇头标志改为蛇身标志4

     head = (head+1)%400;//防止数组越界

     tcsZuobiao[0][head] = x;//蛇头的x坐标

     tcsZuobiao[1][head] = y;//蛇头的y坐标

     do//随机出果子

     {

      x1=rand()%20+1;

      y1=rand()%20+1;

     }

     while(tcsQipan[x1][y1]!=0);//如果不是在空白处重新出果子

     tcsQipan[x1][y1]=5;//贪吃蛇棋盘相应坐标标上果子的标志5

     gotoxy(22,12);

     cout << "\t游戏进行中!" << endl;

     Refresh(tcsQipan,grade,gamespeed,length,score);

    }

    else  //  不吃果子

    {  

     if(otherkey)

     {

      tcsQipan [tcsZuobiao[0][tail]][tcsZuobiao[1][tail]]=0;

      tail=(tail+1)%400;//防止数组越界

      tcsQipan [tcsZuobiao[0][head]][tcsZuobiao[1][head]]=4;

      head=(head+1)%400;//防止数组越界

      tcsZuobiao[0][head]=x;//蛇头的x坐标

      tcsZuobiao[1][head]=y;//蛇头的y坐标

      tcsQipan[tcsZuobiao[0][head]][tcsZuobiao[1][head]]=3;

      gotoxy(22,12);

      cout << "\t游戏进行中!" << endl;

      Refresh(tcsQipan,grade,gamespeed,length,score);

     }

     else

     {

      gotoxy(22,12);

      cout << "\t游戏暂停中!" << endl;

     }

    }

    /

    游戏运行时的核心算法结束

    /

       }

    while(1)

    {

     while(!kbhit());

     if((direction =getch())==13)//按回车键开始下一局

      break;

     if(direction ==27)//按ESC退出游戏

      exit(0);

    }

       system("cls");//清除屏幕重新开始

 }

 return 0;

}

import javaawtColor;  

import javaawtGraphics;  

import javaawtGraphics2D;  

import javaawtRectangle;  

import javaawteventKeyAdapter;  

import javaawteventKeyEvent;  

import javaawtimageBufferedImage;  

import javautilArrayList;  

import javautilList;  

import javaxswingJFrame;  

public class InterFace extends JFrame {  

/

 WIDTH:宽

 HEIGHT:高

 SLEEPTIME:可以看作蛇运动的速度

  L = 1,R = 2, U = 3, D = 4 左右上下代码

/

    public static final int WIDTH = 800, HEIGHT = 600, SLEEPTIME = 200, L = 1,R = 2, U = 3, D = 4;  

    BufferedImage offersetImage= new BufferedImage(WIDTH, HEIGHT,BufferedImageTYPE_3BYTE_BGR);;  

    Rectangle rect = new Rectangle(20, 40, 15  50, 15  35);  

    Snake snake;  

    Node node;  

    public InterFace() {  

     //创建"蛇"对象

        snake = new Snake(this);  

        //创建"食物"对象

        createNode();  

        thissetBounds(100, 100, WIDTH, HEIGHT);

        //添加键盘监听器

        thisaddKeyListener(new KeyAdapter() {  

            public void keyPressed(KeyEvent arg0) {  

                Systemoutprintln(arg0getKeyCode());  

                switch (arg0getKeyCode()) {  

                //映射上下左右4个键位

                case KeyEventVK_LEFT:  

                    snakedir = L;  

                    break;  

                case KeyEventVK_RIGHT:  

                    snakedir = R;  

                    break;  

                case KeyEventVK_UP:  

                    snakedir = U;  

                    break;  

                case KeyEventVK_DOWN:  

                    snakedir = D;  

                }  

            }  

        });  

        thissetTitle("贪吃蛇 01   By : Easy");  

        thissetDefaultCloseOperation(EXIT_ON_CLOSE);  

        thissetVisible(true);  

        //启动线程,开始执行

        new Thread(new ThreadUpadte())start();  

    }  

    public void paint(Graphics g) {  

        Graphics2D g2d = (Graphics2D) offersetImagegetGraphics();  

        g2dsetColor(Colorwhite);  

        g2dfillRect(0, 0, WIDTH, HEIGHT);  

        g2dsetColor(Colorblack);  

        g2ddrawRect(rectx, recty, rectwidth, rectheight);  

        //如果蛇碰撞(吃)到食物,则创建新食物

        if (snakehit(node)) {  

            createNode();  

        }  

        snakedraw(g2d);  

        nodedraw(g2d);  

        gdrawImage(offersetImage, 0, 0, null);  

    }  

    class ThreadUpadte implements Runnable {  

        public void run() {  

         //无限重绘画面

            while (true) {  

                try {  

                    Threadsleep(SLEEPTIME);  

                    repaint();  //

                } catch (InterruptedException e) {  

                    eprintStackTrace();  

                }  

            }  

        }  

    }  

    /

      创建食物

     /

    public void createNode() {  

     //随机食物的出现位置

        int x = (int) (Mathrandom()  650) + 50,y = (int) (Mathrandom()  500) + 50;  

        Color color = Colorblue;  

        node = new Node(x, y, color);  

    }  

    public static void main(String args[]) {  

        new InterFace();  

    }  

}  

/

  节点类(包括食物和蛇的身躯组成节点)

 /

class Node {  

    int x, y, width = 15, height = 15;  

    Color color;  

    public Node(int x, int y, Color color) {  

        this(x, y);  

        thiscolor = color;  

    }  

    public Node(int x, int y) {  

        thisx = x;  

        thisy = y;  

        thiscolor = colorblack;  

    }  

    public void draw(Graphics2D g2d) {  

        g2dsetColor(color);  

        g2ddrawRect(x, y, width, height);  

    }  

    public Rectangle getRect() {  

        return new Rectangle(x, y, width, height);  

    }  

}  

/

  蛇

 /

class Snake {  

    public List<Node> nodes = new ArrayList<Node>();  

    InterFace interFace;  

    int dir=InterFaceR;  

    public Snake(InterFace interFace) {  

        thisinterFace = interFace;  

        nodesadd(new Node(20 + 150, 40 + 150));  

        addNode();  

    }

    /

      是否碰撞到食物

      @return true 是 false 否

     /

    public boolean hit(Node node) {  

     //遍历整个蛇体是否与食物碰撞

        for (int i = 0; i < nodessize(); i++) {  

            if (nodesget(i)getRect()intersects(nodegetRect())) {  

                addNode();  

                return true;  

            }  

        }  

        return false;  

    }  

    public void draw(Graphics2D g2d) {  

        for (int i = 0; i < nodessize(); i++) {  

            nodesget(i)draw(g2d);  

        }  

        move();  

    }  

    public void move() {  

        nodesremove((nodessize() - 1));  

        addNode();  

    }  

    public synchronized void addNode() {  

        Node nodeTempNode = nodesget(0);  

        //如果方向

        switch (dir) {  

        case InterFaceL:

         //判断是否会撞墙

            if (nodeTempNodex <= 20) { 

                nodeTempNode = new Node(20 + 15  50, nodeTempNodey);  

            }  

            nodesadd(0, new Node(nodeTempNodex - nodeTempNodewidth,  

                    nodeTempNodey));  

            break;  

        case InterFaceR: 

         //判断是否会撞墙

            if (nodeTempNodex >= 20 + 15  50 - nodeTempNodewidth) {  

                nodeTempNode = new Node(20 - nodeTempNodewidth, nodeTempNodey);  

            }  

            nodesadd(0, new Node(nodeTempNodex + nodeTempNodewidth,  

                    nodeTempNodey));  

            break;  

        case InterFaceU:  

         //判断是否会撞墙

            if (nodeTempNodey <= 40) {  

                nodeTempNode = new Node(nodeTempNodex, 40 + 15  35);  

            }  

            nodesadd(0, new Node(nodeTempNodex, nodeTempNodey - nodeTempNodeheight));  

            break;  

        case InterFaceD:

         //判断是否会撞墙

            if (nodeTempNodey >= 40 + 15  35 - nodeTempNodeheight) {  

                nodeTempNode = new Node(nodeTempNodex,40 - nodeTempNodeheight);  

            }  

            nodesadd(0, new Node(nodeTempNodex, nodeTempNodey + nodeTempNodeheight));  

            break;  

        }  

    }

在内存中定义一个数组,存储当前局面(如果棋盘小(<15)可以选用unsigned

char类型,否则用int,蛇身就用1,2,3,4,5这样的数字序列表示,每走一格,根据当前方向将下一格数字变一下,把尾巴也处理一下,),每一秒刷新一下(向前走一格),每刷新一下,就重绘一遍当前局面(可以用prinrf函数,也可以用绘图函数),

总之方法很多很多,自己下来可以思索一下

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

}

}

}

以上就是关于贪吃蛇(C语言),“程序已停止工作”的问题全部的内容,包括:贪吃蛇(C语言),“程序已停止工作”的问题、c语言贪吃蛇源代码怎么用、c语言程序,谁帮我注释一下啊贪吃蛇游戏,高值悬赏!谢谢朋友们。。。。。等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

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

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

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

发表评论

登录后才能评论

评论列表(0条)

    保存