我正在用 JavaScript 编写一个类似石头剪刀布的游戏。我让它以某种方式工作,但它更像是写出所有案例而不是让它进行比较。看起来像这样:
var weapons = ["bomb", "knife", "pistol"];
var player = prompt("Choose your weapon: bomb, knife or a pistol?");
console.log("You picked a " + player + ".");
var = weapons[Math.floor(Math.random() * weapons.length)];
console.log(" picked a " + + ".");
while (player == ) {
var player = prompt("You chose " + player + " and he chose " + +
" - the same weapon. Draw is not an option, so " +
"try again! Pick bomb, knife or pistol.");
console.log('...');
var = weapons[Math.floor(Math.random() * weapons.length)];
console.log(" picked a " + + ".")
}
if (player == "bomb" && == "knife")
console.log( `...`);
else if (player == "bomb" && == "pistol")
console.log(`...`);
else if (player == "knife" && == "pistol")
console.log('...');
else if (player == "knife" && == "bomb")
console.log(`...`);
else if (player == "pistol" && == "bomb")
console.log(`...`);
else if (player == "pistol" && == "knife")
console.log(`...`);
else
console.log(`...`);
有没有办法将 (bomb > knife && bomb < pistol) 之类的规则存储到某个东西中,然后将其传递给 if/else 进行比较?或者即使可能我也不应该这样做?
最佳答案
您可以将带有决策的对象用作树
decisions = {
bomb: {
bomb: function () { },
knife: function () { },
pistol: function () { }
}, knife: {
bomb: function () { },
knife: function () { },
pistol: function () { }
}, pistol: {
bomb: function () { },
knife: function () { },
pistol: function () { }
}
};
访问方式
decisions[player][computer]()
关于javascript - 我可以为以后可以在 JavaScript 中的 if/else 语句中进行比较的变量定义任意规则(比另一个更大的规则)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38179338/