帮我用c++实现一个面向对象的贪吃蛇游戏;输出的代码带换行的
时间: 2024-02-06 07:09:14 浏览: 68
基于C++实现的贪吃蛇游戏【100010903】
好的,下面是代码,请参考:
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int width = 20;
const int height = 20;
int x, y, fruitX, fruitY, score;
bool gameOver;
int tailX[100], tailY[100];
int nTail;
enum eDirection {STOP = 0, LEFT, RIGHT, UP, DOWN};
eDirection dir;
class SnakeGame {
public:
void Setup() {
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
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 print = false;
for (int k = 0; k < nTail; k++) {
if (tailX[k] == j && tailY[k] == i) {
cout << "o"; // 小蛇身体
print = true;
}
}
if (!print) {
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 = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; 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;
}
// 检测是否吃到水果
if (x == fruitX && y == fruitY) {
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
// 检测是否碰到自己
for (int i = 0; i < nTail; i++) {
if (tailX[i] == x && tailY[i] == y) {
gameOver = true;
}
}
}
void Run() {
while (!gameOver) {
Draw();
Input();
Logic();
Sleep(50); // 控制速度
}
}
};
int main() {
SnakeGame game;
game.Setup();
game.Run();
return 0;
}
```
这是一个简单的贪吃蛇游戏,使用了面向对象的编程思想。在 `SnakeGame` 类中,我们定义了 `Setup()` 初始化游戏状态,`Draw()` 绘制游戏界面,`Input()` 处理用户输入,`Logic()` 处理游戏逻辑,`Run()` 进行游戏循环。
阅读全文