01 使用C++构建一个虚拟的目标游戏

使用C++构建一个虚拟的目标游戏

​ 下面是一个人物类,拥有基础属性和攻击,回血等操作,同时使用了加锁机制来保证线程安全。

Role.h

#pragma once
#include <mutex>
#include <thread>


class Role
{
private:
int unknow_1[4]; //unknow data
int hp[2]; //当前血量和最大血量
int tp[2];
int mp[2];
int act;
int def;
int sf;
int lv;
int unknow_2;
int exp[2];
int speed;
int unknown_3[4];
int x;
int y;
int unknow_4[36];
char Name[0x20];

private:
std::mutex mtx;
std::thread bloodAdd; //回血线程

public:
Role();
~Role();
void attacked(int damage); //攻击
void regenerateHealth(int health); //回血
bool isDead(); //判断死亡
void setDead(); //设置死亡

int getAtk(); //获取攻击力
public: //移动
int getX();
int getY();
void move(int _x, int _y);

public:
void initRole();
};


Role.cpp

​ 该文件中定义了TEST宏来输出回血提示,可以去掉。注意:回血操作专门开辟了一个线程去处理,因此需要加锁。

#include "Role.h"
#include <chrono>
#include <thread>

#define TEST

#ifdef TEST
#include <iostream>
#define xxx(sentence) \
do{sentence}while(0)
#else
#define xxx(sentence) \

#endif

Role::Role()
{
bloodAdd = std::thread([this]() {regenerateHealth(5); }); //使用lambda表达式
//bloodAdd = std::thread(&Role::regenerateHealth,this,5); //直接传入函数地址
initRole();
}

Role::~Role()
{
setDead();
xxx(std::cout << "The Role has been dead." << std::endl;);
bloodAdd.join();
}

void Role::attacked(int damage)
{
std::lock_guard<std::mutex> lock(mtx);
if (hp[0] - damage < 0)
hp[0] = 0;
else
hp[0] -= damage;
}

void Role::regenerateHealth(int health)
{
while (true)
{
// 做一些回血处理
{
if (isDead()) //死亡
break;
std::lock_guard<std::mutex> lock(mtx); //检测死亡后加锁,否则死锁
if (hp[0] != hp[1])
{
if (hp[0] + health > hp[1])
hp[0] = hp[1];
else
hp[0] += health;

}
xxx(std::cout << "blood regenerate health:" << hp[0] << std::endl;);
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}

bool Role::isDead()
{
std::lock_guard<std::mutex> lock(mtx);
return hp[0] == 0;
}

void Role::setDead()
{
std::lock_guard<std::mutex> lock(mtx);
hp[0] = 0;
}

int Role::getX()
{
return x;
}

int Role::getY()
{
return y;
}

void Role::move(int _x, int _y)
{
x = _x;
y = _y;
}

void Role::initRole()
{
hp[0] = hp[1] = 100;
act = 5;
def = 5;
speed = 10;
}

int Role::getAtk()
{
return act;
}

main.cpp

​ 在main中创建了两个人物,每隔一秒攻击一下对方。

#include <iostream>
#include <thread>
#include <chrono>
#include "Role.h"

int main()
{
Role r1;
Role r2;
while (true)
{
r1.attacked(r2.getAtk());
r2.attacked(r1.getAtk());
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}