(十一)C++自制植物大战僵尸游戏客户端更新实现

植物大战僵尸游戏开发教程专栏地址icon-default.png?t=N7T8http://t.csdnimg.cn/cFP3z


更新检查

游戏启动后会下载服务器中的版本号然后与本地版本号进行对比,如果本地版本号小于服务器版本号就会弹出更新提示。让用户选择是否更新客户端。

在弹出的更新对话框中有显示最新版本更新的内容,以及更新按钮等。用户可以选择更新方式或者进行更新。


文件位置 

代码文件实现位置在Class\Scenes\MainMenuScene文件夹中。 


UpdateClient.h 

客户端更新类继承与对话框类(Dialog),因为客户端更新也是一个对话对话框供玩家操作。UpdateClient头文件定义如下。

class UpdateClient :public Dialog
{
public:
    CREATE_FUNC(UpdateClient);

CC_CONSTRUCTOR_ACCESS:
    UpdateClient();
    virtual bool init();

private:
    enum class Update_Button
    {
        百度网盘下载,
        腾讯微云下载,
        直接下载,
		退出游戏,
        确定
    };
    void createDiglog();	                                                       /* 创建对话框 */
    void createButton(const std::string& name, Vec2& vec2, Update_Button button);  /* 创建按钮 */
    void showText();
    void addScrollView();
    void addMouseEvent();
    void downloadHistoryText();
    void downloadData();
    void downloadProgress();
    void downloadSuccess();
    void downloadError();

private:
    Sprite* _dialog;    /* 对话框 */
    std::unique_ptr<network::Downloader> _downloader;
    Label* _remindText;
    Label* _progressText;
    Label* _explanText;
    Label* _historyText;
    Sprite* _loadBarBackground;
    ui::LoadingBar* _loadingBar;
    ui::ScrollView* _textScrollView;
    bool _isNewDowndload;
};

UpdateClient.cpp

构造函数

在构造函数中对变量进行初始化操作。

UpdateClient::UpdateClient() :
	_dialog(nullptr)
	, _remindText(nullptr)
	, _progressText(nullptr)
	, _explanText(nullptr)
	, _loadBarBackground(nullptr)
	, _loadingBar(nullptr)
	, _historyText(nullptr)
	, _isNewDowndload(true)
{
	_downloader.reset(new network::Downloader());
}

init函数

创建游戏更新对话框,首先会调用init函数。在init函数中首先会在场景中创建一个黑色半透明的遮罩层,使用场景变黑,让玩家聚焦到此对话框中。然后调用createShieldLayer(this)函数屏蔽除本层之外的所以事件监听,该函数的实现在自定义对话框教程(教程九)中有介绍,作用是让玩家只能和该对话框进行交互。最后使用createDialog()函数创建更新菜单。

bool UpdateClient::init()
{
	if (!LayerColor::initWithColor(Color4B(0, 0, 0, 180)))return false;
	createShieldLayer(this);

	createDialog();
	return true;
}

createDialog()函数

在该函数中主要实现整个更新菜单的界面。

void UpdateClient::createDialog()
{
	_dialog = Sprite::createWithSpriteFrameName("LevelObjiectivesBg.png");
	_dialog->setPosition(_director->getWinSize() / 2);
	_dialog->setScale(0.9f);
	this->addChild(_dialog);

    /* 创建触摸监听 */
	createTouchtListener(_dialog);

	auto PauseAnimation = SkeletonAnimation::createWithData(_global->userInformation->getAnimationData().find("PauseAnimation")->second);
	PauseAnimation->setAnimation(0, "animation", true);
	PauseAnimation->setPosition(Vec2(530, 650));
	_dialog->addChild(PauseAnimation);

	showText();

	createButton(_global->userInformation->getGameText().find("百度网盘下载")->second, Vec2(165, 100), Update_Button::百度网盘下载);
	createButton(_global->userInformation->getGameText().find("腾讯微云下载")->second, Vec2(405, 100), Update_Button::腾讯微云下载);
	createButton(_global->userInformation->getGameText().find("直接下载")->second, Vec2(645, 100), Update_Button::直接下载);
	createButton(_global->userInformation->getGameText().find("关闭游戏")->second, Vec2(885, 100), Update_Button::退出游戏);
	createButton(_global->userInformation->getGameText().find("确定")->second, Vec2(520, 100), Update_Button::确定);

}

