Węża miałem w osobnych plikach, ale tu wklejam całość.
#include <iostream>
#include <conio.h>
#include <time.h>
#include <Windows.h>
#include <vector>
void gotoxy(int x, int y)
{
HANDLE hCon;
COORD dwPos;
dwPos.X=x;
dwPos.Y=y;
hCon=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hCon, dwPos);
}
class Snake {
static const int board_Width = 20;
static const int board_Height = 40;
struct Segment
{
Segment(){};
Segment(int x, int y) : X(x), Y(y){};
int X;
int Y;
};
char Board[board_Width][board_Height];
std::vector<Segment> body;
Segment Food;
public:
bool collision{false};
enum class Direction{UP, DOWN, LEFT, RIGHT};
void SetFood() {
Food.X=2 + rand() % (board_Width - 4);
Food.Y=2 + rand() % (board_Height - 4);
}
void WriteToBoard() {
for (auto x : body) Board[x.X][x.Y]=char(219);
Board[Food.X][Food.Y]=char(176);
}
void EnlargeBody(int x, int y){
body.push_back(Segment(x,y));
}
void WipeBoard() {
for (int a = 0; a < board_Width; a++)
for (int b = 0; b < board_Height; b++) Board[a][b] = char(178);
}
void ShowBoard() {
gotoxy(0, 0);
for (int a = 0; a < board_Width; a++) {
for (int b = 0; b < board_Height; b++) std::cout << Board[a][b];
std::cout << "\n";
}
}
bool CheckCollision() {
for (auto x =body.rbegin(); x<body.rend() - 1; x++)
if ((body[0].X==x->X) && (body[0].Y == x->Y)) {
return true;
}
if ((body[0].X==Food.X) && (body[0].Y==Food.Y))
{
EnlargeBody(0,0);
SetFood();
}
return false;
}
void MoveSnake(Direction direction) {
int deltaV{0};
int deltaH{0};
switch (direction) {
case Direction::UP:
deltaV=1; break;
case Direction::DOWN:
deltaV=-1; break;
case Direction::LEFT:
deltaH=-1; break;
case Direction::RIGHT:
deltaH=1; break;
}
for (auto x =body.rbegin(); x<body.rend() - 1; x++) *x = *(x+1);
body[0].X += deltaH;
body[0].Y += deltaV;
if (body[0].X < 1) body[0].X=board_Width - 2;
if (body[0].X > board_Width - 2) body[0].X=1;
if (body[0].Y < 1) body[0].Y=board_Height - 2;
if (body[0].Y > board_Height - 2) body[0].Y=1;
if (CheckCollision()) collision=true;
}
};
int main() {
srand(time(NULL));
Snake snake;
snake.SetFood();
for (int i=22; i<27; i++) snake.EnlargeBody(11,i);
int key{0};
Snake::Direction direction = Snake::Direction::DOWN;
do{
if (_kbhit())
{
key=getch();
switch (key) {
case 224: continue;
case 77: if (direction!=Snake::Direction::DOWN)
direction = Snake::Direction::UP;
break;
case 75: if (direction!=Snake::Direction::UP)
direction = Snake::Direction::DOWN;
break;
case 72: if (direction!=Snake::Direction::RIGHT)
direction = Snake::Direction::LEFT;
break;
case 80: if (direction!=Snake::Direction::LEFT)
direction = Snake::Direction::RIGHT;
break;
}
}
snake.WipeBoard();
snake.MoveSnake(direction);
snake.WriteToBoard();
snake.ShowBoard();
Sleep(70);
}while (!snake.collision);
std::cout << "Koniec";
std::cin.get();
return 0;
}