我正在使用项目,商店等在控制台上进行基于文本的冒险。在C#中使用其他函数中定义的类变量
现在我想通过使用类来缩短购买剑的代码。我把古剑定义在一个单独的功能和代码随机化,你可以在其他买剑:
namespace Text_Adventure
{
class Game
{
//Weapon class
public class Weapon{
public string name;
public int damage;
public int magic;
public int durability;
public int price;
}
//the weapon showed in the shop
public class Weaponshop{
public string name;
public int damage;
public int magic;
public int durability;
public int price;
}
...
// defenition of swords
public void swords()
{
Weapon sword1 = new Weapon();
sword1.name = "Wooden Sword";
sword1.damage = 2;
sword1.magic = 1;
sword1.durability = 20;
sword1.price = 10;
Weapon sword2 = new Weapon();
sword2.name = "Iron Sword";
sword2.damage = 3;
sword2.magic = 2;
sword2.durability = 50;
sword2.price = 20;
...
}
//gamble sword that are shown in the shop
public void swordgamble()
{
Random shopgamble = new Random();
Weaponshop shopsword1 = new Weaponshop();
//gamble shopsword 1
int shopgamblenumber = shopgamble.Next(1, 8 + 1);
现在problemcode
---> if (shopgamblenumber == 1)
{
shopsword1 = sword1;
}
if (shopgamblenumber == 2)
{
shopsword1 = sword1;
}
<----
与shopsword2和shopsword3
发生同样的情况public void buysword
{
swordgamble();
Console.WriteLine("Shop");
Console.WriteLine();
Console.WriteLine("Which sword do you would like to have?");
Console.WriteLine();
while (correct == 0)
{
Console.WriteLine("1. " + shopsword1.name);
Console.WriteLine("2. " + shopsword2.name);
Console.WriteLine("3. " + shopsword3.name);
Console.WriteLine("4. None of these");
Console.WriteLine("");
...
}
我的程序无法读取我在剑中设置的变量并将其分配到商店word1
我的旧版本只有变量,而且因为这个相当大的时候我拿了8把剑可以买到。有谁知道如何读取我在剑中设置的变量并读取函数buysword()中的商店字词? ?
你已经初始化了这些变量,并把它们扔在了swords()void中。你必须将它们存储在某个地方 – 2017-10-13 08:40:42
如何将'Weapon'分配给'Weaponshop'类型的变量? –
--->是为了标记扇区 对不起,我是新的 – KillSwitch