运行情况:
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
const int WIDTH = 20;
const int HEIGHT = 20;
bool gameOver;
int x, y, fruitX, fruitY, score;
vector<pair<int, int>> snake;
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
Direction dir;
void Setup() {
gameOver = false;
dir = STOP;
x = WIDTH / 2;
y = HEIGHT / 2;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
score = 0;
snake.push_back(make_pair(x, y));
}
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 isSnakePart = false;
for (auto part : snake) {
if (part.first == j && part.second == i) {
cout << "o";
isSnakePart = true;
break;
}
}
if (!isSnakePart) cout << " ";
}
if (j == WIDTH - 1)cout << "#";
}
cout << endl;
}
for (int i = 0; i < WIDTH + 2; i++)
cout << "#";
cout << endl;
cout << "Score: " << score << endl;
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameOver = true;
break;
}
}
}
void Logic() {
int prevX = snake[0].first;
int prevY = snake[0].second;
int prev2X, prev2Y;
snake[0].first = x;
snake[0].second = y;
for (size_t i = 1; i < snake.size(); i++) {
prev2X = snake[i].first;
prev2Y = snake[i].second;
snake[i].first = prevX;
snake[i].second = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
if (x >= WIDTH) x = 0; else if (x < 0) x = WIDTH - 1;
if (y >= HEIGHT) y = 0; else if (y < 0) y = HEIGHT - 1;
if (x == fruitX && y == fruitY) {
score += 10;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
snake.push_back(make_pair(-1, -1));
}
for (size_t i = 1; i < snake.size(); i++) {
if (snake[i].first == x && snake[i].second == y) {
gameOver = true;
}
}
}
int main() {
srand(static_cast<unsigned>(time(0)));
Setup();
while (!gameOver) {
Draw();
Input();
Logic();
Sleep(100);
}
return 0;
}
鄙人不才,若不和大佬的观点,望谅解