#include <iostream>
#include <windows.h>
void main()
{
const int w = 20;
const int h = 20;
const int s = w * h;
char map[s] = { };
int snake[s];
int len = 2;
snake[0] = 0;
snake[1] = 1;
int food;
int dir = 3;
for (int i = 0;i < 5; ++i)
map[rand() % (s-1)+1] = 1;
do{food = rand() % s;}while (map[food] == 1);
while (1)
{
system("cls");
int temp[s] = {};
for (int i = 0; i < s; ++i)
temp[i] = map[i];
temp[food] = 2;
for (int i = 0;i < len-1; ++i)
temp[ snake[i] ] = 3;
temp[ snake[len-1] ] = 4;
for (int i = 0;i < s; ++i)
{
switch(temp[i])
{
case 0:std::cout<<"□";break;
case 1:std::cout<<"■";break;
case 2:std::cout<<"★";break;
case 3:std::cout<<"◎";break;
case 4:std::cout<<"●";break;
}
if (i % w == w-1)
std::cout<<std::endl;
}
snake[len-1];
int xx[] = {0,0,-1,1};
int yy[] = {-1,1,0,0};
int nextx = snake[len-1] % w + xx[dir];
if (nextx < 0)
nextx = w-1;
else if (nextx > w-1)
nextx = 0;
int nexty = snake[len-1] / w + yy[dir];
if (nexty < 0)
nexty = h-1;
else if (nexty > h-1)
nexty = 0;
int next = nextx + nexty * w;
bool die = false;
if (map[next] == 1)
die = true;
for (int i = 0;i < len-1; ++i)
if (snake[i] == next)
{
die = true;
break;
}
if (die)
{
std::cout<<"死亡!";
system("pause");
return;
}
if (next == food)
{
snake[len] = next;
len++;
do{
food = rand() % s;
}while (map[food] == 1);
}
for (int i = 1; i < len; ++i)
snake[i-1] = snake[i];
snake[len-1] = next;
if (GetAsyncKeyState('W') & 1)
{
if (dir != 1)
dir = 0;
}
if (GetAsyncKeyState('S') & 1)
{
if (dir != 0)
dir = 1;
}
if (GetAsyncKeyState('A') & 1)
{
if (dir != 3)
dir = 2;
}
if (GetAsyncKeyState('D') & 1)
{
if (dir != 2)
dir = 3;
}
Sleep(100);
}
}