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.