Skip to content

Instantly share code, notes, and snippets.

@janosgyerik
Created May 13, 2015 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janosgyerik/9e2071274a4fb57a83d9 to your computer and use it in GitHub Desktop.
Save janosgyerik/9e2071274a4fb57a83d9 to your computer and use it in GitHub Desktop.

// answer to http://codereview.stackexchange.com/questions/90669/dragon-slayer-game-in-javascript#90669

Slaying dragons... That's the kind of code review I just can't say no to...

So, essentially, we have this logic:

  • Setup:
    • youHit is set to 0 or 1 randomly
    • damageThisRound is set to 1, 2, 3, 4, 5 randomly
  • Play one game round:
    • If youHit is 0 at any time, you die
    • If youHit is 1, you do some damage (always the same damage)
      • If the total damage reaches 4, the dragon dies
      • Otherwise update youHit and play another round

A few improvement ideas:

  • The slaying variable is not really great. The name is not great and you don't really need it. When the game is over, you can break out of the loop without the extra variable.

  • The logic of calculating youHit is duplicated. It would be better to write it once, in a function. The name is not so great either, and you don't actually need a variable, you could use the function directly.

  • damageThisRound is a misleading name. It suggests a different damage per round, but it's actually the same every round.

  • The indentation is off in the middle of the loop

  • The health of the dragon hardcoded as 4 is not great. It would be better to put that in a variable. Actually, it's also strange to have a cumulative total damage. It would make more sense to have decreasing health.

Putting it together:

function hit() {
    return Math.floor(Math.random() * 2);
}

var damagePerRound = Math.floor(Math.random() * 5 + 1)  
var healthOfDragon = 4;

while (true) {       
    if (hit()) {           
        confirm("Congratulations, you hit, dealing " + damagePerRound + " damage!");           
        healthOfDragon -= damageThisRound;             
        if (healthOfDragon <= 0) {
            confirm("You slew the dragon!");
            break;
        }       
    } else {          
        confirm("Unlucky, you were slain by the dragon!");           
        break;
    }   
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment