JavaScript Naval Combat Game

I created a basic battleship game using javascript, but unfortunately it's not working properly. I stored the ship locations in an array and attempted to remove guessed locations by using the splice method. However, it keeps displaying "MISS!" when numbers between 0 and 6 are entered.

Edit: I managed to fix the issue by utilizing the parseInt method for the prompt.

var location1 = Math.floor(Math.random() * 5);
var location2 = location1 + 1;
var location3 = location2 + 1;

var locations = [];
locations.push([location1, location2, location3]);

var guess;
var hits = 0;
var guesses = 0;

var isSunk = false;

while (isSunk == false) {
    guess = prompt("Enter your guess(0 - 6)");
    if (guess < 0 || guess > 6) {
        alert("Please enter a valid number!");
    } else {
        guesses++;

        if (locations.indexOf(guess) > 0) {
            locations.splice(locations.indexOf(guess), 1);
            hits++;
            alert("HIT!");
            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);

Answer №1

In order to accomplish this task, start by creating an Array with elements as shown below:

let numbersArray = [1, 2, 3, 4, 5]

Instead of deleting the index of the array, you should remove individual elements from it.

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

Invoking functions with JavaScript objects

Can anyone help me figure out what is wrong with the following JavaScript code? <form> What is 5 + 5?: <input type ="number" id ="num_answer;"/> </form> <script> function basic_math(){ var num_val = document.getElem ...

Integrating a fresh element into the carousel structure will automatically generate a new row within Angular

I'm currently working on an Angular4 application that features a carousel displaying products, their names, and prices. At the moment, there are 6 products organized into two rows of 3 each. The carousel includes buttons to navigate left or right to d ...

Encountering issues when attempting to establish the initial date of a react DatePicker based on the user's timezone

I am currently working on a React project and facing an issue with setting the default date of a DatePicker component to the user's timezone received from an API. Despite several attempts, I keep encountering an error whenever I try to inject the date ...

How can I seamlessly combine CoffeeScript and TypeScript files within a single Node.js project?

When working on a server-side node project utilizing the standard package.json structure, what is the best way to incorporate both Coffeescript and Typescript files? It's crucial that we maintain the availability of npm install, npm test, and npm sta ...

Managing user sessions in Node.js

What is the best way to manage SESSIONS in Node.js? Specifically, I am interested in storing a UserID in a session using Node.js. How can this be accomplished, and is it possible to access that Node.js session in PHP as well? I am looking for an equivale ...

Disappearing Query Parameters in POST Requests with Node.js and Express

This is my first attempt at creating a JavaScript client and nodeJS server with Express that communicate using REST API. However, I'm running into an issue where any parameter I pass in the xhttp.send function is not being received on the back-end. O ...

We need to display JSON data from a URL onto an HTML page within a table format

Could someone assist me with fetching JSON data from a URL Link on Amazon AWS and displaying it in an HTML table? I am a novice at this, so please explain it easily. Below you can see the HTML code, JS code, and sample information that I would like to ex ...

In what way can an array be assigned to a new key within the same key along with additional objects?

My goal is to transform the existing key value into a new format within the same key. It may be difficult for me to explain clearly through words, but the following data will help clarify. The data is currently structured as follows: const sampelData = [{ ...

Can jQuery help me identify which <input type='image> was clicked within a form containing several submit images?

Consider this hypothetical scenario: <form> <input type="text" name="some_name" value="val" id="some_name"> <input type="image" value="action" alt="Add To Cart" name="add" src="/images/submit.gif"> <input type="image" value="act ...

Using Ruby to loop through JSON data and save it into a MySQL database

I am currently using an open JSON API in the following way require 'net/http' require 'rubygems' require 'json' require 'uri' require 'pp' url = "http://api.turfgame.com/v4/users" uri = URI.parse(url) da ...

JavaScript fails to effectively validate URLs

I have implemented the following validation for URLs: jQuery.validator.addMethod("urlValidatorJS", function (value, element) { var regExp = (/^HTTP|HTTP|http(s)?:\/\/(www\.)?[A-Za-z0-9]+([\-\.]{1}[A-Za-z0-9]+)*\.[A-Za-z]{ ...

What is the reason for recursion not producing a new object as output?

Trying to filter out nodes in a recursion function that iterates through a tree based on the registry property. function reduceNodesRegistry(source: any) { if (!source.registry) return source; return { ...source, children: s ...

Firebase Functions: Your functions are missing a definition

I have the following code in index.js: exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onCreate((snapshot, context) => { // Fetch the current value written to the Realtime Database. const original = snapshot. ...

I'm facing an issue where my React onClick event is not functioning as expected; whenever I click,

When I click the create button, my page is not refreshing and the required part is not working. If I try not using onClick onSubmit, the required part works, but when I click the button, the page refreshes. I'm not sure why. I have written e.preventDe ...

Using Python, Scrapy, and Selenium to extract dynamically generated content from websites utilizing JavaScript

I am currently utilizing Python in combination with Selenium and Firefox to extract specific content from a website. The structure of the website's HTML is as follows: <html> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"> ...

Does one require the express.js framework in order to create a web application using nodeJS?

Exploring the creation of a basic web application using HTML, NodeJS, and Postgres. Can this be achieved without incorporating the ExpressJS framework? Seeking guidance on performing CRUD operations with NodeJs, Javascript, and Postgres sans ExpressJS. G ...

What is the best method to select a sibling element by its class name and then conceal it using solely Javascript?

Here is the HTML structure I am working with: <div id="xyz"> </div> <div class="content"> </div> I am looking to hide the element with a class named content based on the sibling element ID, which is xyz. In jQue ...

JS Issue with Generating Content

Introduction( kind of :) ) Starting with the process of generating 5 coffee beans for each cup of coffee. The coffee class includes a strength attribute, and my goal is to visually distinguish the coffee beans which have a strength greater than the select ...

Is it feasible to send the entire schema in a single response status?

My current experiment involves retrieving all items from five different schema objects. Here is a snippet of my code: const GetAllApple = (req,res) => { const list = [] Ipad.find() .then(data => list.push(data)) .catch(err = ...

What is the best method for toggling between three different elements in an array?

I have been working on a language switcher feature in my Next.js project. The idea is to have three languages available, with the ability for the user to click on a language and have it become the active one, while moving the previously active language t ...