1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
#include <windows.h>
#include <iostream>
#include <list>
struct Position
{
int x, y;
Position(int x_, int y_): x(x_), y(y_) {}
};
void goto_xy(int x, int y)
{
COORD pos = { x, y };
SetConsoleCursorPosition(
GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void clear_screen()
{
DWORD written;
COORD start = { 0, 0 };
FillConsoleOutputCharacter(
GetStdHandle(STD_OUTPUT_HANDLE),
' ', 80 * 25, start, &written);
goto_xy(0, 0);
}
void draw_snake(const std::list<Position> & snake)
{
std::list<Position>::const_iterator cur_it = snake.begin();
std::list<Position>::const_iterator end_it = snake.end();
for (; cur_it != end_it; ++cur_it)
{
goto_xy(cur_it->x, cur_it->y);
std::cout << '@' << std::flush;
}
}
int main()
{
std::list<Position> snake_body;
snake_body.push_front(Position(0, 0));
snake_body.push_front(Position(0, 1));
snake_body.push_front(Position(0, 2));
snake_body.push_front(Position(1, 2));
snake_body.push_front(Position(1, 3));
snake_body.push_front(Position(2, 3));
draw_snake(snake_body);
Sleep(1000);
for (int i = 0; i < 5; ++i)
{
// add new head
snake_body.push_front(Position(3 + i, 3));
// remove old tail
snake_body.pop_back();
// redraw
clear_screen();
draw_snake(snake_body);
Sleep(1000);
}
clear_screen();
}
|