我正在尝试构建一个简单的游戏,基于该游戏,玩家单击按钮的速度提高了100%。每个玩家都有一个分配给他们的按钮,具体取决于谁赢得玩家的点击速度更快。我想做出一个逻辑,即如果COUNT或COUNT_PLAYER2超过100,则玩家赢得一到两次,并且所有功能停止执行。您能帮我解释一下背后的逻辑吗?
let count = 0;
let maxCount = 50;
let player1_progress = document.getElementsByClassName("player1-progress__progressbar")[0];
console.log(player1_progress);
window.addEventListener("keypress", function(e) {
console.log(e.keyCode);
//if the button is "d"
if (e.keyCode === 100) {
console.log(count)
// increase count if it's less than 100
count = count === 100 ? 100 : count + 4;
//target progressbar width and increase it
let newWidth = (count / maxCount) * 50 + "%";
player1_progress.style.width = newWidth;
player1_progress.innerHTML = count + "%";
if (count === 100) {
console.log("player 1 is the winner!");
}
}
});
//player2 count
let count_player2 = 0;
let player2_progress = document.getElementsByClassName("player2-progress__progressbar")[0];
window.addEventListener("keypress", function(e) {
//if the button is "d"
if (e.keyCode === 47) {
// increase count if it's less than 100
count_player2 = count_player2 === 100 ? 100 : count_player2 + 4;
//target progressbar width and increase it
let newWidth_player2 = (count_player2 / maxCount) * 50 + "%";
player2_progress.style.width = newWidth_player2;
player2_progress.innerHTML = count + "%";
if (count_player2 === 100) {
console.log("player 2 is the winner!");
}
}
});
答案 0 :(得分:0)
当计数之一达到100时,您是否尝试删除所有事件侦听器?
类似这样的东西:
button_a_handler = e => {
// do stuff
if (count >= 100) {
window.removeEventListener("keypress", button_a_handler);
window.removeEventListener("keypress", button_b_handler);
}
};
button_b_handler = e => {
// do stuff
if (count >= 100) {
window.removeEventListener("keypress", button_a_handler);
window.removeEventListener("keypress", button_b_handler);
}
};