帮我用c++实现一个面向对象的贪吃蛇游戏
时间: 2024-02-06 18:09:11 浏览: 25
好的,下面是一个简单的面向对象贪吃蛇游戏的代码,仅供参考:
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
class Snake {
private:
int x, y;
public:
Snake(int x, int y) {
this->x = x;
this->y = y;
}
void move(int direction) {
switch (direction) {
case 1: y--; break;
case 2: y++; break;
case 3: x--; break;
case 4: x++; break;
}
}
int getX() { return x; }
int getY() { return y; }
};
class Food {
private:
int x, y;
public:
Food(int x, int y) {
this->x = x;
this->y = y;
}
int getX() { return x; }
int getY() { return y; }
};
class Game {
private:
int width, height;
Snake *snake;
Food *food;
public:
Game(int width, int height) {
this->width = width;
this->height = height;
snake = new Snake(width/2, height/2);
food = new Food(rand()%width, rand()%height);
}
void draw() {
system("cls");
for (int i = 0; i <= width+1; i++) cout << "#";
cout << endl;
for (int i = 0; i < height; i++) {
cout << "#";
for (int j = 0; j < width; j++) {
if (snake->getX() == j && snake->getY() == i)
cout << "O";
else if (food->getX() == j && food->getY() == i)
cout << "X";
else
cout << " ";
}
cout << "#" << endl;
}
for (int i = 0; i <= width+1; i++) cout << "#";
cout << endl;
}
void processInput() {
if (_kbhit()) {
switch (_getch()) {
case 'w': snake->move(1); break;
case 's': snake->move(2); break;
case 'a': snake->move(3); break;
case 'd': snake->move(4); break;
}
}
}
void update() {
if (snake->getX() == food->getX() && snake->getY() == food->getY()) {
delete food;
food = new Food(rand()%width, rand()%height);
}
}
bool gameOver() {
if (snake->getX() < 0 || snake->getX() >= width ||
snake->getY() < 0 || snake->getY() >= height)
return true;
return false;
}
};
int main() {
Game game(20, 10);
while (!game.gameOver()) {
game.draw();
game.processInput();
game.update();
Sleep(100);
}
cout << "Game Over!" << endl;
return 0;
}
```
本代码使用了三个类:`Snake`表示贪吃蛇,`Food`表示食物,`Game`表示游戏。其中,`Snake`和`Food`分别有一个坐标(x,y),表示它们在游戏场景中的位置。`Game`类中包含了一个`Snake`对象和一个`Food`对象,以及游戏场景的宽度和高度。在`Game`类中,`draw()`方法用于绘制游戏场景,`processInput()`方法用于处理玩家输入,`update()`方法用于更新游戏状态,`gameOver()`方法用于判断游戏是否结束。在`main()`函数中,循环调用`draw()`、`processInput()`、`update()`方法,直到游戏结束。
需要注意的是,本代码只是一个简单的贪吃蛇游戏实现,并没有考虑到贪吃蛇的身体长度、碰撞检测等问题,仅供参考。