I am currently working on a game that enables users to place pieces onto a grid. Once a piece has been placed on the grid, there should be some functionality that prevents further pieces from being added in the same grid positions. Below is what I have designed so far for this feature.
The issue I am having is that the function always returns false, thereby enabling pieces to be continually added into the same grid positions, even if there is a ship placed.
start and end are both integer values and direction is either horizontal or vertical:
const checkIfShipPresent = (direction, start, end) => {
if (direction === 'horizontal') {
for (let i = start; i <= end; i++) {
shipYard.forEach((ship => {
if (ship.position.includes(i)) {
return true;
}
}))
};
return false;
The below code illustrates how I have been attempting to test the function:
const checkIfShipPresent = (direction, start, end) => {
if (direction === 'horizontal') {
for (let i = start; i <= end; i++) {
shipYard.forEach((ship => {
console.log(ship.position)
console.log(i)
console.log(ship.position.includes(i))
if (ship.position.includes(i)) {
console.log("triggered")
return true;
}
}))
};
console.log("firing")
return false;
Here is the associated console log results (with a ship placed at grid positions [0,1,2,3,4] and clicking on cell 0):
gameboardFactory.js:71 (5) [0, 1, 2, 3, 4]
gameboardFactory.js:72 0
gameboardFactory.js:73 true
gameboardFactory.js:75 triggered
gameboardFactory.js:71 (5) [0, 1, 2, 3, 4]
gameboardFactory.js:72 1
gameboardFactory.js:73 true
gameboardFactory.js:75 triggered
gameboardFactory.js:71 (5) [0, 1, 2, 3, 4]
gameboardFactory.js:72 2
gameboardFactory.js:73 true
gameboardFactory.js:75 triggered
gameboardFactory.js:71 (5) [0, 1, 2, 3, 4]
gameboardFactory.js:72 3
gameboardFactory.js:73 true
gameboardFactory.js:75 triggered
gameboardFactory.js:71 (5) [0, 1, 2, 3, 4]
gameboardFactory.js:72 4
gameboardFactory.js:73 true
gameboardFactory.js:75 triggered
gameboardFactory.js:80 firing
I need the function to return true if there is a ship present, but as you can see it doesn't ever break out of the loop and consequently will always return false.
return trueis from the function inside theforEach(which ignores its return value) - you're not actually returning from thecheckIfShipPresentfunctionconst foundTarget = shipYard.some(ship => { ... })--return true;will now break out of the loop and propagate tofoundTarget, which you can test and return.