贪吃蛇游戏c++面向对象代码
时间: 2023-07-09 11:30:57 浏览: 124
C++实现简单贪吃蛇游戏
好的,以下是一个简单的贪吃蛇游戏的 C++ 面向对象代码示例:
```cpp
#include <iostream>
#include <vector>
#include <conio.h>
#include <windows.h>
using namespace std;
const int WIDTH = 20; // 游戏界面宽度
const int HEIGHT = 20; // 游戏界面高度
const int FPS = 10; // 游戏帧率
// 定义坐标点结构体
struct Point {
int x;
int y;
};
// 定义运动方向枚举类型
enum Direction {
UP,
DOWN,
LEFT,
RIGHT
};
// 定义贪吃蛇类
class Snake {
public:
Snake(Point head) {
body.push_back(head);
direction = RIGHT;
}
void move() {
// 根据当前的运动方向移动贪吃蛇的身体
Point head = body.front();
switch (direction) {
case UP:
head.y -= 1;
break;
case DOWN:
head.y += 1;
break;
case LEFT:
head.x -= 1;
break;
case RIGHT:
head.x += 1;
break;
}
body.insert(body.begin(), head);
body.pop_back();
}
void change_direction(Direction dir) {
direction = dir;
}
void eat_food() {
// 将食物添加到身体的末尾
Point tail = body.back();
switch (direction) {
case UP:
tail.y += 1;
break;
case DOWN:
tail.y -= 1;
break;
case LEFT:
tail.x += 1;
break;
case RIGHT:
tail.x -= 1;
break;
}
body.push_back(tail);
}
bool check_collision() {
// 检查是否与边界或身体碰撞
Point head = body.front();
if (head.x < 0 || head.x >= WIDTH || head.y < 0 || head.y >= HEIGHT) {
return true;
}
for (int i = 1; i < body.size(); i++) {
if (head.x == body[i].x && head.y == body[i].y) {
return true;
}
}
return false;
}
void draw() {
// 在游戏界面上绘制贪吃蛇
system("cls");
for (int i = 0; i < body.size(); i++) {
cout << "o";
}
cout << endl;
}
private:
vector<Point> body;
Direction direction;
};
// 定义游戏类
class Game {
public:
Game() {
snake = Snake(Point{ WIDTH / 2, HEIGHT / 2 });
spawn_food();
score = 0;
}
void start() {
while (true) {
update();
draw();
Sleep(1000 / FPS);
}
}
private:
Snake snake;
Point food;
int score;
void update() {
// 更新游戏状态
if (_kbhit()) {
char input = _getch();
switch (input) {
case 'w':
snake.change_direction(UP);
break;
case 's':
snake.change_direction(DOWN);
break;
case 'a':
snake.change_direction(LEFT);
break;
case 'd':
snake.change_direction(RIGHT);
break;
}
}
snake.move();
if (check_food_collision()) {
snake.eat_food();
spawn_food();
score++;
}
if (snake.check_collision()) {
game_over();
}
}
void draw() {
// 在游戏界面上绘制贪吃蛇和食物
snake.draw();
cout << "Score: " << score << endl;
}
void spawn_food() {
// 随机生成食物位置
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
}
bool check_food_collision() {
// 检查是否与食物碰撞
Point head = snake.get_head();
if (head.x == food.x && head.y == food.y) {
return true;
}
return false;
}
void game_over() {
// 游戏结束,显示得分并提示是否重新开始
cout << "Game Over!" << endl;
cout << "Score: " << score << endl;
cout << "Press r to restart or q to quit." << endl;
while (true) {
char input = _getch();
if (input == 'r') {
snake = Snake(Point{ WIDTH / 2, HEIGHT / 2 });
spawn_food();
score = 0;
break;
}
else if (input == 'q') {
exit(0);
}
}
}
};
int main() {
Game game;
game.start();
return 0;
}
```
以上是一个比较简单的贪吃蛇游戏的 C++ 面向对象代码示例,您可以根据具体需求进行修改和完善。
阅读全文