我大概在一个多月前把自己上学期写的c代码的贪吃蛇游戏push到csdn上,并且说c风格的贪吃蛇写起来有些麻烦(贪吃蛇游戏的c语言实现),准备用面向对象的c++再写一遍。现在我们专业恰好刚教完了c++,学校也布置了一道简单的贪吃蛇的编程题目,实现下来,的确觉得c++的思路清晰很多,所以再次把c++的代码push上来,供大家对比参考:)

直接上代码,c++把整个游戏拆分成几个文件,分开上,有一定的c++基础的同学应该可以很容易看懂。

1、全局头文件(global.hpp)

#ifndef _GLOBAL_H_

#define _GLOBAL_H_

#ifndef SYMBOLS

#define HEAD '@'

#define BODY 'X'

#define EMPTY '+'

#define FOOD '$'

#endif // !SYMBOLS

enum direction { up = 0, down = 1, left = 2, right = 4, freeze = 5 };

struct point {

int x;

int y;

point(int x = 0, int y = 0) : x(x), y(y) {}

point(const point& another) : x(another.x), y(another.y) {}

point& operator=(const point& other) {

x = other.x;

y = other.y;

return *this;

}

friend bool operator==(const point& point1, const point& point2) {

return point1.x == point2.x && point1.y == point2.y;

}

point& move(direction d) {

switch (d) {

case up:

x--;

break;

case down:

x++;

break;

case left:

y--;

break;

case right:

y++;

break;

case freeze:

default:

break;

}

return *this;

}

};

#endif // !_GLOBAL_H_

2、snake类的声明和实现(snake.hpp)

(为了简化结构,把声明和实现共同放在了hpp文件里,减少了一点封装性,实际上应该分开头文件和实现文件好一点)

此处使用了容器list作为蛇身(body)的表达形式,这样可以非常方便地进行表达,读者有兴趣可以用数组实现一下,一不小心就会出现有趣的内存错误。。。

#ifndef _SNAKE_H_

#define _SNAKE_H_

#include

#include

#include "global.hpp"

class snake {

point head;

std::list body;

public:

snake(point initial_head);

snake();

~snake() {}

point& getHead();

std::list& getbody();

void grow(point);

void setHead(point);

};

snake::snake() {

head.x = 0;

head.y = 0;

}

snake::snake(point initial_head) {

setHead(initial_head);

}

void snake::setHead(point _head) {

head = _head;

}

void snake::grow(point second_node) {

this -> body.push_front(second_node);

}

point& snake::getHead() {

return head;

}

std::list& snake::getbody() {

return body;

}

#endif

3、map类的声明和实现(map.hpp)

在这里,map中应该包含一个snake类作为组合关系。

在组合关系里面,想要直接修改snake的各种参数是不可行的,所以在前面snake类的声明里加上了诸如setHead(), getHead(), getbody() 这一类的函数。

#ifndef _MAP_H_

#define _MAP_H_

#include

#include "global.hpp"

#include "snake.hpp"

class map {

private:

char** _map;

snake _snake;

int height, width;

std::list foods;

public:

map();

map(point initial_size, point initial_head,

std::list initial_foods);

~map();

void move(direction d);

void print();

bool isGameOver();

bool isEat();;

void makemap(void);

};

map::map() {

_map = NULL;

height = width = 0;

}

void map::makemap() { // 这个是用来更新地图的

for (int i = 0; i < height; i++) {

for (int j = 0; j < width; j++)

_map[i][j] = 0;

}

for (std::list::iterator i = foods.begin(); i != foods.end(); ++i) {

_map[i->x][i->y] = FOOD;

}

_map[_snake.getHead().x][_snake.getHead().y] = HEAD;

for (std::list::iterator i = _snake.getbody().begin();

i != _snake.getbody().end(); ++i) {

_map[i->x][i->y] = BODY;

}

for (int i = 0; i < height; i++) {

for (int j = 0; j < width; j++) {

if (_map[i][j] == 0)

_map[i][j] = EMPTY;

}

}

}

map::map(point initial_size, point initial_head, std::list initial_foods)

{

height = initial_size.x;

width = initial_size.y;

_map = new char*[height];

for (int i = 0; i < height; i++)

_map[i] = new char[width]();

_snake.setHead(initial_head);

foods = initial_foods;

makemap();

}

map::~map() {

for (int i = 0; i < height; i++) {

delete []_map[i];

}

delete []_map;

}

void map::print() {

for (int i = 0; i < height; i++) {

for (int j = 0; j < width; j++) {

std::cout << _map[i][j];

}

std::cout << std::endl;

}

std::cout << std::endl;

}

bool map::isGameOver() {

point temp = _snake.getHead();

if (temp.x == height || temp.y == width || temp.x < 0 || temp.y < 0)

return true;

if (_map[temp.x][temp.y] == BODY) return true;

return false;

}

