Quantcast
Channel: Keyboard handler for moving in four directions - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 3

Answer by SirPython for Keyboard handler for moving in four directions

$
0
0

Your code is rather short, but can still be greatly improved.


Should I keep the default: break; or not?

Do not keep it. Since you aren't doing anything for the default case, there is no point in having it. You can remove that entire thing.


Map

In order to improve the readability of your code (and overall efficiency), I recommend creating a map that maps the key code values to the changes needed to be made to dx and dy. Here is what I mean:

var keyToChangeMap = {    87: [0, -50], // [change in x, change in y]    65: [-50, 0]    ...};

Now, you have an \$O(1)\$ method for finding out how to change the dx and dy values. This is also flexible: you can easily change the values that x and y change by, and you can easily add more keys to listen to.

Then, in your function, simply use the key code to get a value from the map:

function handleKeyDownEvent(event) {    var keyCode = event.keyCode;    if(keyToChangeMap.hasOwnProperty(keyCode)) {        var change = keyToChangeMap[keyCode];        player.dx += change[0];        player.dy += change[1];    }}

Magic numbers

You have some magic numbers in your code. It's pretty difficult to understand these numbers, so you should create constants to represent these values.

For example,

var W_KEY = 87;var A_KEY = 65;

You don't even have to be that specific. You can do something like this:

var UP_KEY = 87;var LEFT_KEY = 65;

which is even more readable.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>