创建更新菜单背景,设置位置到屏幕中心,缩放0.9倍大小。 

_dialog = Sprite::createWithSpriteFrameName("LevelObjiectivesBg.png");
_dialog->setPosition(_director->getWinSize() / 2);
_dialog->setScale(0.9f);
this->addChild(_dialog);

对创建好的背景进行触摸监听,可以实现更新菜单的拖动。 

/* 创建触摸监听 */
createTouchtListener(_dialog);

 显示文字内容以及创建多个按钮。

showText();

createButton(_global->userInformation->getGameText().find("百度网盘下载")->second, Vec2(165, 100), Update_Button::百度网盘下载);
createButton(_global->userInformation->getGameText().find("腾讯微云下载")->second, Vec2(405, 100), Update_Button::腾讯微云下载);
createButton(_global->userInformation->getGameText().find("直接下载")->second, Vec2(645, 100), Update_Button::直接下载);
createButton(_global->userInformation->getGameText().find("关闭游戏")->second, Vec2(885, 100), Update_Button::退出游戏);
createButton(_global->userInformation->getGameText().find("确定")->second, Vec2(520, 100), Update_Button::确定);

downloadData()函数

客户端内文件下载更新函数。创建文件下载进度条以及文字信息。

void UpdateClient::downloadData()
{
	if (!_loadBarBackground)
	{
		_loadBarBackground = Sprite::createWithSpriteFrameName("bgFile.png");
		_loadBarBackground->setPosition(Vec2(_dialog->getContentSize().width / 2.f, _dialog->getContentSize().height / 2.f - 100));
		_loadBarBackground->setScale(1.5f);
		_dialog->addChild(_loadBarBackground);
	}

	if (!_loadingBar)
	{
		_loadingBar = ui::LoadingBar::create();
		_loadingBar->loadTexture("progressFile.png", TextureResType::PLIST);
		_loadingBar->setDirection(LoadingBar::Direction::LEFT); /* 设置加载方向 */
		_loadingBar->setPercent(0);
		_loadingBar->setScale(1.5f);
		_loadingBar->setPosition(Vec2(_dialog->getContentSize().width / 2.f, _dialog->getContentSize().height / 2.f - 100));
		_dialog->addChild(_loadingBar);
	}

	_explanText->setColor(Color3B::BLACK);
	_explanText->setString("");

	const static string sNameList = _global->userInformation->getGameText().find("资源名称")->second + UserInformation::getNewEditionName(true) + ".rar";
	const static string path = _global->userInformation->getGameText().find("存放路径")->second + sNameList;

	_downloader->createDownloadFileTask(_global->userInformation->getGameText().find("资源网址")->second, path, sNameList);
	
	downloadProgress();
	downloadSuccess();
	downloadError();
}

创建下载任务,传入服务器文件地址 、文件路径、文件名称。

_downloader->createDownloadFileTask(_global->userInformation->getGameText().find("资源网址")->second, path, sNameList);

调用下载进度、下载成功、下载失败函数 。下载过程会调用downloadProgress()函数,下载成功调用downloadSuccess()函数,下载失败调用downloadError()函数。

downloadProgress();
downloadSuccess();
downloadError();

downloadProgress()函数

onTaskProgress lamda函数中,会实时计算下载进度,bytesReceived参数是当前下载的文大小,totalBytesExpected是文件总大小,totalBytesReceived是总下载大小。通过这三个参数可以计算下载完成所需事件。

