Head-First-JavaScript-Programming icon indicating copy to clipboard operation
Head-First-JavaScript-Programming copied to clipboard

battleship game in chapter 2 is flawed !!!

Open kshitijpurwar opened this issue 10 years ago • 4 comments

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.

kshitijpurwar avatar Jun 07 '15 10:06 kshitijpurwar

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

bethrobson avatar Jun 08 '15 03:06 bethrobson

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

jlgeter2002at2002dotcom avatar Jan 17 '22 19:01 jlgeter2002at2002dotcom

Or go on to Chapter 8 :-)

bethrobson avatar Jan 18 '22 18:01 bethrobson

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);

LetsGoMaan avatar Jul 02 '22 10:07 LetsGoMaan