我正在制作基于文本的RPG,您可以在每个屏幕上说是或否,并且我需要帮助来删除事件监听器

时间:2019-04-18 15:34:00

标签: javascript window removeeventlistener

因此,我有一个功能可以检查您是否按了'n'或'y',当您按'n'时,一个数字会攻击您,应该删除事件侦听器,然后给您机会赢得战斗,但在此之前有一个屏幕,显示按任意键继续,但该屏幕不显示。帮助吗?

我已经研究了一段时间了,它只是行不通,不会删除事件监听器。

这是命名角色和内容后的开始屏幕代码

document.body.innerHTML = "<h4>As you are walking to the bar at a pub, a dark, hooded figure, pulls you aside to a corner: 'Listen, I have a job for you...'</h4><h2>Press 'Y' to accept, and 'N' to turn back to the bar</h2><img id='hoodedFigure' src='https://render.fineartamerica.com/images/rendered/default/print/6.125/8.000/break/images-medium/the-hooded-figure-kayleigh-semeniuk.jpg'>";

//然后添加事件监听器:

var event1 = window.addEventListener("keydown", checkKeyPressed, false);

//这是它调用的函数:

        {if (evt.keyCode == "89") {
        changeContentOnPressY(1);
    } if (evt.keyCode == "78") {
changeContentOnPressN(1);
    }}}```

//Then it calls this function to change the screen:

```function changeContentOnPressN(num) {
        if (num == 1) {
    window.removeEventListener("keydown", checkKeyPressed, false);
    document.body.innerHTML = "The strange figure draws his weapons and agresses on you. You draw your small blade, and attempt to slash his stomach.<h3 style='text-align:center;'>Press any key to continue...</h3>";
            window.addEventListener("keydown", chance(1), false);
        } if(num == 2) {
window.addEventListener("keydown", checkKeyPressed2, false);
document.body.innerHTML = ""; // for 2nd n path}}```

//This is the part that is not working:

```window.removeEventListener("keydown", checkKeyPressed, false);```

This is the chance() function:

```function chance(num) {
    if (num == 1) {
        var chance = Math.random(0.1, 1);
 if (chance >= 0.80) {
 document.body.innerHTML = "Suddenly a swaggering figure walks towards you he says intrduces himself as Jean-Jacques le Tourment des Ombres, Grand Connoisseur of the Ombres House, he says 'You made the right choice, he was not to be trusted. I too dont like the Sabbath Family. Together we can get revenge'. Press Y to accept and N top refuse";
 } else {
 document.body.innerHTML = "He quickly slits your right wrist, and collects the blood spilled in a barrel. Soon nobles will enjoy this aged red. <br> <h1 style='text-align:center;'>GAME OVER<h1><br><h3 style='text-align:center;'>Press any key to continue...</h3>";
 window.addEventListener("keydown", startGame1, false);}}}}```

1 个答案:

答案 0 :(得分:0)

您的问题中发生了很多事情,我将重点介绍我认为是跳过的屏幕。据我所知,它应该删除事件监听器。

在您的代码中,您具有该段,应该等待玩家按下任意键。

window.addEventListener("keydown", chance(1), false);

问题是您立即调用“机会”功能,而不是等待。

如果您希望能够再次解除绑定该功能,则拥有

function waitForChance() {
    chance(1)
}

window.addEventListener("keydown", waitForChance, false);

然后您可以稍后与

解除绑定
window.removeEventListener("keydown", waitForChance, false);

顺便说一句,如果我是您,我可能会尽量避免取消绑定和重新绑定事件侦听器,因为它容易出错(并且很难阅读)。我可能会创建一个像这样的状态系统,在其中创建对象并在它们之间切换。我认为可以更清楚地了解哪些功能属于哪个状态。

// every state has 2 properties text and options
// text is what is displayed on the screen
// options contain the functions that are executed when the user presses a key
// if you want to bind a specific just bind enter that key in lower case
// if you want to accept any key add a function on anyKey 

//---------------- STATES --------------------------
let startState = {
  text: `<h4>As you are walking to the bar at a pub, a dark, hooded figure, pulls you aside to a corner: 'Listen, I have a job for you...'</h4><h2>Press 'Y' to accept, and 'N' to turn back to the bar</h2><img id='hoodedFigure' src='https://render.fineartamerica.com/images/rendered/default/print/6.125/8.000/break/images-medium/the-hooded-figure-kayleigh-semeniuk.jpg'>`,
  options: {
    y: function() {
      loadState(takeDealState)
    },
    n: function() {
      loadState(ambushState)
    }
  }
}

let takeDealState = {
  text: `What ever happend when you take the deal  (for now i reload the game on anykey)`,
  options: {
    /*Your options when you take the deal for now I just reset the game*/
    anyKey: function() {
      loadState(startState)
    }
  }
}

let ambushState = {
  text: `The strange figure draws his weapons and agresses on you. You draw your small blade, and attempt to slash his stomach.<h3 style='text-align:center;'>Press any key to continue...</h3>`,
  options: {
    anyKey: function() {
      var chance = Math.random(0.1, 1)
       if (chance >= 0.80) {
        loadState(successfullAmbush)
       } else {
        loadState(failedAmbush)
       }
    }
  }
}

let successfullAmbush = {
  text: `Suddenly a swaggering figure walks towards you he says intrduces himself as Jean-Jacques le Tourment des Ombres, Grand Connoisseur of the Ombres House, he says 'You made the right choice, he was not to be trusted. I too dont like the Sabbath Family. Together we can get revenge'. Press Y to accept and N top refuse`,
  options: {
    y: function() {
      console.log("accept")
    },
    n: function() {
      console.log("decline")
    }
  }
}

let failedAmbush = {
  text: `He quickly slits your right wrist, and collects the blood spilled in a barrel. Soon nobles will enjoy this aged red. <br> <h1 style='text-align:center;'>GAME OVER<h1><br><h3 style='text-align:center;'>Press any key to continue...</h3>`,
  options: {
    anyKey: function() {
      loadState(startState)
    }
  }
}

///---------------- LOGIC show and handle keypresses ---------------------------------- 
let currentState;

function loadState(state) {
  // set the state as the current state, so it can 
  currentState = state;
  // let the state descibe the scene
  document.body.innerHTML = state.text;
}

function keyHandler(event) {
  if(currentState.options.anyKey) {
    // handle anykey
    currentState.options.anyKey(event.key)
  } else if(currentState.options[event.key]) {
    // handle other key presses such as y/n
    currentState.options[event.key](event.key)
  }
}

window.addEventListener("keypress", keyHandler, true)

// start the game
loadState(startState)