My current project involves utilizing jQuery to develop a interactive feature called "Drowning vessels."

I am currently working on creating functions to place ships on a board, but I am facing some issues with the function that checks if certain fields are available. My approach involves having one method that is triggered by a button click:

$("#dodaj1x1").click(function(){
        var available=parseInt($("#raspolozivo1x1").text());
        if(available>0){

            generate1x1();//call the function that generates a random field

            var newAvailable= available-1;
            $("#raspolozivo1x1").html(newAvailable);
        }
        else{
            alert("All available ships of this type have been placed!");
        }
    });

It will then call a function to generate a random field:

function generate1x1(){
            var minRow = 0;
            var maxRow = 9;
            var minCol = 0;
            var maxCol = 9;
            randRow=Math.floor(Math.random() * (maxRow - minRow + 1)) + minRow;
            randCol=Math.floor(Math.random() * (maxCol - minCol + 1)) + minCol;
            check1x1(randRow,randCol);//call the function to check if the field is available
    }

The generate1x1() function calls another function to check if the field is available:

function check1x1(randRow,randCol){
        for(i=randRow-1;i<randRow+2;i++){
            for(j=randCol-1;j<randCol+2;j++){
                if($(".row"+i+".column"+j+"").hasClass('shipPart')){
                    alert("row:"+" "+i+" column:"+j);
                    generate1x1();
                }
                else { place1x1(randRow,randCol);}
            }
        }
    }

My issue lies in the fact that sometimes it works well (or at least appears to work), while other times it only generates 3 ships of size 1x1 (instead of the expected 4), or it shows error messages and generates 5 ships (4 in correct positions, 1 in the wrong position).

Here is a screenshot of an incorrect placement: Added ship 1x1 on position 5,3 right next to ship 4x1

You can view a live demo of the entire code here: Live demo

So far, I have only implemented the ability to insert ships of sizes 4x1 and 1x1, and am currently only checking for 1x1 ships. The plan is to extend this functionality to cover all ship sizes. Any assistance would be greatly appreciated.

Answer №1

To enhance comprehension, it is advisable for proveri1x1() to handle the validations and return either true or false, while generisi1x1() takes care of executing the postavi1x1() function;

function generisi1x1() {
    var minRow = 0, maxRow = 9, minCol = 0, maxCol = 9;
    randRow = Math.floor(Math.random() * (maxRow - minRow + 1)) + minRow;
    randCol = Math.floor(Math.random() * (maxCol - minCol + 1)) + minCol;
    if(proveri1x1(randRow, randCol)) { //call to function to check field availability
        postavi1x1(randRow,randCol);//set
    } else {
        generisi1x1();//try again
    }
}

function proveri1x1(randRow, randCol) {
    for(var i=randRow-1; i<randRow+2; i++) {
        for(var j=randColumn-1; j<randColumn+2; j++) {
            if($(".row" + i + ".column" + j).hasClass('shipPart')) {
                return false;
            }
        }
    }
    return true;//<<<< consider the placement of this return statement
}

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

Is there a way to prompt the native browser message for HTML5 form validation on a custom element?

https://i.sstatic.net/3wuWh.png Can the native validation UI be activated on non-default input elements like divs or similar? I want to develop a custom React element with validation without relying on hidden or invisible input fields. ...

Obtain the hexadecimal color code corresponding to the level of humidity

I am in search of a formal method to determine the hexadecimal color based on a percentage value of relative humidity. Here is an illustration of the color range I aim to utilize, it being the most widely used. Is there a specific technique that I can em ...

The data parsing process is throwing an error. Any suggestions on how to fix it?

