Skip to content

Instantly share code, notes, and snippets.

@le717
Created August 28, 2014 18:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save le717/9dd67d07bfcb3644f150 to your computer and use it in GitHub Desktop.
Save le717/9dd67d07bfcb3644f150 to your computer and use it in GitHub Desktop.
v1.2 of Elisabeth Robson ( https://github.com/bethrobson )'s Battleship game from her book Head First JavaScript program, which I am using as the textbook at college. I call it v1.2 as I made it slightly more advanced than it should be at the end of Chapter 2. 😃
/* jshint -W097 */
/* global prompt, alert */
"use strict";
var guess,
loc1 = Math.floor(Math.random() * 5),
loc2 = loc1 + 1,
loc3 = loc1 + 2,
hits = 0,
isSunk = false,
guesses = [];
// Loop until the ship is sunk
while (!isSunk) {
guess = parseInt(prompt("Ready, aim, fire! (enter as number between 0-6)"));
// The user entered an invalid guess or a cell that has been guessed already
if (guess < 0 || guess > 6 || guesses.indexOf(guess) > -1) {
alert("Please enter a valid cell number!");
// The guess was valid
} else {
// The user correctly guessed the ship's location
switch (guess) {
case loc1:
case loc2:
case loc3:
hits += 1;
alert("Hit!");
break;
// ... Or not
default:
alert("Miss!");
}
// The user found and sunk the battleship
if (hits === 3) {
isSunk = true;
alert("You sunk my battleship!");
}
}
// Keep track of the cells the user has guessed
guesses.push(guess);
}
// Give the user the round's results, round shooting accuracy to nearest percent
var stats = "You took " + guesses.length + " guesses to sink the battleship. " +
"This gives you a shooting accuracy of " + Math.round((3 / guesses.length) * 100) + "%.";
alert(stats);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment