JavaScript Easy Battleship Game

This is a fun and simple way to create a Battleship Game using only JavaScript


* Based on example in Head First Javascript Programming by Eric Freeman & Elisabeth Robson


JavaScript


var randomloc = Math.floor(Math.random() * 20)
var loc1 =randomloc;
var loc2 = loc1+1;
var loc3 =loc2+1;
var guess;
var hits =0;
var guesses = 0; 
var isSunk = false;

while (isSunk == false){
    guess = prompt("Ready aim fire! (enter a # from 1-20):");
    if (guess<0 || guess > 20){
        alert("Please enter a valid cell #!");
    }
    else {
        guesses = guesses +1;
        
        if (guess == loc1 || guess == loc2 || guess== loc3){
            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);


Click here to See this code and Play



More Free Code Examples:


Random Animal Generator Tutorial


Substitution Cipher


Hello World in 10 Programming Languages





Comments

Popular posts from this blog

Crypto Mining

Multi-tap Keypad Text Entry