我正在创建一个有两个玩家的游戏。这些球员是0,1
var activePlayer = [0,1]
取决于谁是活跃的,我想提供事件侦听器,该事件侦听器仅在播放器处于活跃状态时才激活每个播放器的控件。 我尝试以下方法,但是当然不能正常工作。
function controlGame(){
do{
document.querySelector('.btn-roll-0').addEventListener('click', play,);
document.querySelector('.btn-hold-0').addEventListener('click',hold);
}while(activePlayer === 0)
do{
document.querySelector('.btn-hold-1').addEventListener('click',hold);
document.querySelector('.btn-roll-1').addEventListener('click', play,);
}while(activePlayer === 1)
}
答案 0 :(得分:0)
忽略完成演示的脚手架代码,并查看事件侦听器。 我们只有在活跃玩家正确的情况下才激活。
// This is just for the demo ignore
const play = (player) => {
let newNum = Date.now();
setOut(`Role ${newNum} for Player ${player}`);
};
// This is just for the demo ignore
const hold = (player) => {
setOut(`hold for ${player}`);
};
// This is just for the demo ignore
const setOut = (msg) => {
document.querySelector('#out').innerText = msg;
};
let activePlayer = 0;
// Here we add event listeners that toggle based on active player.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('.btn-roll-0').addEventListener('click', (event) => {
if (activePlayer == 0) play(0);
});
document.querySelector('.btn-hold-0').addEventListener('click', (event) => {
if (activePlayer == 0) hold(0);
});
document.querySelector('.btn-roll-1').addEventListener('click', (event) => {
if (activePlayer == 1) play(1);
});
document.querySelector('.btn-hold-1').addEventListener('click', (event) => {
if (activePlayer == 1) hold(1);
});
document.querySelector('.btn-switch-plyr').addEventListener('click', (event) => {
activePlayer = (activePlayer == 0) ? 1 : 0;
});
});
<button class="btn-roll-0">Player 1 Roll</button>
<button class="btn-hold-0">Player 1 Hold</button>
<button class="btn-roll-1">Player 2 Roll</button>
<button class="btn-hold-1">Player 2 Hold</button>
<button class="btn-switch-plyr">Switch Player</button>
<div id="out">
<div>