65,187
社区成员




#include <iostream>
#include <deque>
#include <windows.h>
using namespace std;
#define MAX_WIDTH 16
#define MAX_HEIGHT 16
#define SLEEP_TIME 250
#define KEYDOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
#define KEYUP(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)
class MY_POINT
{
public:
int x, y;
MY_POINT(){}
MY_POINT(int _x, int _y):x(_x), y(_y){}
bool operator==(MY_POINT &pt){return pt.x == x && pt.y == y;}
};
class GameStatus
{
public:
char map[MAX_HEIGHT+1][MAX_WIDTH+1];
deque<MY_POINT> snack;
MY_POINT pt_tar;
enum STATE{RUNNING, END};
STATE game_state;
char dir;
GameStatus()
{
InitMap();
snack.push_back(MY_POINT(MAX_WIDTH/2, MAX_HEIGHT/2));
snack.push_back(MY_POINT(MAX_WIDTH/2, MAX_HEIGHT/2-1));
snack.push_back(MY_POINT(MAX_WIDTH/2, MAX_HEIGHT/2-2));
RandTarget();
dir = 's';
game_state = RUNNING;
}
void EndGame()
{
game_state = END;
}
void InitMap()
{
memset(map, '-', sizeof map);
for (int i = 0; i < MAX_HEIGHT; i++)
{
map[i][MAX_HEIGHT] = '\0';
}
}
void RandTarget()
{
pt_tar.x = rand()%(MAX_WIDTH);
pt_tar.y = rand()%(MAX_HEIGHT);
}
bool InMap(int x, int y)
{
return x < MAX_WIDTH && y < MAX_HEIGHT && x >= 0 && y >= 0;
}
bool InMap(MY_POINT &pt)
{
return InMap(pt.x, pt.y);
}
void RefreshMap()
{
InitMap();
for (int i = 0; i < snack.size(); i++)
{
map[snack[i].y][snack[i].x] = 'x';
}
map[pt_tar.y][pt_tar.x] = '@';
}
void ShowMap()
{
system("cls");
for (int i = 0; i < MAX_HEIGHT; i++)
{
cout << map[i] << endl;
}
}
void NextState()
{
MY_POINT head = snack[0];
switch (dir)
{
case 's':
head.y++;
break;
case 'a':
head.x--;
break;
case 'd':
head.x++;
break;
case 'w':
head.y--;
break;
default:
break;
}
if (!InMap(head))
{
EndGame();
return;
}
for (int i = 0; i < snack.size(); i++)
{
if (head == snack[i])
{
EndGame();
return;
}
}
if (head == pt_tar) // target is hit
{
snack.push_front(head);
RandTarget();
return;
}
else
{
snack.push_front(head);
snack.pop_back();
}
}
void SetDirection()
{
if (KEYDOWN(0x25)) // VK_LEFT 25
dir = 'a';
else if (KEYDOWN(0x28)) // VK_DOWN 28
dir = 's';
else if (KEYDOWN(0x26)) // VK_UP 26
dir = 'w';
else if (KEYDOWN(0x27)) // VK_RIGHT 27
dir = 'd';
}
void GameMainLoop()
{
while (game_state == RUNNING)
{
Sleep(SLEEP_TIME);
SetDirection();
NextState();
RefreshMap();
ShowMap();
}
}
};
int main()
{
GameStatus gs;
gs.GameMainLoop();
cout << "Game Over!" << endl;
cin >> ws;
}