php 实现贪吃蛇游戏,C++实现简单贪吃蛇游戏

我大概在一个多月前把自己上学期写的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! :)

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/530128.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java中的斜杠和反斜杠,老生常谈java路径中的反斜杠和斜杠的区别

JAVA中的斜杠有正斜杠与反斜杠之分&#xff0c;正斜杠&#xff0c;一般就叫做斜杠&#xff0c;符号为“/”&#xff1b;反斜杠的符号为“\”。斜杠(/)在JAVA中没有什么特别的意义&#xff0c;就是代表一个字符‘/;反斜杠(\)则不然&#xff0c;它和紧跟着它的那个字符构成转义字…

小程序 php cookie,微信小程序使用Cookie

微信小程序使用Cookie微信小程序不支持Cookie,因此,需要借助小程序的数据缓存来实现Cookie.环境: mpvue fly.js登录成功后,在处理登录验证的method里,加入以下内容保存Cookie:wx.setStorageSync("sessionid",response.headers["set-cookie"][0])我对fly.j…

php对象好用吗,在数据库中使用对象的好处_php

我们都知道如何从mysql获取我们需要的行(记录)&#xff0c;读取数据&#xff0c;然后存取一些改动。很明显也很直接&#xff0c;在这个过程背后也没有什么拐弯抹角的。然而对于我们使用面对对象的程序设计(OOP)来管理我们数据库中的数据时&#xff0c;这个过程就需要大大改进一…

linux apache php显示源码,linux 源码安装apache PHP 问题

sudo ./configure --prefix/var/php --with-apxs2/usr/local/apache2/bin/apxsLoadModule php5_module modules/libphp5.soDirectoryIndex index.html index.html.var .phpa-bash-3.2$ pwd/usr/local/apache2/htdocs-bash-3.2$ cat info.phpphpinfo();?>打开info.ph…

mysql临时表的的理解,如何理解存储过程中已存在的mysql临时表?

它在创建表时具有IF NOT EXISTS(13.1.17. CREATE TABLE Syntax)选项,在这种情况下可以使用.例&#xff1a;DELIMITER $$CREATE PROCEDURE temp_sp1()BEGINCREATE TEMPORARY TABLE IF NOT EXISTS temp_table (col2 int(11) DEFAULT NULL,col3 int(11) DEFAULT NULL);INSERT INTO…

python 发邮件 抄送,Python调用outlook发送邮件,发送给多人、抄送给多人并带上附件...

我的报告目录具体解释在代码中有详细注释import win32com.client as win32import datetime, osaddressee test01qq.com;test02jd.com#收件人邮箱列表cc test02163.com;test03alibaba.com#抄送人邮件列表mail_path os.path.join(rC:\Users\songlihui\PycharmProjects\test001…

php阻止输入sql,在PHP中全面阻止SQL注入式攻击之三

一、 建立一个安全抽象层我们并不建议你手工地把前面介绍的技术应用于每一个用户输入的实例中&#xff0c;而是强烈推荐你为此创建一个抽象层。一个简单的抽象是把你的校验方案加入到一个函数中&#xff0c;并且针对用户输入的每一项调用这个函数。当然&#xff0c;我们还可以创…

Oracle12081,【Oracle介质】Oracle 12C Linux x86-64 最新OPatch patch 6880880 12.2.0.1.7

天萃荷净Linux x86-64 补丁程序6880880: OPatch patch of version 12.2.0.1.7 for Oracle software releases 12.1.0.x (installer) and 12.2.0.x (AUG 2016)上次更新时间 2016-8-26 上午1:48 (8 天前)产品 Oracle Global Lifecycle Management OPatc…

如何使用oracle ebs,Oracle EBS进行集成的实际操作步骤

我们今天主要向大家介绍的是如何使用WebService和Oracle EBS进行集成&#xff0c;以及在使用WebService和Oracle EBS进行集成时&#xff0c;所需要的一些项目的描述&#xff0c;以下的文章就是对相关内容的描述。架构系统从总体上分为两部分&#xff0c;一部为企业的EBS及接口系…

linux nls_lang oracle,linux操作系统环境变量LANG和NLS_LANG的区别

例如&#xff1a;复制代码代码如下:export LANGzh_CN.GB2312export NLS_LANGAMERICAN_AMERICA.ZHS16GBK$export LANGzh_CN.GB2312$date2012年 11月 27日 星期二 16:20:35 CST显示是中文界面。复制代码代码如下:$export NLS_LANGAMERICAN_AMERICA.ZHS16GBK$sqlplus / as sysdbaS…