void UpdateClient::downloadProgress()
{
	_downloader->onTaskProgress = [=](const network::DownloadTask& task,
		int64_t bytesReceived,
		int64_t totalBytesReceived,
		int64_t totalBytesExpected)
	{
		_explanText->setString(_global->userInformation->getGameText().find("解释说明_慢")->second);

		float percent = float(totalBytesReceived * 100) / totalBytesExpected;
		_loadingBar->setPercent(percent);

		int hour = (totalBytesExpected - totalBytesReceived) / (bytesReceived * 10) / 3600;
		int min = ((totalBytesExpected - totalBytesReceived) / (bytesReceived * 10) - hour * 3600) / 60;
		int second = (totalBytesExpected - totalBytesReceived) / (bytesReceived * 10) - hour * 3600 - min * 60;

		char buf[128];
		if (bytesReceived / 1024.f * 10 >= 1000)
		{
			std::snprintf(buf, 128, "%.1fMB/s  %dKB/%dKB  %.2f%%  time:%02d:%02d:%02d",
					bytesReceived / 1024.f / 1024.f * 10, int(totalBytesReceived / 1024), int(totalBytesExpected / 1024), percent, hour, min, second);
			_progressText->setString(buf);
		}
		else
		{
			std::snprintf(buf, 128, "%.1fKB/s  %dKB/%dKB  %.2f%%  time:%02d:%02d:%02d",
					bytesReceived / 1024.f * 10, int(totalBytesReceived / 1024), int(totalBytesExpected / 1024), percent, hour, min, second);
			_progressText->setString(buf);
		}

		_remindText->setString(_global->userInformation->getGameText().find("文件正在下载中!请稍等!")->second);
    };
}

downloadSuccess()函数

成功下载文件后会调用onFileTaskSuccess lamda函数。在函数中显示下载成功文字信息,将按钮隐藏,然后提示用户退出重新启动游戏。

void UpdateClient::downloadSuccess()
{
	_downloader->onFileTaskSuccess = [this](const cocos2d::network::DownloadTask& task)
	{
		_progressText->setString(_global->userInformation->getGameText().find("下载成功")->second +
			_global->userInformation->getGameText().find("存放路径")->second + task.identifier + " ]");
		_remindText->setString(_global->userInformation->getGameText().find("点击确定退出游戏!")->second);
		_explanText->setString(_global->userInformation->getGameText().find("下载成功说明")->second);

		((Button*)_dialog->getChildByName("0"))->setVisible(false);
		((Button*)_dialog->getChildByName("1"))->setVisible(false);
		((Button*)_dialog->getChildByName("2"))->setVisible(false);
		((Button*)_dialog->getChildByName("3"))->setVisible(false);
		((Button*)_dialog->getChildByName("4"))->setVisible(true);
	};
}

downloadError()函数

如果下载失败,会调用onTaskError lamda函数,在函数中先错误信息提示用户。errorCode的是错误代码,errorStr是错误信息,errorCodeInternal是内部错误代码。

void UpdateClient::downloadError()
{
	_downloader->onTaskError = [this](const cocos2d::network::DownloadTask& task,
		int errorCode,
		int errorCodeInternal,
		const std::string& errorStr)
	{
		_remindText->setString(_global->userInformation->getGameText().find("下载失败")->second);
		((Button*)_dialog->getChildByName("2"))->setEnabled(true);
		((Button*)_dialog->getChildByName("3"))->setEnabled(true);

		char str[256];
		snprintf(str, 256, "Failed to download : 资源文件, identifier(%s) error code(%d), internal error code(%d) desc(%s) 请检查网络连接是否正常!如果网络连接正常请多试几次!或更换其他方式下载!"
			, task.identifier.c_str()
			, errorCode
			, errorCodeInternal
			, errorStr.c_str());
		_explanText->setString(str);
		_explanText->setColor(Color3B::RED);
#ifdef DEBUG
		log("Failed to download : %s, identifier(%s) error code(%d), internal error code(%d) desc(%s)"
			, task.requestURL.c_str()
			, task.identifier.c_str()
			, errorCode
			, errorCodeInternal
			, errorStr.c_str());
#endif // DEBUG
    };
}

其他函数

showText()、createButton()、addScrollView()、addMouseEvent()等函数不再一一列举,可自行查看。