bool map::isEat() {

point temp = _snake.getHead();

if (temp.x == height || temp.y == width || temp.x < 0 || temp.y < 0)

return false;

if (_map[temp.x][temp.y] == FOOD) return true;

else return false;

}

void map::move(direction d) {

point temp_f = _snake.getHead();

if (!(_snake.getbody().empty())) { // 为了避免追尾问题

_map[_snake.getbody().back().x][_snake.getbody().back().y] = EMPTY;

}

_snake.getHead().move(d);

if (_snake.getHead() == _snake.getbody().front()) { // 判断蛇是否往回走

_snake.setHead(temp_f);

_map[_snake.getbody().back().x][_snake.getbody().back().y] = BODY;

return;

}

if (!isGameOver()) {

if (isEat()) {

point eaten = _snake.getHead();

foods.remove(eaten);

_snake.grow(temp_f);

} else {

_snake.getbody().push_front(temp_f);

_snake.getbody().pop_back();

}

makemap();

} else {

if (!(_snake.getbody().empty())) {

_map[_snake.getbody().back().x][_snake.getbody().back().y] = BODY;

}

}

}

#endif

蛇移动的算法是,头先动,如果判断可以走,则把头原来的位置push_front到body的头部,然后用pop_back把body的尾部抹去

(读者不熟悉list容器的操作的话可以先去了解一下,很容易的:))

4、游戏运行主文件(game.cpp)

#include "map.hpp"

#include "global.hpp"

#include

#include

#include

using std::cin;

using std::cout;

using std::cerr;

using std::endl;

class InvalidInputException {

public:

InvalidInputException() { cerr << "Invalid input!" << endl; }

};

class DuplicateInputException : public InvalidInputException {

public:

DuplicateInputException() { cerr << "Duplicate input!" << endl; }

};

class GameUI {

private:

map* world;

point initial_size;

point initial_head;

std::list initial_foods;

public:

GameUI() {

cout << "please input two positive integers indicates the map size!"

<< endl;

cin >> initial_size.x >> initial_size.y;

if (initial_size.x <= 5 || initial_size.y <= 5 || initial_size.x > 15 ||

initial_size.y > 15) {

cout << "invalid input" << endl;

throw InvalidInputException();

}

cout << "please input two positive integers(range(0, size_x-1), "

"range(0,size_y-1)) the initialize snake head position!"

<< endl;

cin >> initial_head.x >> initial_head.y;

if (initial_head.x >= initial_size.x || initial_head.x < 0 ||

initial_head.y >= initial_size.y || initial_head.y < 0) {

cout << "invalid input" << endl;

throw InvalidInputException();

}

int food_num;

cout << "please input how many food you will put and then input food "

"position which is different form each other"

<< endl;

cin >> food_num;

if (food_num <= 0) {

throw InvalidInputException();

}

while (food_num > 0) {

food_num--;

point temp;

cin >> temp.x >> temp.y;

if (temp.x >= 0 && temp.x < initial_size.x && temp.y >= 0 &&

temp.y < initial_size.y &&

std::find(initial_foods.begin(), initial_foods.end(), temp) ==

initial_foods.end() &&

!(temp.x == initial_head.x && temp.y == initial_head.y)) {

initial_foods.push_back(temp);

} else {

throw DuplicateInputException();

}

}

world = new map(initial_size, initial_head, initial_foods);

}

~GameUI() { delete world; }

void GameLoop() {

world->print();

bool exit = false;

while (true) {

char operation = getInput();

switch (operation) {

case 'w':

case 'W':

this->world->move(up);

break;

case 's':

case 'S':

this->world->move(down);

break;

case 'a':

case 'A':

this->world->move(left);

break;

case 'd':

case 'D':

this->world->move(right);

break;

case 'q':

case 'Q':

exit = true;

break;

default:

this->world->move(freeze);

}

world->print();

if (world->isGameOver()) {

cout << "Game Over!" << endl;

break;

}

if (exit) {

cout << "Bye!" << endl;

break;

}

}

}

char getInput() {

char temp;

cin >> temp;

return temp;

}

};

int main() { // 看,main函数只有这么短!!!!

GameUI greedySnake;

greedySnake.GameLoop();

return 0;

}

(事实上为了达到封装性,gameUI的类也应该分开来实现。)

5、小结

这个贪吃蛇还比较的低端,只能实现一键一步的行走方式,还没有像我的c语言贪吃蛇那样可以自己走,并且有AI模式。实现自己走要使用到windows的下的一个库,实现起来还比较麻烦,可以参考我的c贪吃蛇。用c++重写一遍贪吃蛇,主要作用是可以更加清楚地体会到类的封装与使用。

以后如果有时间,笔者可能会为这个贪吃蛇写下补丁什么的,体会一下c++的代码重用和方便修改的特性,这是c语言所没有的优点。

Enjoy coding! :)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

