EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

[Tutorial] Teach you step by step to use JavaScript to write a Sokoban game (Part 1)

If you are a complete beginner, you have found the right blog. This blog will teach you how to use JavaScript through a game example——Sokoban game.

By default you have some basic knowledge of HTML, and you know how to write a javascript tag. The first knowledge point we need to learn is the document.onkeydown event.

Normally, we write "document.onkeydown=" to start the keydown function. In other words, when you press any key, the method after this "=" will be executed.

Code:

<script>
document.onkeydown=function(e){
    var keyNum=window.event ? e.keyCode :e.which;    
    if(keyNum==87){
    console.log('You pressed W');
    }
    if(keyNum==83){
    console.log('You pressed S');
    }
    if(keyNum==65){
    console.log('You pressed A');
    }
    if(keyNum==68){
    console.log('You pressed D');
    }
}
</script>

Let me explain this "e", which means event. This is a variable predefined by the javascript interpreter for listening to keyboard events. We can get the key code through it.

var keyNum=window.event ? e.keyCode :e.which;    

This sentence means that I have declared a variable called "keyNum" to store the obtained key code. Then it is my logic to determine what the key code is and what to execute.

87=W, 83=S, 65=A, 68=D

You don't need to remember these, you just need to look up these key codes when you use them.

Complete code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>KeyBoardEvent Demo</title>
</head>
<body>
<script>
document.onkeydown=function(e){
    var keyNum=window.event ? e.keyCode :e.which;    
    if(keyNum==87){
    console.log('You pressed W');
    }
    if(keyNum==83){
    console.log('You pressed S');
    }
    if(keyNum==65){
    console.log('You pressed A');
    }
    if(keyNum==68){
    console.log('You pressed D');
    }
}
</script>
</body>
</html>

You can try to run these codes in Google Chrome. Press F12 to open the console and observe what happens when you press the "W" "A" "S" "D" keys.

Basically, if it runs correctly, if you press the "W" key, the console will print "You pressed W", if you press the "S" key, the console will print "You pressed S", and other same. (Actually I shouldn't explain it, but consider if you are a complete beginner)


Next: [Tutorial] Teach you step by step to use JavaScript to write a Sokoban game (Part 2)

This article was last edited at 2020-11-14 21:49:27

* *