void UpdateClient::showText()
{
	addScrollView();
	_historyText = Label::createWithTTF(_global->userInformation->getGameText().find("更新信息加载中!")->second, GAME_FONT_NAME_1, 50);
	_historyText->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP);
	_historyText->setColor(Color3B::BLACK);
	_historyText->setMaxLineWidth(650); 
	_textScrollView->addChild(_historyText);
	_textScrollView->setInnerContainerSize(_historyText->getContentSize());
	_historyText->setPosition(Vec2(_dialog->getContentSize().width / 2.f - 150, _textScrollView->getInnerContainerSize().height - 150));
	downloadHistoryText();

	/* 标题 */
	_remindText = Label::createWithTTF(_global->userInformation->getGameText().find("检测到有新版本,请选择更新方式!")->second, GAME_FONT_NAME_1, 50);
	_remindText->setPosition(Vec2(_dialog->getContentSize().width / 2.f, _dialog->getContentSize().height / 2.f + 200));
	_remindText->setColor(Color3B::BLACK);
	_remindText->setMaxLineWidth(900);
	_remindText->setName("Update");
	_dialog->addChild(_remindText);

	/* 进度文字 */
	_progressText = Label::createWithTTF("", GAME_FONT_NAME_1, 25);
	_progressText->setMaxLineWidth(900);
	_progressText->setPosition(Vec2(_dialog->getContentSize().width / 2.f, _dialog->getContentSize().height / 2.f));
	_dialog->addChild(_progressText);

	/* 说明文字 */
    _explanText = Label::createWithTTF("", GAME_FONT_NAME_1, 30);
	_explanText->setPosition(Vec2(_dialog->getContentSize().width / 2.f, _dialog->getContentSize().height / 2.f + 100));
	_explanText->setColor(Color3B::BLACK);
	_explanText->setMaxLineWidth(900);
	_dialog->addChild(_explanText);
}

void UpdateClient::addScrollView()
{
	_textScrollView = ui::ScrollView::create();
	_textScrollView->setDirection(ui::ScrollView::Direction::VERTICAL);
	_textScrollView->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
	_textScrollView->setContentSize(Size(720.0f, 320.0f));
	_textScrollView->setPosition(_dialog->getContentSize() / 2.0f);
	_textScrollView->setBounceEnabled(true);
	_textScrollView->setScrollBarPositionFromCorner(Vec2(20, 0));
	_textScrollView->setScrollBarWidth(10);
	_textScrollView->setScrollBarColor(Color3B::BLACK);
	_dialog->addChild(_textScrollView);
	addMouseEvent();
}

void UpdateClient::addMouseEvent()
{
	/* 鼠标滑动监听 */
	auto mouse = EventListenerMouse::create();
	mouse->onMouseScroll = [=](Event* event)
	{
		auto mouseEvent = static_cast<EventMouse*>(event);
		float movex = mouseEvent->getScrollY() * 5;

		auto minOffset = 0.f;
		auto maxOffset = 100.f;

		auto offset = _textScrollView->getScrolledPercentVertical();
		offset += movex;

		if (offset < minOffset)
		{
			offset = minOffset;
		}
		else if (offset > maxOffset)
		{
			offset = maxOffset;
		}
		_textScrollView->scrollToPercentVertical(offset, 0.5f, true);
	};
	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(mouse, _textScrollView);
}

