正文

贪食蛇2005-02-09 20:29:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/book/197.html

分享到:

/* 贪食蛇,TC2.0  by kingwei */

#include <graphics.h>
#include <time.h>
#include <stdlib.h>

#define MAX 100
#define APPLEMAX 10
#define APPLEIN  2
#define INCREASE 5
#define L 10
#define SPEED 2000

int snake[MAX][2]={0},rear=0,front=0;
int d[4][2]={{0,-L},{0,L},{-L,0},{L,0}},dn;
int applex,appley,applenum;

void insert()
{
   snake[rear][0]=snake[(rear-1)<0?MAX-1:rear-1][0]+d[dn][0];
   snake[rear][1]=snake[(rear-1)<0?MAX-1:rear-1][1]+d[dn][1];
   bar(snake[rear][0],snake[rear][1],
       snake[rear][0]+L,snake[rear][1]+L);
   rear=(rear+1)%MAX;
}
void delete()
{
   setfillstyle(0,0);
   bar(snake[front][0],snake[front][1],
       snake[front][0]+L,snake[front][1]+L);
   setfillstyle(1,15);
   front=(front+1)%MAX;
}
int inmap(int x,int y)
{
   if(x<0||x>640-L||y<0||y>480-L) return 0;
   else return 1;
}
int untouchsnake(int x,int y)
{
   int i;
   for(i=front;i!=rear;i=(i+1)%MAX)
      if(x==snake[i][0]&&y==snake[i][1])   return 0;
   return 1;
}
void makeapple()
{
   int x,y;
   randomize();
   do{
      x=random(620/L)+1;
      y=random(460/L)+1;
      if(untouchsnake(x*L,y*L))
      {
     circle(x*L+L/2,y*L+L/2,L/2-1);
     applex=x*L;appley=y*L;break;
      }
   }while(1);
}
int touchapple(int x,int y)
{
    if(x==applex&&y==appley)  return 1;
    else return 0;
}
void movesnake()
{
  int count,flagate;
  for(applenum=0,count=0,flagate=0;;)
   {
      if(bioskey(1))
     switch(bioskey(0))
     {
     case 18432:if(dn==1) break;dn=0;break;
     case 20480:if(dn==0) break;dn=1;break;
     case 19200:if(dn==3) break;dn=2;break;
     case 19712:if(dn==2) break;dn=3;break;
     case 283:return;
     }
      if(flagate&&applenum!=0&&applenum%APPLEIN==0)
      {
     count=INCREASE;flagate=0;
      }
      if(!count)  delete();
      if(inmap(snake[(rear-1)<0?MAX-1:rear-1][0]+d[dn][0],
           snake[(rear-1)<0?MAX-1:rear-1][1]+d[dn][1])&&
     untouchsnake(snake[(rear-1)<0?MAX-1:rear-1][0]+d[dn][0],
              snake[(rear-1)<0?MAX-1:rear-1][1]+d[dn][1]))
      {
     insert();
     if(count>0)  count--;
     if(touchapple(snake[(rear-1)<0?MAX-1:rear-1][0],
               snake[(rear-1)<0?MAX-1:rear-1][1]))
     {
        applenum++;flagate=1;
        if(applenum==APPLEMAX)  break;
        else makeapple();
     }
     delay(SPEED);
      }
      else {printf("Fail!");return;}
   }
   printf("Congratulation!");
}
void makesnake()
{
   int n,i;
   dn=3;n=10;
   cleardevice();
   for(i=0;i<n;i++)
   {
      insert();
      delay(SPEED);
   }
}
int main()
{
   int gdriver, gmode;
   detectgraph(&gdriver,&gmode);
   initgraph(&gdriver, &gmode, "e:\\tc\\bgi");
   makesnake();
   makeapple();
   movesnake();
   getch();
   closegraph();
}

阅读(3216) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论

发表评论

评论内容:(字数请控制在500字以内)