该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
srand(time(NULL));
while (1)
{
while (!kbhit()) //在没有按键的情况下,蛇自己移动身体
{
if (food.addFood == 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.addFood = 0; //画面上有食物
}
if (food.addFood == 0) //画面上有食物,则显示
{
setcolor(GREEN);
rectangle(food.x, food.y, food.x+10, food.y-10);
}
for (i=snake.joint-1; i>0; i--) //蛇的每个节往前移动
{
snake.x[i] = snake.x[i-1];
snake.y[i] = snake.y[i-1];
} //1,2,3,4 表示右,左,上,下四个方向,来决定蛇头的移动
switch(snake.direction)
{
case MV_RIGHT: snake.x[0] += 10; break;
case MV_LEFT: snake.x[0] -= 10; break;
case MV_UP: snake.y[0] -= 10; break;
case MV_DOWN: snake.y[0] += 10; break;
} //从蛇的第四节开始判断是否撞到自己,因为蛇头为两节,第三节不可能拐过来
for (i=3; i
{
if (snake.x[i]==snake.x[0] && snake.y[i]==snake.y[0])
{
GameOver(score); //显示失败
snake.life = 1; //蛇死*/
break;
}
} //判断蛇是否撞到墙壁
if (snake.x[0]<55 || snake.x[0]>595
|| snake.y[0]<55 || snake.y[0]>455)
{
GameOver(score); //本次游戏结束
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.joint] =-20; snake.y[snake.joint] =-20;
snake.joint++; //蛇的身体长一节
food.addFood = 1; //画面上需要出现新食物
score += 10;
PrScore(score); //输出新得分
} //画蛇
setcolor(RED);
for (i=0; i
{
rectangle(snake.x[i], snake.y[i],
snake.x[i]+10, snake.y[i]-10);
} Sleep(gamespeed); //延时控制蛇的速度 //去除蛇的最后一节
setcolor(0);
rectangle(snake.x[snake.joint-1], snake.y[snake.joint-1],
snake.x[snake.joint-1]+10,snake.y[snake.joint-1]-10);
} //end of while(!kbhit) if (snake.life == 1) break; //如果蛇死,则跳出循环
key=getch();//接收按键
switch(key)//判断按键,是否往相反方向移动,按Esc键则退出
{
case 'w':snake.direction = MV_UP;break;
case 'd':snake.direction = MV_RIGHT;break;
case 'a':snake.direction = MV_LEFT;break;
case 's':snake.direction = MV_DOWN;break;
}
} //end of while(1)
}