在Actionscript中,我试图找到一种方法来生成字符串和字符串变量,每次调出时都会吐出不同的文本。纯粹可视化:
var text:String "Red||Blue"; //Whenever the variable is called, it's either Red or Blue
textoutput("You spot a grey||black cat."); //A function equivalent of the same issue
我可以生成一个实现这种效果的函数,但据我所知,似乎变量不能是函数。
我已经考虑了数组变量,但我不知道如何在调用变量时使用数组吐出单个条目,而且我不知道如何使这个工作用于不是的字符串变量 - 假设我可以使用适用于这两种情况的单个系统。
修改
为了扩展蝙蝠侠答案中表达的问题,在变量上使用他的结果会产生一个“坚持”随机选择的结果。例如:
var shoes:String = grabRandomItem("Red shoes||Crimson shoes");
trace("You have " + shoes + ".") //Whichever result is chosen it stays that way.
此外,我可能想要将此变量更改为完全不随机的其他内容:
var secondshoes:String = "Blue shoes";
function newshoes():
{
shoes = secondshoes;
}
答案 0 :(得分:2)
您想要一个可能值列表中的随机值。而不是调用变量,您可以动态地引用它...
function random(low:Number=0, high:Number=1):Number {
/* Returns a random number between the low and high values given. */
return Math.floor(Math.random() * (1+high-low)) + low;
}
var options:Array = ["red", "blue", "grey", "black"];
trace("You spot a " + options[random(0, options.length-1)] + " cat.")
//You spot a black cat.
或者,您可以使用函数代替变量来删除内联逻辑...
function catColor():String { return options[random(0, options.length-1)]; }
trace("You found a " + catColor() + " key.")
// You found a red key.
或者将它概括为带参数的泛型函数。
var options:Object = {
"cat":["grey", "black"],
"key":["gold", "silver"],
"door":["blue", "red", "green"]
}
function get(item:String):String {
return options[item][random(0, options[item].length-1)];
}
trace("You found a " + get("door") + " door.")
// You found a green door.
答案 1 :(得分:1)
有很多方法可以做到这一点,但为了与你想要的方式保持一致,这是实现这一目标的最简单方法:
//populate your string: (remove the word private if using timeline code)
private var text_:String = "Red||Blue||Green||Yellow";
//create a getter to use a function like a property
function get text():String {
//create an array by splitting the text on instances of ||
var arr:Array = text_.split("||");
//return a random element of the array you just made
return arr[Math.floor(Math.random() * arr.length)];
}
trace(text);
更好的是,创建一个通用函数来解析你的字符串:
function grabRandomItem(str:String):String {
var arr:Array = str.split("||");
return arr[Math.floor(Math.random() * arr.length)];
}
//make a getter variable that regenerates everytime it's called.
function get label():String {
return "You spot a " + grabRandomItem("grey||black||blue||red||purple") + " cat";
}
trace(label); //anytime you access the label var, it will re-generate the randomized string
trace(label);
trace(label);
trace(label);
// ^^ should have different results
当然,这种方式我认为只有文本来自用户输入才有效。如果您正在将文本硬编码到应用程序中,您也可以直接在数组中创建它,如another answer you have中所示,因为这样的开销较少。