bethrobson / Head-First-JavaScript-Programming

421 stars 347 forks source link

battleship game in chapter 2 is flawed !!! #8

Open kshitijpurwar opened 9 years ago

kshitijpurwar commented 9 years ago

The code used in battleship game has a very serious bug using which a person can win the game even by getting his one HIT correct. For example if the battleship is present at indices 2,3 & 4.And I come to know by guessing that there is a HIT at 3 then,I can enter "3" two more times and win without even caring about other HITS.

bethrobson commented 9 years ago

Good work! You found the bug :-) This is the bug we find on page 70.

jlgeter2002at2002dotcom commented 2 years ago

I’ve been racking my brain on how to fix it. Reset the counter after each guess?

bethrobson commented 2 years ago

Or go on to Chapter 8 :-)

LetsGoMaan commented 2 years ago

Hello, can you please explain to me what is wrong? Here is the code, when executed in chrome, a miss is thrown every time, but the same code in Edge works fine

var location1 = 3; var location2 = 4; var location3 = 5; var guess; var hits = 0; var guesses = 0; var isSunk = false;

while (isSunk == false) { guess = prompt("Ready, aim, fire! (enter a number from 0-6) : "); if (guess < 0 || guess > 6) { alert("Please enter a valid cell number!"); } else { guesses = guesses + 1;

if (guess == location1 || guess == location2 || guess == location3) {
  alert("HIT!");
  hits = hits + 1;
  if (hits == 3) {
    isSunk = true;
    alert("You sank my battleship!");
  }
} else {
  alert("MISS");
}

} } var stats = "You took " + guesses + " guesses to sink the battleship, " + "which means your shooting accuracy was " + (3 / guesses); alert(stats);