Search code examples
javascriptarraysappcelerator

Hit register for a 1d Battleship game. Using array to record previous user inputs, then cross-checking them with current input


I am a novice programmer. I have started teaching myself JavaScript. I made a rudimentary battleship game. Problem is that if the user enters the same location(if it's a hit) 3 times the battleship sinks. To avoid that I added an array "userchoices" to record user inputs and then cross-check by iterating through a for-loop. the for loop, in turn, contains an If statement that should alert the user if they have already fired at the location before. Problem is that the if statement gets executed each time.

Please review the code below and suggest corrections. Thank you.

var randomloc = Math.floor(Math.random() * 5);
var location1 = randomloc;
var location2 = location1 + 1;
var location3 = location2 + 1;
var guess;
var userchoices = [];
var hits = 0;
var guesses = 0;
var issunk = false;

function battleship() {
while(issunk == false)
{
    guess = prompt("Ready,Aim,Fire! (Enter a number 0-6):");

    console.log("users input = " + guess);

    if (guess == null)
        break;

    if (guess < 0 || guess > 6){
        alert("Please enter a valid cell number. No of guesses has been 
    incremented.")
    }
    else{
        guesses++;
        userchoices[guesses] = guess;
        console.log("users choices = " + userchoices);
        }

   /* for(var i = 0; i <= guesses; i++)
        {
            if(userchoices[guesses] = guess)
            console.log("you have already fired at this location");
        } */

    if (guess == location1 || guess == location2 || guess == location3){
        alert("Enemy Battleship HIT");
    hits = hits + 1;

    if (hits == 3){
        issunk = true;
        alert("Enemy battleship sunk")
    }
        }
    else{
        alert("You Missed");
    }
    }
    if (issunk){var stats = "you took " + guesses + " guesses to sink the battleship. You accuracy was " + (3/guesses);alert(stats);}
    else{alert("You Failed!"); issunk = false;}
    }

This is the part that is causing an error

for(var i = 0; i<=guesses; i++)
{
if (userchoices[guesses] = guess){
console.log("you have fired at this location already");
}}

The if statement should execute only when the user enters a grid number that he already has fire upon, no matter hit or miss.


Solution

  • After much-needed help from Avin Kavish and bit of tinkering of my own, I can now present an answer to my own question for future viewers.

    Edit: More like my final program

    function battleship() 
    {
    var guess; //Stores user's guess
    var userchoices = []; //records user's guess until ship is sunk or user chickens out
    var issunk = false; //status of ship
    var hits = 0; //number of hits
    var guesses = 0; //number of guesses
    var randomloc = Math.floor(Math.random() * 5); //Random Number Generator
    var location1 = randomloc; 
    var location2 = location1 + 1;
    var location3 = location2 + 1;
    
    while(issunk == false)
    {
        guess = prompt("Ready,Aim,Fire! (Enter a number 0-6):");
        console.log("users input = " + guess);
    
        if(guess == null) // If users presses 'OK' without entering anything or the 'Cancel' this would break the loop.
            break;
    
        if (guess < 0 || guess > 6){
            alert("Please enter a valid cell number. No of guesses has been incremented.");
    guesses++; //Gotta punish the player.
        }
        else if (userchoices.includes(guess) == false) /*instead of doing what i did yo u 
    can change this line to "else if (userchoices.includes(guess)) and then put the 
    following oprations in its else clause. */
        {
            guesses++;
            userchoices[guesses] = guess;
            console.log("User choices = " + userchoices);
    
            if (guess == location1 || guess == location2 || guess == location3)
            {
                alert("Enemy Battleship HIT");
                hits = hits + 1;
                if (hits == 3)
                {
                    issunk = true;
                    alert("Enemy battleship sunk");
                }
            }
                else
                {
                    alert("You Missed");
                }
        }
             else
            {
                alert("you have already fired at this location.")
            }
        if (issunk) //writing issunk == true is overkill
        {
            var stats = "you took " + guesses + " guesses to sink the battleship. You 
    accuracy was " + (3/guesses);
            alert(stats);
        }
    }
    if(guess == null && issunk == false)
    console.log("You failed");  //Humiliate the user for chickening out.
    userchoices = []; //Empties the array so user can start over again without relaoding the page
    issunk = false; //sets issunk to false for a new game
    var randomloc = Math.floor(Math.random() * 5); //creates new random numbers for ship coordinates
    }
    

    2D 7X7 version coming soon. Will post here.