用c++语言面对对象思想,再用vector构建二维数组,写出一个贪吃蛇代码。其中食物类构成,代码
时间: 2024-03-18 07:38:33 浏览: 65
基于二维数组的简易贪吃蛇游戏c++源码(课程作业).zip
好的,我会尽力回答你的问题。以下是基于C++语言和面向对象思想的贪吃蛇代码,其中使用了vector构建二维数组,同时实现了食物类。
```c++
#include <iostream>
#include <vector>
#include <conio.h>
#include <windows.h>
using namespace std;
// 坐标类
class Coordinate {
public:
int x;
int y;
Coordinate(int _x = 0, int _y = 0) {
x = _x;
y = _y;
}
};
// 食物类
class Food {
public:
Coordinate coordinate;
Food() {
srand((unsigned)time(NULL));
coordinate.x = rand() % 20;
coordinate.y = rand() % 20;
}
void generateFood() {
srand((unsigned)time(NULL));
coordinate.x = rand() % 20;
coordinate.y = rand() % 20;
}
};
// 贪吃蛇类
class Snake {
public:
vector<Coordinate> body;
Coordinate direction;
int length;
Snake() {
length = 3;
direction.x = 1;
direction.y = 0;
body.push_back(Coordinate(0, 0));
body.push_back(Coordinate(1, 0));
body.push_back(Coordinate(2, 0));
}
void move() {
// 计算蛇头新的位置
Coordinate newHead = body[length - 1];
newHead.x += direction.x;
newHead.y += direction.y;
// 判断蛇头是否与食物重合
bool isEatFood = (newHead.x == food.coordinate.x && newHead.y == food.coordinate.y);
// 将蛇头插入到身体最后面
body.push_back(newHead);
// 判断是否吃到了食物
if (!isEatFood) {
// 如果没有吃到食物,将蛇尾移除
body.erase(body.begin());
}
else {
// 如果吃到了食物,重新生成一个食物
food.generateFood();
length++;
}
}
bool isDead() {
// 判断蛇头是否超过边界
if (body[length - 1].x < 0 || body[length - 1].x >= 20 || body[length - 1].y < 0 || body[length - 1].y >= 20) {
return true;
}
// 判断蛇头是否与身体重合
for (int i = 0; i < length - 1; i++) {
if (body[i].x == body[length - 1].x && body[i].y == body[length - 1].y) {
return true;
}
}
return false;
}
private:
Food food;
};
// 游戏类
class Game {
public:
void start() {
while (true) {
// 清空屏幕
system("cls");
// 输出地图
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
bool isSnake = false;
// 判断该位置是否为蛇身
for (int k = 0; k < snake.length; k++) {
if (snake.body[k].x == j && snake.body[k].y == i) {
isSnake = true;
break;
}
}
// 输出地图
if (isSnake) {
cout << "■";
}
else if (food.coordinate.x == j && food.coordinate.y == i) {
cout << "★";
}
else {
cout << "□";
}
}
cout << endl;
}
// 判断是否死亡
if (snake.isDead()) {
cout << "Game Over" << endl;
break;
}
// 接收用户输入
if (_kbhit()) {
switch (_getch()) {
case 'w':
if (snake.direction.y != 1) {
snake.direction.x = 0;
snake.direction.y = -1;
}
break;
case 's':
if (snake.direction.y != -1) {
snake.direction.x = 0;
snake.direction.y = 1;
}
break;
case 'a':
if (snake.direction.x != 1) {
snake.direction.x = -1;
snake.direction.y = 0;
}
break;
case 'd':
if (snake.direction.x != -1) {
snake.direction.x = 1;
snake.direction.y = 0;
}
break;
}
}
// 移动蛇
snake.move();
// 延时
Sleep(100);
}
}
private:
Snake snake;
Food food;
};
int main() {
Game game;
game.start();
return 0;
}
```
其中,贪吃蛇类包含了蛇的身体、移动方向和长度等信息,食物类包含了食物的位置信息,游戏类包含了游戏的开始、结束和循环等逻辑。整个游戏的流程如下:
1. 初始化贪吃蛇和食物,输出地图;
2. 接收用户输入,移动蛇;
3. 判断是否死亡,如果死亡则结束游戏,否则继续循环;
4. 延时一段时间,再次循环。
希望这个代码能够帮助到你!
阅读全文