Question

I'm making a battleship game in JavaScript and I stumbled upon a problem

    var targetString = target.replace(/\s+/g, '');
    for(var i = 0; i !== inputArray.length; i++) {
        for(var j = 0; j !== boats[i].usedPositions.length; j++) {
            if(targetString === boats[i].usedPositions[j].toString()) {
                hit = true;
                boats[i].hits[j] = 1;
                console.log(boats[i].hits);
                currentBoat = boats[i];
                boats[i].usedPositions.splice(j,1);
                break;
            }                                
        }  
    }

    if(hit && stop == false) {
        alert ("Hit!");
        if(allEquals(currentBoat.hits, 1) && hit) {
            alert("Boat with length " + currentBoat.hits.length + " has sunken!");
            sunkenBoat++;
        }
    }

The first piece of code checks if the entered coordinate matches a coordinate of the boats (all of these are stored in usedPositions). To prevent that the player can hit that boat again, I want to take the hit coordiante out of that array using splice. But when I do this, it doesn't alert me when a boat has sunken (second piece of code). When the line with splice in is removed, it does give the alert. Can anyone help me? Full code is found here.

Was it helpful?

Solution

splice moves the subsequent array elements down to fill the space. Your logic doesn't look like it's expecting things to move like that.

Instead of splice, you probably just want to assign some other value to that array location, e.g.:

boats[i].usedPositions[j] = " "; // Where " " is assumed not to represent a boat
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top