A simple Battleship game using javascript
Screenshot:
<script>
var rand = Math.floor(Math.random() * 5);
var location1 = rand;
var location2 = location1 + 1;
var location3 = location2 + 1;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while(isSunk==false) {
guess = prompt("Ready,aim,fire! (Enter a number 0-6):");
if(guess < 0 || guess > 6) {
alert("Please enter a valid 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 battleship, " + "your shooting accuracy was " + (3/guesses);
alert(stats);
</script>
Description:-
The first parameter of prompt() is the heading of program.
The alert checks whether you entered a correct value between 0-6 and it shows that you hit or miss the targets.Finally,it will show your result.
If you find the code useful,share it!.

Comments
Post a Comment