在创建对象时,我试图通过一系列函数调用来设置对象(Robolord)的'moniker‘属性。这是我的密码:
function RobolordCreator (moniker) {
this.moniker = moniker;
};
RobolordCreator.prototype.Attack = function (color) {
console.log(this.moniker + " fires a " + color + " laser for " + 2 + " damage!");
};
var Robolord = new RobolordCreator(MonikerGenerator());
function MonikerGenerator () {
function Chancey (percent) {
function rando (percent) {
percent = "." + percent;
return ((Math.random() <= percent) ? true : false);
};
if(rando(percent) == true){
RandomVowel();
} else {
RandomConsonant();
};
};
Chancey(50);
};
function RandomConsonant () {
var consonant = ["q", "w", "r", "t", "p", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"];
return consonant[(Math.floor(20 * Math.random()))];
};
function RandomVowel () {
var vowel = ["a", "e", "i", "o", "u", "y"];
return vowel[(Math.floor(6 * Math.random()))];
};
Robolord.Attack("green");现在,它正在打印“未定义的发射绿色激光造成2点伤害!”如何使RandomConsonant和RandomVowel函数在被调用到对象Robolord的'moniker‘属性时传递其结果?
发布于 2013-12-02 04:06:35
错过了几个return。
function MonikerGenerator () {
function Chancey (percent) {
function rando (percent) {
percent = "." + percent;
return ((Math.random() <= percent) ? true : false);
};
if(rando(percent) == true){
return RandomVowel(); //return Chancey result
} else {
return RandomConsonant(); //return Chancey result
};
};
return Chancey(50); //return Moniker to caller
}Demo
发布于 2013-12-02 04:24:03
如果要查找多个字符长的名称,则必须存储名称并向其添加字符。下面是代码的一个版本。
function Robolord(moniker) {
this.moniker = moniker
}
Robolord.prototype.attack = function (color) {
console.log(this.moniker + " fires a " + color + " laser for " + 2 + " damage!")
};
var robolord = new Robolord(generateName(8, 50))
function generateName(length, percent) {
var name = ''
for (var i = 0; i < length; i++) {
if (randomInt(1,100) > percent) {
name += randomVowel()
} else {
name += randomConsonant()
}
}
return name
}
function randomConsonant () {
var consonant = ["q", "w", "r", "t", "p", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"]
return consonant[(Math.floor(20 * Math.random()))]
}
function randomVowel () {
var vowel = ["a", "e", "i", "o", "u", "y"]
return vowel[(Math.floor(6 * Math.random()))]
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
robolord.attack("green");我为重命名了一些东西而道歉,我在玩它:)
函数generateName现在有一个长度,以及元音的百分之一(我认为这是最初的意图)。例如,这会生成8个字母长的名称,以及50%的元音。
我添加了一个名为randomInt的函数,它在一个范围内给出一个随机数--我使用一个函数来生成游戏中的名称/地形/ NPCs。
http://jsfiddle.net/ayvaV/
https://stackoverflow.com/questions/20320606
复制相似问题