#include <iostream> #include <conio.h> #include <windows.h> #include <vector> #include <ctime> using namespace std;
const int WIDTH = 20; const int HEIGHT = 20; const int MAX_LENGTH = 100;
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
class SnakeGame { private: bool gameOver; int x, y; int fruitX, fruitY; int score; vector<int> tailX; vector<int> tailY; int tailLength; Direction dir;
public: SnakeGame() { gameOver = false; dir = STOP; x = WIDTH / 2; y = HEIGHT / 2; fruitX = rand() % WIDTH; fruitY = rand() % HEIGHT; score = 0; tailLength = 0; }
void Setup() {
gameOver = false;
dir = STOP;
x = WIDTH / 2;
y = HEIGHT / 2;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
score = 0;
tailLength = 0;
tailX.clear();
tailY.clear();
}
void Draw() {
system("cls");
for (int i = 0; i < WIDTH + 2; i++)
cout << "#";
cout << endl;
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (j == 0)
cout << "#";
if (i == y && j == x)
cout << "O";
else if (i == fruitY && j == fruitX)
cout << "F";
else {
bool printTail = false;
for (int k = 0; k < tailLength; k++) {
if (tailX[k] == j && tailY[k] == i) {
cout << "o";
printTail = true;
}
}
if (!printTail)
cout << " ";
}
if (j == WIDTH - 1)
cout << "#";
}
cout << endl;
}
for (int i = 0; i < WIDTH + 2; i++)
cout << "#";
cout << endl;
cout << "分数: " << score << endl;
cout << "使用WASD控制方向,按X退出游戏" << endl;
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
if (dir != RIGHT) dir = LEFT;
break;
case 'd':
if (dir != LEFT) dir = RIGHT;
break;
case 'w':
if (dir != DOWN) dir = UP;
break;
case 's':
if (dir != UP) dir = DOWN;
break;
case 'x':
gameOver = true;
break;
}
}
}
void Logic() {
int prevX = tailX.empty() ? x : tailX[0];
int prevY = tailY.empty() ? y : tailY[0];
int prev2X, prev2Y;
if (!tailX.empty()) {
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < tailLength; i++) {
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
if (x >= WIDTH || x < 0 || y >= HEIGHT || y < 0)
gameOver = true;
for (int i = 0; i < tailLength; i++)
if (tailX[i] == x && tailY[i] == y)
gameOver = true;
if (x == fruitX && y == fruitY) {
score += 10;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
tailLength++;
if (tailX.size() < tailLength) {
tailX.push_back(prevX);
tailY.push_back(prevY);
}
}
}
bool IsGameOver() { return gameOver; }
};
int main() { srand(time(0)); SnakeGame game;
cout << "贪吃蛇游戏" << endl;
cout << "按任意键开始游戏..." << endl;
_getch();
game.Setup();
while (!game.IsGameOver()) {
game.Draw();
game.Input();
game.Logic();
Sleep(100);
}
cout << "游戏结束!最终分数: " << endl;
cout << "按任意键退出..." << endl;
_getch();
return 0;}