我正在用C++为我的编程类编写一个简单的项目。我正在制作一个简单的口袋妖怪战斗模拟器,在控制台上运行
然而,我遇到的问题是,存储口袋妖怪数据的最佳方法是什么?我必须将诸如HP、攻击、防御等东西存储在一个文件中,但我不确定如何才能最好地解决这个问题。我知道一些读写文件的基本知识,但没有什么能满足我所做的工作。我在考虑使用YAML,但在花了几个小时想弄清楚之后,我放弃了,因为我认为我不需要那么复杂的东西
我想我想要做的事情应该是
Open file
find string with name "pikachu"
find defense for pokemon pikachu
defense = pikachu defense
find HP for pokemon pikachu
HP = pikachu HP
find attack for pokemon pikachu
attack = pikachu attack那么,什么才是最好的方法,使用工具呢?
发布于 2014-05-05 21:30:07
您可以编写如下结构:
// A separate struct for stats allow you to add and remove
// stats parameters without touch pokemon struct.
struct stats
{
int hp;
int attack;
int defense;
};
typedef struct stats stats_t;
struct pokemon
{
string name;
stats_t stats;
// You can also add some behaviour to your pokemons.
void defend_from_attack(int incomming_attack)
{
// And for instance.
stats.defense -= incomming_attack;
}
void attack(pokemon attacked_pokemon)
{
attacked_pokemon.defend_from_attack(stats.attack);
}
// This is cool right?
void evolve(stats_t new_stats)
{
stats = new_stats;
}
}现在您所需要的只是一个读取文件(或文件)的函数,您可以在其中放置口袋妖怪的统计数据。如果你在使用YAML就更容易了。该函数必须读取文件并返回包含所需数据的pokemon实例。
下面的示例遵循您的假代码:
// Assume the YAML file has been open.
// find string with name "pikachu"
struct pokemon pikachu;
// find defense for pokemon pikachu
// defense = pikachu defense
pikachu.stats.defense = defense;
//find HP for pokemon pikachu
//HP = pikachu HP
pikachu.stats.hp = HP;
//find attack for pokemon pikachu
//attack = pikachu attack
pikachu.stats.attack = attack;实现该功能取决于您,我认为您必须已经知道了如何执行该功能。
发布于 2014-05-05 21:08:36
在运行时存储此数据的最佳方法是为pokemon创建一个类结构。这意味着您将有一个名为pokemon的类,它将具有各种属性,例如名称、hp和攻击。如果您希望通过多次执行保存此数据;您是正确的,则需要一些文件I/O。一旦有了类结构,就很容易使函数将口袋妖怪数据写入文件。如果您不熟悉面向对象,请查看此链接以获得更多信息。http://www.cplusplus.com/doc/tutorial/classes/
https://stackoverflow.com/questions/23481767
复制相似问题