void UpdateClient::downloadHistoryText()
{
	const string sURLList = _global->userInformation->getGameText().find("更新信息网址")->second;
	_downloader->createDownloadDataTask(sURLList);
	_downloader->onDataTaskSuccess = [this](const cocos2d::network::DownloadTask& task,
		std::vector<unsigned char>& data)
	{
		string historyNetWork;
		for (auto p : data)
		{
			historyNetWork += p;
		}

		TTFConfig ttfConfig(GAME_FONT_NAME_1, 25, GlyphCollection::DYNAMIC);
		_historyText->setTTFConfig(ttfConfig);
		_historyText->setString(historyNetWork);
		_textScrollView->setInnerContainerSize(_historyText->getContentSize());
		_historyText->setPosition(Vec2(350, _textScrollView->getInnerContainerSize().height));
	};
	_downloader->onTaskError = [this](const cocos2d::network::DownloadTask& task,
		int errorCode,
		int errorCodeInternal,
		const std::string& errorStr)
	{
		_historyText->setString(_global->userInformation->getGameText().find("更新信息加载失败!")->second);
		_textScrollView->setInnerContainerSize(_historyText->getContentSize());
	};
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

React-hooks:useRef

useRef文档 useRef 是一个ReactHook&#xff0c;它能帮助引用一个不需要渲染的值。 const ref useRef(initialValue)参数 initialValue&#xff1a;ref对象的 current 属性的初始值&#xff0c;可以是任意类型的值&#xff0c;这个参数在首次渲染后被忽略。 返回值 useRe…

Day99:云上攻防-云原生篇K8s安全实战场景攻击Pod污点Taint横向移动容器逃逸

目录 云原生-K8s安全-横向移动-污点Taint 云原生-K8s安全-Kubernetes实战场景 知识点&#xff1a; 1、云原生-K8s安全-横向移动-污点Taint 2、云原生-K8s安全-Kubernetes实战场景 云原生-K8s安全-横向移动-污点Taint 如何判断实战中能否利用污点Taint&#xff1f; 设置污点…

Java中的装箱和拆箱

本文先讲述装箱和拆箱最基本的东西&#xff0c;再来看一下面试笔试中经常遇到的与装箱、拆箱相关的问题。 目录&#xff1a; 装箱和拆箱概念 装箱和拆箱是如何实现的 面试中相关的问题 装箱和拆箱概念 Java为每种基本数据类型都提供了对应的包装器类型&#xff0c;至于为…

Xshell无法输入命令输入命令卡顿

Xshell是一款功能强大的终端模拟软件&#xff0c;可以让用户通过SSH、Telnet、Rlogin、SFTP等协议远程连接到Linux、Unix、Windows等服务器。然而&#xff0c;在使用Xshell的过程中&#xff0c;我们可能会遇到一些问题。比如输入不了命令&#xff0c;或者输入命令很卡。这些问题…

React-Redux(二)

​&#x1f308;个人主页&#xff1a;前端青山 &#x1f525;系列专栏&#xff1a;React篇 &#x1f516;人终将被年少不可得之物困其一生 依旧青山,本期给大家带来React篇专栏内容:React-Redux&#xff08;二&#xff09; 目录 react-redux 模块化 redux-thunk react-redu…

【pyhon】while语句的题目

1.计算1至100的偶数之和 sum_even 0 # 初始化偶数之和为0 i 1 # 从1开始循环 while i < 100: # 当i小于或等于100时&#xff0c;继续循环 if i % 2 0: # 如果i是偶数 sum_even i # 将i加到偶数之和上 i 1 # i自增1 print(“1至100的偶数之和为:”, sum_even) 给出乘…

SpringBoot源码解析-02

5. 模板引擎 由于 SpringBoot 使用了嵌入式 Servlet 容器 (tomca)。所以 JSP 默认是不能使用的。如果需要服务端页面渲染&#xff0c;优先考虑使用 模板引擎。 模板引擎页面默认放在 src/main/resources/templates SpringBoot 包含以下模板引擎的自动配置 FreeMarkerGroov…

Java NIO,高效操作I/O流的必备技能

Java IO在工作中其实不常用到&#xff0c;更别提NIO了。但NIO却是高效操作I/O流的必备技能&#xff0c;如顶级开源项目Kafka、Netty、RocketMQ等都采用了NIO技术&#xff0c;NIO也是大多数面试官必考的体系知识。虽然骨头有点难啃&#xff0c;但还是要慢慢消耗知识、学以致用哈…

设计模式:观察者模式(Observer)

设计模式&#xff1a;观察者模式&#xff08;Observer&#xff09; 设计模式&#xff1a;观察者模式&#xff08;Observer&#xff09;模式动机模式定义模式结构时序图模式实现观察者模式在单线程环境下的测试观察者模式在多线程环境下的测试多线程下的观察者模式模式分析优缺点…

计算机不联网是否有IP地址

计算机不联网是否会有IP地址&#xff0c;这个问题涉及到计算机网络的基础知识。要深入探讨这个问题&#xff0c;我们需要从IP地址的定义、作用&#xff0c;以及计算机在不联网状态下的网络配置等多个方面进行分析。 首先&#xff0c;IP地址&#xff08;Internet Protocol Addre…

HCIA--综合实验(超详细)

要求&#xff1a; 1. 使用172.16.0.0/16划分网络 2.使用ospf协议合理规划区域保证更新安全 3.加快收敛速度 4. r1为DR没有BDR 5.PC2&#xff0c;3&#xff0c;4&#xff0c;5自动获取IP地址&#xff1b;PC1为外网&#xff0c;PC要求可用互相访问 6.r7为运营商&#xff0c;只能配…

Oracle 正则,开窗,行列转换

1.开窗函数 基本上在查询结果上添加窗口列 1.1 聚合函数开窗 基本格式: ..... 函数() over([partition by 分组列,...][order by 排序列 desc|asc][定位框架]) 1&#xff0c;partition by 字段 相当于group by 字段 起到分组作用2&#xff0c;order by 字段 即根据某个字段…

Java实现优先级队列(堆)

前言 在学习完二叉树的相关知识后&#xff0c;我们对数据结构有了更多的认识&#xff0c;本文将介绍到优先级队列(堆&#xff09; 1.优先级队列 1.1概念 前面介绍过队列&#xff0c;队列是一种先进先出(FIFO)的数据结构&#xff0c;但有些情况下&#xff0c;操作的数据可能…

万兆以太网MAC设计(1)10G PCS PMA IP核使用

文章目录 一、设计框图二、模块设计三、IP核配置四、上板验证五、总结 一、设计框图 关于GT高速接口的设计一贯作风&#xff0c;万兆以太网同样如此&#xff0c;只不过这里将复位逻辑和时钟逻辑放到了同一个文件ten_gig_eth_pcs_pma_0_shared_clock_and_reset当中。如果是从第…

将图片按灰度转换成字符

from struct import *ch [., :, !, ~, ,, ^, *,$, #] ch.reverse()def calc(R, G, B):#模式Lreturn R * 299 // 1000 G * 587 // 1000 B * 144 / 1000def character( val):num val / 260 * len(ch)num round(num)if num>len(ch):numlen(ch)-1return ch[num]class rmb:d…

浅谈Spring的Bean生命周期

在Spring框架中&#xff0c;Bean&#xff08;即Java对象&#xff09;的生命周期涵盖了从创建到销毁的全过程&#xff0c;主要包含以下几个阶段&#xff1a; 实例化&#xff08;Instantiation&#xff09;&#xff1a; 当Spring IoC容器需要创建一个Bean时&#xff0c;首先会通过…

【安全设备】Hfish如何测试

部署好了蜜罐如何测试&#xff1f; 1、查找节点 2、节点的端口 3、将部署的主机和节点联系在一起 http访问。 就可以测试了。

Win10系统VScode远程连接VirtualBox安装的Ubuntu20.04.5

1.打开虚拟机&#xff0c;在中端中输入命令: sudo apt-get install openssh-server 安装ssh 我这里已经安装完成&#xff0c;故显示是这样 2.输入命令&#xff1a;sudo systemctl start ssh 启动远程连接 注意&#xff0c;如果使用VirtualBox安装的虚拟机&#xff0c;需要启用…

Git分布式版本控制系统——在IDEA中使用Git(一)

一、在IDEA中配置Git 本质上还是使用的本地安装的Git软件&#xff0c;所以需要在IDEA中配置Git 打开IDEA的设置页面&#xff0c;按照下图操作 二、在IDEA中使用Git获取仓库 1、本地初始化仓库 2、从远程仓库克隆 方法一&#xff1a; 方法二&#xff1a; 三、.gitignore文件…

测绘管理与法律法规 | 测绘资质分类分级标准 | 学习笔记

目录 1. 申请条件 2.审批程序 3.专业技术人员的特殊规定 1. 申请条件 法人资格&#xff1a;申请单位必须具有法人资格。 专业技术人员&#xff1a;需拥有与测绘活动相适应的测绘专业技术人员和相关专业技术人员。 技术装备&#xff1a;具备与测绘活动相适应的技术装备和设…
最新文章