简体   繁体   English

Javascript 输入密钥修复

[英]Javascript enter key fix

I made a code using javascript我使用 javascript 编写了一个代码
the code basically says: if enter is pressed take the user input from the input box代码基本上说:如果按下输入,则从输入框中获取用户输入
and check if it is right.并检查它是否正确。 (this is for a simple maths game) (这是一个简单的数学游戏)
I have a timer in place我有一个计时器
and after the timer is done the game ends计时器结束后游戏结束

the problem is when the user clicks play again问题是当用户再次点击播放
and uses the enter key并使用回车键
it presses it twice.它按了两次。

I don't know how to fix this problem我不知道如何解决这个问题

sample code is provided of the enter key function:提供了输入键 function 的示例代码:

onEvent("addition", "click", function() { //This is what happens when the user picks the addition mode of the game.
newGame("plus", "minus", "times"); //This is just a function I made to restart the score and time for the game
timer(); //A function to start the timer

onEvent("game", "keydown", function(event) { //This is where the main problem is.
  if((event.key === "Enter") && (seconds < 0)) { //This makes it so it will only work when enter is the key pressed.
//When the user clicks play again the script works, but enter is clicked twice while the user only clicks the keyboard once.
  z = getText("text_input1"); //<This is all the mathy bits you don't need to worry about the parts under this line
  console.log(z);
  x = a + b;
  console.log(x);
  if(z == x){
   setText("result", "Correct");
   setText("text_input1", "");
   changeNum();
   score++;
   setText("scoreT", score);
  } 
  if(z != x) {
    setText("text_input1", "");
    setText("result", "Incorrect");
    changeNum();
    if(score > 0) {
    score--;
    setText("scoreT", score);
  }
  }
  }
});
});

Just add a Flag:只需添加一个标志:

let NoGame = true;

/.../

onEvent("game", "keydown", function(event)
  {
  if ((event.key === "Enter") && NoGame)
    {
    NoGame = false;
/.../
   }

on Game ending: NoGame = true游戏结束时: NoGame = true

every time the user click center key,you have to check the game is started每次用户点击中心键,你必须检查游戏是否启动

when the game started,it should not be again start.游戏开始时,不应该重新开始。

below is sample code下面是示例代码

 let isStarted = false;
            function checkState(){
                if(isStarted === true){
                    return;
                }
                isStarted = true

                //todo something else
                //when the game is done , isStarted should be false
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM