Jump to content

If Statement to Switch Statement


AlexT

Recommended Posts

Hello Everyone,
I have to change the if statements to a switch statement, in this game. Can anyone help? Thanks.

var checkKeyPressed = function (e) {
// Press key A or key D to make dog run to the left or right
// The running speed is specified by the step variable, 10 by default.
// If you replace 10 with a larger integer, the dog will run faster.

    //press A, dog runs left
    if (e.keyCode == "65") {
        if (prex[0] > 5) {
            prex[0] = prex[0] - step;
        }
    }
    //press D, dog runs right
    if (e.keyCode == "68") {
        if (prex[0] < right) {
            prex[0] = prex[0] + step;
        }
    }
};
Link to comment
Share on other sites

Thanks for the link.  How is this looking?

 

switch (e.keyCode) {
case '65':
if (prex[0] > 5) {
         prex[0] = prex[0] - step;
}
break;
case '68':
if (prex[0] < right) {
            prex[0] = prex[0] + step;
}
break; 
Link to comment
Share on other sites

That's the idea behind a switch statement. Should be no issues with that code you just wrote.

 

However, because I'm picky, I want to point out that you are currently referencing your switch statement's keys with Strings. IE '65', '68'. Because browsers parse/react differently to javascript objects and keys/values, I'd like to make this suggestion:

 

 

var keyCode = parseInt(e.keyCode);
 
switch(keyCode) {
case 65:
...
break;
case 68:
...
break;
}

 

This way you can be sure it will work cross-browsers. I know some browsers tend to consider the keyCode as an integer, which makes sense. While others consider it a string. So in short, parsing the String to an Integer is the safer option here.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.