Jump to content

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
https://forums.phpfreaks.com/topic/292919-if-statement-to-switch-statement/
Share on other sites

Have you tried this your self? If you are not familiar with a switch then see here first

 

Basically you pass e.keyCode as the expression. 65 and 68 will be used as the case expression. The if statements will go in the corresponding case statement.

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.