#include <iostream>
#include <windows.h>
#include <conio.h>
#include <ctime>
#include <cstdlib>
const int WIDTH = 80;
const int HEIGHT = 20;
struct Snake {
int x[WIDTH * HEIGHT];
int y[WIDTH * HEIGHT];
int length;
};
struct Food {
int x;
int y;
};
void initSnake(Snake& snake) {
snake.length = 5;
for (int i = 0; i < snake.length; i++) {
snake.x[i] = WIDTH / 2 - i;
snake.y[i] = HEIGHT / 2;
}
}
void initFood(Food& food) {
std::srand(static_cast<unsigned int>(std::time(ddnullptr)));
food.x = std::rand() % (WIDTH - 2) + 1;
food.y = std::rand() % (HEIGHT - 2) + 1;
}
void draw(const Snake& snake, const Food& food) {
system("cls");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1) {
std::cout << "#";
}
else {
bool isSnake = false;
for (int k = 0; k < snake.length; k++) {
if (snake.x[k] == j && snake.y[k] == i) {
std::cout << "O";
isSnake = true;
break;
}
}
if (!isSnake) {
if (i == food.y && j == food.x) {
std::cout << "$";
}
else {
std::cout << " ";
}
}
}
}
std::cout << std::endl;
}
}
void move(Snake& snake, int& direction, const Food& food) {
for (int i = snake.length - 1; i > 0; i--) {
snake.x[i] = snake.x[i - 1];
snake.y[i] = snake.y[i - 1];
}
if (direction == 0) {
snake.x[0]++;
}
else if (direction == 1) {
snake.x[0]--;
}
else if (direction == 2) {
snake.y[0]++;
}
else if (direction == 3) {
snake.y[0]--;
}
if (snake.x[0] == food.x && snake.y[0] == food.y) {
snake.length++;
snake.x[snake.length - 1] = snake.x[snake.length - 2];
snake.y[snake.length - 1] = snake.y[snake.length - 2];
initFood(const_cast<Food&>(food));
}
}
bool isGameOver(const Snake& snake) {
if (snake.x[0] == 0 || snake.x[0] == WIDTH - 1 || snake.y[0] == 0 || snake.y[0] == HEIGHT - 1) {
return true;
}
for (int i = 1; i < snake.length; i++) {
if (snake.x[0] == snake.x[i] && snake.y[0] == snake.y[i]) {
return true;
}
}
return false;
}
int main() {
Snake snake;
Food food;
initSnake(snake);
initFood(food);
int direction = 0;
bool gameOver = false;
while (!gameOver) {
draw(snake, food);
if (_kbhit()) {
char ch = _getch();
if (ch == 'd' && direction!= 1) {
direction = 0;
}
else if (ch == 'a' && direction!= 0) {
direction = 1;
}
else if (ch =='s' && direction!= 3) {
direction = 2;
}
else if (ch == 'w' && direction!= 2) {
direction = 3;
}
}
move(snake, direction, food);
gameOver = isGameOver(snake);
Sleep(100);
}
std::cout << "游戏结束!" << std::endl;
return 0;
}