#include <iostream>
#include <Windows.h>
#include <conio.h>
#include <time.h>
#include <vector>
using namespace std;
const int WIDTH = 30;
const int HEIGHT = 20;
struct Point {
int x, y;
};
enum Direction {
UP, DOWN, LEFT, RIGHT
};
class Snake {
public:
Snake() {
body.push_back({ WIDTH / 2, HEIGHT / 2 });
body.push_back({ WIDTH / 2, HEIGHT / 2 + 1 });
body.push_back({ WIDTH / 2, HEIGHT / 2 + 2 });
}
void move(Direction dir) {
Point head = body.front();
switch (dir) {
case UP:
head.y--;
break;
case DOWN:
head.y++;
break;
case LEFT:
head.x--;
break;
case RIGHT:
head.x++;
break;
}
body.pop_back();
body.insert(body.begin(), head);
}
bool eat(Point p) {
if (body.front().x == p.x && body.front().y == p.y) {
body.push_back(p);
return true;
}
return false;
}
bool hit() {
Point head = body.front();
for (int i = 1; i < body.size(); i++) {
if (head.x == body[i].x && head.y == body[i].y) {
return true;
}
}
return head.x < 0 || head.x >= WIDTH || head.y < 0 || head.y >= HEIGHT;
}
vector<Point> getBody() {
return body;
}
private:
vector<Point> body;
};
class Food {
public:
void spawn(vector<Point> obstacles) {
srand(time(NULL));
do {
pos = { rand() % WIDTH, rand() % HEIGHT };
} while (conflict(obstacles));
}
Point getPos() {
return pos;
}
private:
bool conflict(vector<Point> obstacles) {
for (int i = 0; i < obstacles.size(); i++) {
if (pos.x == obstacles[i].x && pos.y == obstacles[i].y) {
return true;
}
}
return false;
}
Point pos;
};
void drawBoard(Snake snake, Food food) {
system("cls"); // 清空控制台
vector<Point> obstacles = snake.getBody();
obstacles.push_back(food.getPos());
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
bool isObstacle = false;
for (int i = 0; i < obstacles.size(); i++) {
if (x == obstacles[i].x && y == obstacles[i].y) {
isObstacle = true;
break;
}
}
if (isObstacle) {
cout << "x";
}
else {
cout << " ";
}
}
cout << endl;
}
}
int main() {
Snake snake;
Food food;
food.spawn(snake.getBody());
Direction dir = RIGHT;
bool gameOver = false;
while (!gameOver) {
if (_kbhit()) {
char input = _getch();
switch (input) {
case 'w':
case 'W':
if (dir != DOWN) {
dir = UP;
}
break;
case 's':
case 'S':
if (dir != UP) {
dir = DOWN;
}
break;
case 'a':
case 'A':
if (dir != RIGHT) {
dir = LEFT;
}
break;
case 'd':
case 'D':
if (dir != LEFT) {
dir = RIGHT;
}
break;
case 'q':
case 'Q':
gameOver = true;
break;
}
}
snake.move(dir);
if (snake.eat(food.getPos())) {
food.spawn(snake.getBody());
}
drawBoard(snake, food);
if (snake.hit()) {
cout << "Game Over!" << endl;
gameOver = true;
}
Sleep(100); // 控制游戏速度
}
return 0;
}
使用WASD控制方向