p1x*_*xel 2 javascript if-statement
我正在用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(`...`);
Run Code Online (Sandbox Code Playgroud)
有没有办法将(炸弹>刀&&炸弹<手枪)等规则存储到某个东西中,然后将其传递给if/else进行比较?或者即使可能,我也不应该这样做?
您可以使用具有决策的对象作为树
decisions = {
bomb: {
bomb: function () { },
knife: function () { },
pistol: function () { }
}, knife: {
bomb: function () { },
knife: function () { },
pistol: function () { }
}, pistol: {
bomb: function () { },
knife: function () { },
pistol: function () { }
}
};
Run Code Online (Sandbox Code Playgroud)
访问通过
decisions[player][computer]()
Run Code Online (Sandbox Code Playgroud)