Skip to content

Instantly share code, notes, and snippets.

@kariabancroft
Created August 31, 2015 16:27
Show Gist options
  • Save kariabancroft/f8611d5c938c84c5cdd8 to your computer and use it in GitHub Desktop.
Save kariabancroft/f8611d5c938c84c5cdd8 to your computer and use it in GitHub Desktop.
Basic JS implementation of a little battleship
$(document).ready(function(){
/* Stores the board info
0 for empty
1 for ship
X when hit
*/
var board = [];
// Stores the locations of the ships
var ships = [];
// Current number of ships
var shipNum = 2;
// Size of the board
var boardSize = 10;
// Bool indicating whether or not game is over
var gameOver = false;
// Number of ship hits
var hits = 0;
// Number of guesses
var guesses = 0;
initializeGame();
function initializeGame(){
generateRandomBoard();
printBoard();
}
function generateRandomBoard(){
// Add some random ships
var shipsAdded = 0;
while (shipsAdded < shipNum) {
var randomVal = Math.floor(Math.random() * (boardSize - 1));
if (ships.indexOf(randomVal) < 0) { // Not already one of the ships
ships.push(randomVal);
shipsAdded++;
}
}
// Set the board values based on ships added
for(var j = 0; j < boardSize; j++) {
if (ships.indexOf(j) < 0) { // This location not a ship
board[j] = 0; // Empty
} else {
board[j] = 1; // Ship!
}
}
}
function printBoard() {
var boardOut = "";
for(var i = 0; i < boardSize; i++) {
boardOut += board[i];
}
$("#board").text(boardOut);
}
function endGame() {
// TODO: End game
// ADDED FUN: Disable submit button
console.log("End game");
$("#end-game").text("GAME OVER!");
}
// CLICK HANDLERS
$("#submit").click(userGuess);
function userGuess(){
var guess = $("#guess").val();
$("#guess").val("");
if (guess < 0 || guess > 9) {
alert("Please enter a valid cell number!");
} else if (guess === null){
console.log("QUIT");
} else {
if (!gameOver) {
guesses++;
guess = parseInt(guess);
// Check the users guess against the board for hit/miss
if (ships.indexOf(guess) !== -1){ // HIT
board[guess] = "X";
hits ++;
showResult("HIT");
} else { // MISS
board[guess] = "-";
showResult("MISS");
}
printBoard();
if (hits === shipNum){
endGame();
} else {
// userGuess();
}
} else {
endGame();
}
}
}
function showResult(result) {
var guessDiv = $('#guess-result');
guessDiv.text(result);
guessDiv.show();
window.setTimeout(function () {
$('#guess-result').hide();
}, 2000); // hide after 5s
var guessCount = $("#guess-count");
guessCount.text("Num guesses: " + guesses);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment