#include<bits/stdc++.h>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<string.h>
#include<list>
#include<deque>
#include<stack>
#include<windows.h>
#include<time.h>
#include<stdio.h>
#include<conio.h>
#include<assert.h>
#include<ctype.h>
#include<errno.h>
#include<float.h>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<limits.h>
#include<locale.h>
#include<math.h>
#include<stdlib.h>
#include<wchar.h>
#include<wctype.h>
using namespace std;
const int WIDTH = 50; //游戏窗口的宽度
const int HEIGHT = 20; //游戏窗口的高度
const int SNAKE_LENGTH = 4; //蛇的初始长度
const char HEAD_CHAR = '@'; //蛇头的字符表示
const char BODY_CHAR = '+'; //蛇身的字符表示
const char FOOD_CHAR = '$'; //食物的字符表示
struct Point {
int x;
int y;
};
struct Snake {
int length;
Point head;
Point body[WIDTH * HEIGHT];
int direction; // 0: up, 1: right, 2: down, 3: left
};
struct Food {
Point position;
};
void init(Snake& snake, 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) {
cout << "#";
} else {
cout << " ";
}
}
cout << endl;
}
// 初始化蛇的位置和长度
snake.head.x = WIDTH / 2;
snake.head.y = HEIGHT / 2;
snake.length = SNAKE_LENGTH;
for (int i = 0; i < SNAKE_LENGTH; i++) {
snake.body[i].x = snake.head.x;
snake.body[i].y = snake.head.y + i;
}
snake.direction = 0;
// 初始化食物的位置
srand((unsigned)time(NULL)); // 随机数种子
food.position.x = rand() % (WIDTH - 2) + 1;
food.position.y = rand() % (HEIGHT - 2) + 1;
}
void update(Snake& snake, Food& food) {
// 移动蛇
for (int i = snake.length - 1; i > 0; i--) {
snake.body[i] = snake.body[i - 1];
}
snake.body[0] = snake.head;
switch(snake.direction) {
case 0:
snake.head.y--;
break;
case 1:
snake.head.x++;
break;
case 2:
snake.head.y++;
break;
case 3:
snake.head.x--;
break;
}
// 检测碰撞
if (snake.head.x == 0 || snake.head.x == WIDTH - 1 || snake.head.y == 0 || snake.head.y == HEIGHT - 1) {
cout << "Game over!" << endl;
exit(0);
}
for (int i = 1; i < snake.length; i++) {
if (snake.head.x == snake.body[i].x && snake.head.y == snake.body[i].y) {
cout << "Game over!" << endl;
exit(0);
}
}
if (snake.head.x == food.position.x && snake.head.y == food.position.y) {
snake.length++;
food.position.x = rand() % (WIDTH - 2) + 1;
food.position.y = rand() % (HEIGHT - 2) + 1;
}
// 生成食物
cout << FOOD_CHAR << endl;
cout << food.position.x << "," << food.position.y << endl;
// 绘制蛇
cout << HEAD_CHAR << endl;
cout << snake.head.x << "," << snake.head.y << endl;
for (int i = 1; i < snake.length; i++) {
cout << BODY_CHAR << endl;
cout << snake.body[i].x << "," << snake.body[i].y << endl;
}
}
int main() {
Snake snake;
Food food;
init(snake, food);
while (true) {
update(snake, food);
Sleep(100);
}
return 0;
}