//--.cpp(执行文件)--//
#include <windows.h>
#include <ctime>
#include <iostream>
#include "snake.h"
using namespace std;
void Csnake::InitInstance()
{
snakeMap.resize(line);
for(int i=0;i<line;i++)
{
snakeMap[i].resize(row);
for(int j=0;j<row;j++)
{
if(i==0||i==line-1)snakeMap[i][j]='-';
else if(j==0||j==line)snakeMap[i][j]='|';
else snakeMap[i][j]=' ';
}
for(int m=1;m<6;m++)snakeMap[line/2][m]='@';
firstSign.setPoint(5,line/2);
secondSign.setPoint(4,line/2);
lastSign.setPoint(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()
{
int choice=GetDirections();
int r;int l;
static bool eatFood=true;
if(eatFood)
{
do
{
srand(time(0));
r=(rand()%row-2)+1;
l=(rand()%line-2)+1;
if(snakeMap[r][l]!='@')snakeMap[r][l]='*';
}while (snakeMap[r][l]=='@');
}
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,firstSign.lSign+1);
else nextSign=firstSign+(firstSign-secondSign);
break;
default:
nextSign=firstSign+(firstSign-secondSign);
}
if(getSymbol(nextSign)!='*'&&getSymbol(nextSign)!='@'
&& nextSign.rSign<row-1 && nextSign.rSign>0
&& nextSign.lSign<line-1 && nextSign.lSign>0)
//如果没有碰到食物(且没有死亡的情况下),直接将蛇尾减去,并在移动方向上在firstSign前面加上新的蛇头
{
change(snakeMap[nextSign.rSign][nextSign.lSign],snakeMap[lastSign.rSign][lastSign.lSign]);
//-------改变蛇头坐标--------
firstSign.rSign=nextSign.rSign; firstSign.lSign=nextSign.lSign;
secondSign.rSign=firstSign.rSign; secondSign.lSign=firstSign.lSign;
//-------改变蛇尾坐标--------
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
if(snakeMap[lastSign.rSign+i][lastSign.lSign+j]=='@')
{lastSign.rSign+=i;lastSign.lSign+=j;}
//---------------------------
eatFood=false;
return true;
}
//-----吃食-----
else if(getSymbol(nextSign)=='*')
{
snakeMap[nextSign.rSign][nextSign.lSign]='@';
firstSign.rSign=nextSign.rSign;firstSign.lSign=nextSign.lSign;
return true;
}
//-----死亡-----
else 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(1000);
system("cls");
}
[此贴子已经被作者于2006-6-13 9:13:53编辑过]