Utilizing AJAX, I am fetching information from a specified URL. var settings = { "url": ".php", "method": "POST", "timeout": 0, "headers": { "Content-Type": "application/json" }, "data": JSON.stringify({"email":"mail","userid":"admin","typ ...

Is there a way to exclude specific routes in AngularJS ui router?

In my current web application, I am utilizing the ui-router to manage routing. Within one of my views, there is a canvas that interacts with a third-party library which dynamically loads images through HTTP GET requests. However, due to ui.router's $u ...

It is impossible for me to enclose a container around a bootstrap 4 navbar

My goal is to wrap a container class around my navbar, but I'm encountering a problem where the toggle button moves to the center in mobile view. <nav class="navbar navbar-toggleable-md navbar-light bg-faded" id="commRollover"> <div cla ...

What purpose does the <noscript> tag serve in React?

Recently delving into the world of React, I've been working on a simple application by following this tutorial: https://reactjs.org/tutorial/tutorial.html. I've started modifying the code to suit my own project. While inspecting my HTML, I notic ...

The transparent sticky navigation bar isn't functioning as intended

I stumbled upon a code for the sticky navbar that I found on this website. Intrigued, I decided to copy the code and test it out on my Laravel blade file. The output turned out like this: https://i.sstatic.net/lexRl.jpg Here is how I copied the code: CS ...

Assistance with Redirecting Responses in Next.js API Routes

I'm currently working on implementing a login functionality in Next.js. I have made significant progress but I am facing an issue with redirecting to the homepage after a successful login. My setup involves using Next.js with Sanity as the headless CM ...

Utilize jQuery to set a cookie, then apply the bodyclass retrieved from the cookie upon page

I have a button that changes the body class to .blackout For this, I am utilizing js-cookie library to manage cookies. The code snippet associated with my button is shown below: <script> $('#boToggle').on('click', function(e) { ...

Implementing a new class for the select tag in a Ruby on Rails project

Can someone help me with adding a class to the select tag? Here is the HTML code: <select class="phone_no"> I am looking for the ruby equivalent of the above line of code. Can someone provide assistance? <%= select_tag(:id, '<option val ...

What is the best way to ensure the navigation bar stays at the top of the window once it has reached

I have a sample js fiddle provided here. The navigation bar is positioned right below the "Hello World" section, and the content follows beneath the nav bar. Is there a way to make the navigation bar stick to the top of the window once it reaches that poin ...

Implementing incremental value for a dropdown in JavaScript and php when integrating Ajax requests

I am currently working on implementing multiple dynamic drop-down options and attempting to set an incremental value when the user clicks the add button (utilizing the .append function in JavaScript) for both the drop-down options in JavaScript and PHP whi ...

The error message 'this.props.navigation is not defined when using createStackNavigator'

Interested in creating a straightforward navigation example in ReactNative. Take a look at the code snippet below; import React, { Component } from 'react'; import { Button, View, Text } from 'react-native'; import { createStackNaviga ...

What is the best way to handle empty inputs in a class?

I am a novice web developer working on my first application, a small CRUD project. Here is the code I have so far: <template> <CRow> <CCol col="12"> <CCard no-header> <CCardBody> <h3& ...

Emphasize the CSS property and give it top priority

I am struggling with setting the highest priority for the background of the <h1> element. Specifically, I want the background color specified for the <h1> to show instead of what is specified for the <a> element. h1{ background-color:b ...

Don't forget to preserve the hover state of divs even after refreshing

I recently added a navigation bar that expands in width upon hovering over it. For an illustration, check out this example: http://jsfiddle.net/Gsj27/822/ However, I encountered an issue when clicking on a button within the hover effect area. After load ...

The setting for the background color of the chart area in chartjs appears to be ineffective

Why can't I color the chart area of my line graph using this code? options={{ maintainAspectRatio: false, title: { display: true, fontSize: 20 }, chartArea: { backgroundColor: ...

Grid layout that adapts to any screen size, perfect for websites or showcasing

I'm currently developing a responsive grid layout for a gallery. You can view the example here. The goal is to create a grid that automatically adjusts itself when the device orientation changes. Everything works smoothly when the #big_box container& ...

Using AngularJs to implement a $watch feature that enables two-way binding

I am in the process of designing a webpage that includes multiple range sliders that interact with each other based on their settings. Currently, I have a watch function set up that allows this interaction to occur one way. However, I am interested in havi ...

Using jQuery to transfer an attribute from selected elements to their child elements

Currently, I am working with a series of anchor tags that look like this: <a class="lb" href="#">text</a> <a class="lb" href="#" style="width:200px">text</a> <a class="lb" href="#" style="color: reen; width:200px">text</a& ...