php 实现贪吃蛇游戏,C++实现简单贪吃蛇游戏相关推荐

  1. html与js简单小游戏,JS实现简单贪吃蛇小游戏

    本文实例为大家分享了JS实现简单贪吃蛇游戏的具体代码,供大家参考,具体内容如下 1.使用语言 HTML+CSS+JavaScript 2.使用工具 visual studio code 3.GitHu ...

  2. python猜数游戏流程_python简单猜数游戏实例

    本文实例讲述了python简单猜数游戏.分享给大家供大家参考.具体实现方法如下: #!/usr/bin/env python import random number = random.randint ...

  3. 目前大部分的游戏框架_简单的Windows游戏-第1部分:游戏框架

    目前大部分的游戏框架 我已决定使用C#和WinForms创建一个简单的Windows游戏,从而得出一系列见解. 还有其他方法可以完成此任务,但我选择了使事情保持简单并演示如何制作游戏的方法. 经验丰富 ...

  4. python纸牌游戏_python模拟简单的扑克牌游戏

    这个代码实现的是J来家游戏,规则是这样的: 两个玩家随机平分一副扑克牌中的纸牌,然后从最上面出牌,名牌摆出,如果玩家出的牌是J,则将已经落地的名牌全部收归自己,放到自己牌的最下方,再出一张牌:如果出的 ...

  5. 用python写个根据提示猜词语简单的游戏_python实现简单猜单词游戏

    本文实例为大家分享了python实现猜单词游戏的具体代码,供大家参考,具体内容如下 电脑根据单词列表随机生成一个单词,打印出这个单词长度个 ' _ ' ,玩家随机输入一个这个单词可能包含的英文字母,如 ...

  6. 指针游戏1 最简单的指针游戏

    这篇文章只是一个引子,为了下一篇文章的   "如何在子函数中改变指针的指向"  的问题做铺垫. 所以这些基本问题都不会解释多少,如果有问题的话欢迎留言. #include < ...

  7. C语言编写扫雷游戏,超简单

    C语言编写扫雷游戏,超简单 1.扫雷游戏的流程 2.代码编写 3.总结 通过学习C语言的基础知识,基本上是理解了大部分内容,现在就通过所学的知识,写个简单的扫雷游戏,加深对基础知识的理解,正所谓实践是 ...

  8. Python不能做游戏?一小时做出一个游戏!

    嗨喽-小伙伴们,我又来了, 写在前面的话: [ 一直都听他们说,python做不出好的游戏,个人是不赞同的,我只能说,python可以用来写游戏,但不适合. 举个最简单的例子,弹弓可以用来拔牙吗?当然 ...

  9. 怎样链接计算机一起玩游戏,怎么在投影上打游戏?电脑连接投影玩游戏教程 这样玩游戏才爽!...

    虽然现在很多人喜欢在手机上没事儿玩两把游戏,放松一下,但是真正要爽快的玩游戏,还是得在电脑显示器或者是电视机上大屏幕玩主机.PC游戏来的过瘾.毕竟不管是主机游戏还是PC游戏,其画质和游戏的精美程度都是 ...

最新文章

  1. MySQL主从库--同步异常
  2. RtlAdjustPrivilege 一行代码提升进程权限
  3. jQuery的load()方法
  4. zcmu1157: 新年彩灯Ⅱ(二维树状数组)
  5. C#将Json字符串反序列化成List对象类集合
  6. 实例带你掌握如何分解条件表达式
  7. 【10天基于STM32F401RET6智能锁项目实战第2天】用按键点灯----GPIO的输入和输出
  8. Linux平台安装Clion
  9. 实现“0”的突破:给一直没有对主机硬件进行过任何“保洁、养护”的网友“支两招”...
  10. 关于Unity中DOTween插件的使用(专题一)
  11. yeta机器人_Yeta智能语音电话机器人开放平台接入指南(2)
  12. c语言 停车管理系统
  13. gomarket服务器位置,第一章 昂达V711双核版常见问题解答.pdf
  14. 关于公布部分非法刊物的通知及冀职改办字[2006]48号
  15. H5组件Canvas画电子印章
  16. 当前比较流行的页面布局方式
  17. DHCP+DHCP中继
  18. openCV ROI
  19. 《操作系统》总结四(文件管理)
  20. vue中eslint报错的解决方案

热门文章

  1. 无法启动此程序因为计算机丢失dtlui,电脑缺少dll文件_电脑开机总是出来DLL文件丢失,...
  2. html代码style图片width,HTML Style columnWidth用法及代码示例
  3. 企业微信H5_网页jssdk调用 agentconfig选人选照片等案例演示
  4. linux7基础——给用户添加sudo权限
  5. Unexpected end of JSON input while parsing near '...解决方法
  6. 第13篇: Flowable-BPMN操作流程之流程进展查看之流程图
  7. MyBatis-Plus_AR 模式
  8. Docker 容器导出为镜像
  9. JavaScript-jQuery操作Dom元素
  10. 星外主机销售系统源码_业务员大客户销售订货订单管理系统源码开发外包解析...