C++格斗游戏效果视频
1.案例简介
#include "broadSword.h"
//构造函数
BroadSword::BroadSword()
{
FileManager fm;
map<string, map<string, string>> mWeapon;
fm.loadCSVData("Weapons.csv", mWeapon);
//武器id
string id = mWeapon["2"]["weaponId"];
//武器名称
this->weaponName = mWeapon[id]["weaponName"];
//武器攻击力
this->baseDamage = atoi(mWeapon[id]["weaponAtk"].c_str());
//武器暴击系数
this->critPlus = atoi(mWeapon[id]["weaponCritPlus"].c_str());
//武器暴击率
this->critRate = atoi(mWeapon[id]["weaponCritRate"].c_str());
//武器吸血系数
this->suckPlus = atoi(mWeapon[id]["weaponSuckPlus"].c_str());
//武器吸血率
this->suckRate = atoi(mWeapon[id]["weaponSuckRate"].c_str());
//武器冰冻率
this->frozenRate = atoi(mWeapon[id]["weaponFrozenRate"].c_str());
}
//获取基础伤害
int BroadSword::getBaseDamage()
{
return this->baseDamage;
}
//暴击效果 返回值大于0 触发暴击 否则不触发
int BroadSword::getCrit()
{
if (isTrigger(this->critRate))
{
return this->baseDamage * this->critPlus;
}
else
{
return 0;
}
}
//吸血效果 返回值大于0 触发吸血 否则不触发
int BroadSword::getSuckBlood()
{
if (isTrigger(this->suckRate))
{
return this->baseDamage * this->suckPlus;
}
else
{
return 0;
}
}
//冰冻效果 返回true代表触发 否则不触发
bool BroadSword::getFrozen()
{
if (isTrigger(this->frozenRate))
{
return true;
}
else
{
return false;
}
}
//触发概率的算法
bool BroadSword::isTrigger(int rate)
{
int num = rand() % 100 + 1; // 1 ~ 100
if (num <= rate)
{
return true;
}
return false;
}
2.CSV文件制作
3.解析单行CSV数据
#include "fileManager.h"
//加载CSV格式文件
void FileManager::loadCSVData(string path, map<string, map<string, string>>& mData)
{
//读文件
ifstream ifs(path);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
//第一个数据
string firstLine;
ifs >> firstLine;
//cout << "第一行数据为: " << firstLine << endl;
//heroId,heroName,heroHp,heroAtk,heroDef,heroInfo
vector<string>vFirst; //第一行解析后数据放入的容器
this->parseLineToVector(firstLine, vFirst);
//测试
/*for (vector<string>::iterator it = vFirst.begin(); it != vFirst.end(); it++)
{
cout << *it << endl;
}*/
string otherLine;
while (ifs >> otherLine)
{
//cout << "otherLine = " << otherLine << endl;
vector<string>vOther;
this->parseLineToVector(otherLine, vOther);
map<string, string>m;
for (int i = 0; i < vFirst.size(); i++)
{
m.insert(make_pair(vFirst[i], vOther[i]));
}
//将小map容器插入到大map容器中
mData.insert(make_pair(vOther[0], m));
}
//cout << "第一个英雄姓名: " << mData["1"]["heroName"] << endl;
//cout << "第二个英雄血量: " << mData["2"]["heroHp"] << endl;
//cout << "第三个英雄攻击力: " << mData["3"]["heroAtk"] << endl;
}
//解析单行数据到vector容器中
void FileManager::parseLineToVector(string line, vector<string>& v)
{
int pos = -1;
int start = 0;
while (true)
{
pos = (int)line.find(",", start);
if (pos == -1)
{
//最后一个单词处理
string temp = line.substr(start);
v.push_back(temp);
break;
}
string temp = line.substr(start, pos - start);
v.push_back(temp);
start = pos + 1;
}
}