oracle监听 3个配置文件,Oracle 11g 监听 配置修改 说明

这里我们看2个比较常用的操作。1. 停止写listener log在某些特定的场合可能会有这样的需求。控制这个功能的参数是LOG_STATUS。 官网对这个参数的说明&#xff1a;To turn listenerlogging on or off.--在OS层面直接使用&#xff1a;lsnrctl SET LOG_STATUS {on | off}--在LSNR…

suse linux如何重置密码忘记,SUSE Linux忘记root密码的处理办法

GRUB修改法注意&#xff1a;此办法仅适用SLES8、SLES9&#xff0c;不适用于SLES10&#xff0c;SLES10请用光盘修改法。此办法不适合用于grub启动超时时间为0的机器&#xff0c;因为grub超时时间设置为0后&#xff0c;不能编辑grub选项&#xff0c;此类机器必须使用光盘或网络引…

linux怎么启动端口服务,Linux 根据端口快速停止服务并启动的办法

ll /proc/7167结果为:[rootcentos76 deploy]# ll /proc/7167total 0dr-xr-xr-x 2 root root 0 Jun 25 11:13 attr-rw-r--r-- 1 root root 0 Jun 25 11:13 autogroup-r-------- 1 root root 0 Jun 25 11:13 auxv-r--r--r-- 1 root root 0 Jun 25 11:05 cgroup--w------- 1 root …

linux进程增删改查,iptables的增删改查

iptables是自带的防火墙&#xff0c;功能强大&#xff0c;学习起来需要一段时间&#xff0c;下面是一些习iptables的时候的记录。如果iptables不熟悉的话可以用apf&#xff0c;是一款基于iptables的防火墙&#xff0c;挺好用的。一,安装并启动防火墙[root ~]# /etc/init.d/ipta…

重装系统 linux启动windows系统文件在哪里,Win-Lin双系统重装Windows找回Linux启动

第一系统Windows&#xff0c;第二系统Linux&#xff1a;Ubuntu18.10&#xff1b;1. 重新安装Windows系统后&#xff0c;使用Ubuntu的安装光盘&#xff0c;或启动U盘启动电脑&#xff1b;2. 选择&#xff1a;Try Ubuntu ;3. 进入Ubuntu界面&#xff0c;打开命令行终端(Ctrl Alt…

linux远程监控毕业设计,毕业设计论文:基于嵌入式Linux远程监控系统的设计与实现.doc...

摘 要可编程逻辑控制器(PLC)不仅在工业控制中应用越来越广泛&#xff0c;而且在其他领域的应用也逐渐扩大&#xff0c;例如&#xff1a;电力、化工、能源、水利等。由于它的功能比较强大、使用安全可靠、维护简单方便的优点&#xff0c;在很多地方已经取代了继电器电路的逻辑控…

linux卡死在选择内核界面,求助:am3352 linux内核启动时卡在 Starting kernel ...

这是用光盘里的uImage的输出信息&#xff1a;U-Boot# tftp 0x82000000 bakuImagelink up on port 0, speed 100, full duplexUsing cpsw deviceTFTP from server 192.168.0.231; our IP address is 192.168.0.224Filename bakuImage.Load address: 0x82000000Loading: ########…

u盘分为windows和linux启动,【电脑软件】Ventoy 官方版,一个U盘,同时拥有启动win+linux+Ubuntu...

软件介绍&#xff1a;Ventoy是一个制作可启动U盘的开源工具。有了Ventoy你就无需反复地格式化U盘&#xff0c;你只需要把ISO文件拷贝到U盘里面就可以启动了&#xff0c;无需其他操作。 你可以一次性拷贝很多个不同类型的ISO文件&#xff0c;在启动时Ventoy会显示一个菜单来选择…

linux cpu频率软件,linux cpu频率控制

安装cpufrequtils&#xff1a; sudo apt-get install cpufrequtils查看cpu&#xff1a; sudo cpufreq-info设置cpu模式&#xff1a; cpufreq-set -g {powersave, userspace, ondemand, conservative, performance}对应于{最省电(最低频率)&#xff0…

linux var 空间不足,/var空间不足怎么办?(求安全保险的方法)

最近想把Ubuntu从12.04升级到13.10&#xff0c;可/var目录下的空间不足&#xff0c;怎么处理这个问题&#xff1f;提示需要850M多的空间&#xff0c;可从以下的信息来看&#xff0c;里面的东西我几乎是没得删除了。# du -h --max-depth1 /var92K /var/crash4.0K /var/local4.0K…