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1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, },
};
struct SData
{
int nRow;
int nCol;
int nRowBk;
int nColBk;
};
SData snake[20];
SData food;
int nDir = 0;
enum{
NONO,
UP,
DOWN,
LEFT,
RIGHT
};
int _tmain(int argc, _TCHAR* argv[])
{
int nLen = 1;
srand((unsigned)time(NULL));
snake[0].nRow = rand() % 13 + 1;
snake[0].nCol = rand() % 17 + 1;
food.nRow = rand() % 13 + 1;
food.nCol = rand() % 17 + 1;
while (true)
{
system("cls");
Sleep(100);
if (KEY_DOWN(VK_UP))
{
nDir = UP;
}
else if (KEY_DOWN(VK_DOWN))
{
nDir = DOWN;
}
else if (KEY_DOWN(VK_LEFT))
{
nDir = LEFT;
}
else if (KEY_DOWN(VK_RIGHT))
{
nDir = RIGHT;
}
snake[0].nRowBk = snake[0].nRow;//备份蛇头坐标
snake[0].nColBk = snake[0].nCol;
switch (nDir)
{
case 1:
snake[0].nRow--;
break;
case 2:
snake[0].nRow++;
break;
case 3:
snake[0].nCol--;
break;
case 4:
snake[0].nCol++;
break;
default:
break;
}
if (snake[0].nRow == food.nRow &&snake[0].nCol == food.nCol)
{
nLen++;//身长加1
food.nRow = rand() % 13 + 1;
food.nCol = rand() % 17 + 1;
}
for (int i = 1; i < nLen; i++)
{
snake[i].nRowBk = snake[i].nRow; //备份蛇身坐标
snake[i].nColBk = snake[i].nCol;
snake[i].nRow = snake[i - 1].nRowBk;//前后坐标
snake[i].nCol = snake[i - 1].nColBk;
}
for (int i = 0; i < 15; i++)//渲染
{
for (int j = 0; j < 20; j++)
{
bool bts = false;
for (int k = 0; k < nLen; k++)
{
if (i == snake[k].nRow &&j == snake[k].nCol)
{
bts = true;
}
}
if (1 == arrMap[i][j])
{
cout << "■";
}
else if (bts)
{
cout << "★";
}
else if (i == food.nRow &&j == food.nCol)
{
cout << "☆";
}
else
{
cout << " ";
}
}
cout << endl;
}
cout << "<" << snake[0].nRow << "," << snake[0].nCol << ">" << endl;
}
return 0;
}