将变量的值设置为另一个变量的值

问题描述 投票:0回答:2

我将举例说明我正在努力实现的目标。

使用twine2(我开始)我可以通过直接引用其他变量来编程设置和操作变量(我将为不熟悉twine的人解释一下语法)。

初始化并设置我的变量

  // data map is equivalent to dict
$Inv = (dm: potion, 0, bomb, 0, gold, 0);
  // array
$PossibleRewards =(a: potion, bomb, gold);
  // string
$Reward "";

然后

set $Reward to (shuffled... $PossibleReward's 1st);
set $Inv's $Reward to it +1;

所以它的作用就是简单地随机抽取PossibleRewards数组,选择第一个条目,然后将Reward字符串设置为所选内容,然后自动将Inv数据映射适当地增加一个。

当然你可以跳过字符串然后去

set $Inv's (shuffled... $PossibleReward's 1st to ot +1

我知道它可以完成,但需要一些语法帮助,任何输入都值得赞赏

unity3d syntax
2个回答
0
投票

如果PossibleRewards只是Dictionary.Keys值的副本,那么你可能不需要它。您可以使用Random类使用字典的ElementAt方法(返回KeyValuePair)来获取字典中的随机项,将Reward设置为该元素的Value,然后可以在字典中递增该元素的Value

Random rnd = new Random(); // Note: you typically only need one instance of Random in a class

// Create a dictionary of rewards and quantity
Dictionary<string, int> inventory = new Dictionary<string, int> 
    {{"potion", 0}, {"bomb", 0}, {"gold", 0}};

// Grab the Key of a random item in the dictionary for the reward
string reward = inventory.ElementAt(rnd.Next(inventory.Count)).Key;

// Increment the value at that Key
inventory[reward]++;

否则,如果需要列表(例如,如果Rewards是不同类的实例之间的共享列表),则可以基于列表初始化单个库存字典。最简单的方法是使用System.Linq扩展方法ToDictionary

private static readonly Random Random = new Random();
private static readonly List<string> Rewards = new List<string> {"potion", "bomb", "gold"};

private static void Main()
{
    // Initialize an inventory dictionary based on the shared list of rewards
    var inventory = Rewards.ToDictionary(key => key, value => 0);

    // Grab the Key of a random item in the dictionary for the reward
    var reward = inventory.ElementAt(Random.Next(inventory.Count)).Key;

    // Increment the value at that Key
    inventory[reward]++;
}

0
投票

这是一篇用C#填充数组的帖子:Best way to randomize an array with .NET。答案中有几个选项。

假设您的库存有Dictionary<string, int>(已经填充了所有可能的奖励),您可以简单地将其指定为inventory[possibleRewards[0]] += 1inventory[possibleRewards[0]]++

但是,我不会每次都对阵列进行洗牌。我会生成一个随机数,并使用它来选择数组中的索引,例如

var rand = new Random(); // do this once, e.g. in startup
// initialize possibleRewards array 

// in your reward method
var index = rand.Next(numberOfRewards);
inventory[possibleRewards[index]] += 1;

如果到目前为止Twine2是你唯一接触过编程的话,我建议你介绍一下C#教程。

© www.soinside.com 2019 - 2024. All rights reserved.