Join the tournament for a thrilling game of Battleship in 1 dimension. We will keep track of all your moves using an array, comparing them to your latest input for

As a beginner programmer, I have recently delved into learning JavaScript on my own. One of the projects I tackled was creating a simple battleship game. However, I encountered an issue where if the user hits the same location three times, the battleship sinks prematurely. To address this problem, I implemented an array called "userchoices" to store user inputs and added a for-loop to cross-check whether the user has already fired at a particular location. Unfortunately, the current implementation leads to the if statement being executed each time, which is not the intended behavior.

I would appreciate it if you could take a look at the code snippet below and provide suggestions for improvement. Thank you for your assistance.

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("User's input = " + guess);

    if (guess == null)
        break;

    if (guess < 0 || guess > 6){
        alert("Please enter a valid cell number. Number of guesses has been incremented.");
    }
    else{
        guesses++;
        userchoices[guesses] = guess;
        console.log("User's 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. Your accuracy was " + (3/guesses);alert(stats);}
else{alert("You Failed!"); issunk = false;}
}

This section appears to be causing the error:

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

The intention behind the above if statement is to notify the user only when they fire upon a grid number they've previously targeted, regardless of hitting or missing the battleship.

Answer №1

Ensure you are accessing the array using the correct index. Try userchoices[i] instead of userchoices[guesses]. Remember that equality comparisons require 2 equal signs, like this: ==:

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

You can simplify it by doing:

  if (userchoices.includes(guess)){
    console.log("you have fired at this location already");
  }

Also remember to increment guesses after adding the first value:

    else{
      userchoices[guesses] = guess;
      guesses++;
      console.log("users choices = " + userchoices);
    }

EDIT

There is a logic error in your code as you are checking the array for the element after inserting it. Make sure to perform the check in the else statement before inserting the element. Combining all of the above:

else if (userchoices.includes(guess)){
  console.log("you have fired at this location already");
} else {
  userchoices[guesses] = guess;
  guesses++;
  console.log("users choices = " + userchoices);
}

Answer №2

With the valuable assistance of Avin Kavish and some tweaking on my part, I am pleased to share a solution to my own query for the benefit of future viewers.

Update: This is more like my finalized 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
}

Stay tuned for the upcoming 2D 7X7 version. It will be shared here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I increase the element by $100 using a dropdown selection in JavaScript?

Hey there! Looking to create a dropdown list with two shipping options: Special Shipping Normal Shipping <select> <option>Special Shipping</option> <option>Normal Shipping</option> </select> If the user selects Speci ...

Steps to create a function in a .js file that uses ng-show conditions

I am in the process of validating a web page where the user inputs must be alphanumeric, have a maximum length of 45 characters, and be unique. Below is the code snippet I am working with. Is there a way to consolidate these three ng-show conditions into ...

What are some quality open APIs available for web-based frontend painting tools?

I am in the process of creating an HTML5/JavaScript application inspired by: Although I could simply copy and paste their source code, I am concerned about potential copyright issues. Instead, I am exploring the option of using free APIs that offer simila ...

Shuffle and Arrange Divs - Slick.JS

Incorporating the slick.js library, I have implemented the following code snippet in my web page to shuffle the slides within the carousel. JavaScript/jQuery: $('.qa').on('init', function(event, slick, currentSlide, nextSlide) { / ...

Guide to converting a log string into JSON using Javascript

I encountered a console log that appears as follows: 2021-01-06T09:06:05.541212726Z D saveGarment: Function execution took 736 ms, finished with status code: 204 2021-01-06T09:06:10.844901031Z D saveGarment: Function execution started 2021-01-06T09:06:16.1 ...

Exploring the functionality of Vue.js through Jasmine without the use of JavaScript modules

My task involves investigating unit testing for JavaScript on an older application that does not utilize JS modules (import/export). The app contains JS object/prototypes in external .js files that are imported via script src, and more recently, some Vue 2 ...

What is the best way to send multiple PHP variables to an ajax function when clicked?

I'm encountering an issue while trying to pass variables to a function in my controller using AJAX. The error message at the bottom of the image is preventing the variables from being passed successfully. My setup involves the use of the CodeIgniter ...

I am looking for a sample code for Tizen that allows scrolling of a <div> element using the bezel

Seeking a functional web application in Tizen that can scroll a div using the rotating bezel mechanism. I have dedicated several hours to getting it to work without success. I keep revisiting the same resources for the past three days: View Link 1 View Li ...

What could be causing my AJAX code to fail in retrieving information from an API?

Hey everyone, I'm new here and hoping to get some help with an issue I'm facing. I've written a code to fetch data from an API and display it on my HTML page, but for some reason the AJAX code isn't working. There's nothing showing ...

There is no response from Ajax

I am facing an issue with my AJAX call in communication with my Rails controller. Even though the AJAX call itself seems fine, the callback function does not contain any data. Here is the AJAX request I'm making: $.ajax({ url: '/get_progres ...

Guide to finding and saving email addresses from a string output: extracting and storing each one individually in a text file

After collecting data from multiple sources, the output I obtained is as follows: "addressId":"132234","businessEntryCount":2026},{"district":"Nordend-West","districtSlug":"frankfurt-am-main- ...

Showing API data as JSON feedback in an angular template

I am seeking a way to showcase data on my website directly from a JSON file located at a specific URL. Currently, I am working with Angular and have set up a HttpClient in my component. The code snippet below successfully logs all documents to the console. ...

Troubleshooting JavaScript issues: jQuery not functioning as expected

Although I consider myself experienced in programming, my venture into jQuery has hit a roadblock with this seemingly simple code: $(document).ready(function() { $('.footer').click(function() { $('.footer').fadeOut('sl ...

How to trigger useEffect when the state changes to the same value using React hooks?

Currently working on a drum-pad app, most features are functional except for one small issue. Quick update: Uploaded the project to codesandbox for anyone willing to take a look: codesandbox.io/s/sleepy-darwin-jc9b5?file=/src/App.js const [index, setIndex ...

Error in calculation of $.post function in JQuery

I am facing an issue with my file delete.php, which contains the following code: <?php $folder = "./fak/"; $filename = $_POST['name']; unlink($folder.$filename); ?> Additionally, I have an index.html file with the below code: <html ...

Using Prototype Library to Implement the Nth-child Selector

I've been experimenting with using "nth-child(n)" in Prototype, similar to how it's done in jQuery. See the example code below... function myFunction() { $$('div.amfinder-horizontal td:nth-child(1) select').simulate('click'); ...

Implementing Enter key functionality to add items to a Todo list using pure DOM manipulation

var listLis=document.getElementById('list'); const addbutton=document.querySelector('.fa-plus') const inputBar=document.querySelector('.show') function showInput(e){ inputBar.classList.toggle('show') } addbutt ...

Using jQuery with Rails 3 for Efficient Callback Handling

I have been working on creating my own custom confirm dialogs that take two parameters. function myAlert(message, address) { jConfirm(message, 'Confirmation Dialog', function(response) { if (response){ window.location = a ...

An effective method to transfer a JSON file in PHP with the given structure

Within my collection of data, there is a json file [ ["HEADER", "TEXT", "DATE"], ["Monday", "The text for Monday's entry can be found here", "09:55\n10:00\n10:30\n11:00\n15:45"], ["Tuesday", "This is where the content ...

Exploring the capabilities of Angular 2 and delving into inquiries regarding IIS

I'm diving into the world of Angular 2 as a beginner. Previously, I used to include JavaScript (like jQuery.js) in my HTML and then upload the finished page to my IIS website. Now that I'm learning Angular 2, I've had to install Node.js, NP ...