I want to disable keystrokes in game over using JavaScript.

Asked 2 years ago, Updated 2 years ago, 49 views

This is my first time posting.

We develop simple games with JavaScript.
The challenge now is to disable the key when the player hits the enemy so that it cannot be operated.
Currently, even if the player hits the enemy, only the game over text is displayed, and if you press the key, you can use it again.

When I looked it up, I got information that if a player hits an enemy, I could return return false, but they didn't return return false, so the key operation was enabled.

return false was written in the event handler.

addEventListener("keydown", function(event){
  if(event.key=="ArrowUp"){
    sy-=62.5;
    if(sy<0){
      sy = 32.5;
    }
  } else if(event.key=="ArrowDown"){
    sy+=62.5;
    if(sy>500){
      sy = 467.5;
    }
  } else if(event.key=="ArrowLeft"){
    sx-=62.5;
    if(sx<0){
      sx = 32.5;
    }
  } else if(event.key=="ArrowRight"){
    sx+=62.5;
    if(sx>500){
      sx = 467.5;
    }
  }
  if(sx==ex&&sy==ey){
    return drawGameOver();    
    return event.key=false; 
  }

  draw();
});

Write return false If you know the right location, what other code is needed to activate the key
Please let me know if you know.

javascript

2022-09-30 21:47

1 Answers

If you return false in the event handler, cancel the default behavior of the browser only for the event in progress.Default behavior includes inserting characters into text fields, scrolling with space keys, and so on.

In this case, return false is irrelevant because it is not the browser's default behavior that you want to cancel.

You may want to be able to check the status of the game in the event handler and not process it after the game has been over.

const State={
  PLAYING: 0,
  GAME_OVER:1
};
let gameState = State.PLAYING;

addEventListener("keydown", function(event){
  // do nothing after a game over
  if(gameState===State.GAME_OVER)
    return;

  // handle cursor keys during play
  console.assert(gameState===State.PLAYING);
  if(event.key=="ArrowUp"){
    ...
  if(sx==ex&&sy==ey){
    gameState=State.GAME_OVER;
    drawGameOver();
    return;
  }

  draw();
});


2022-09-30 21:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.