1

Making a battleship project in JS for practicing OOP, and I'm having a hard time with the function of positioning objects (ships) properly in the grid board

I have this factories:

const Coordinate = ({ship = null, hit = false} = {}) => ({
    ship,
    hit,
})

And this:

const Gameboard = ( { ships = ships, grid = Array(10).fill(Array(10).fill(Coordinate())) } = {} ) => ({
    ships,
    grid,
    putShip(ship, x, y) {
        let pos = ship.length;
        while (pos > 0) {
            this.grid[x][y].ship = ship;
            pos -= 1;
            x += 1;
        }
        return this;
    },
    AllShipsDown() {
        return this.grid.every(row => {
            row.every(cord => {
                cord.hit === true;
            })
        })
    }
})

and ships:

const Ship = ({length, name}) => ({
    length,
    name,
    hit() {
        this.length -= 1;
        return this;
    },
    isSunk() {
        return this.length == 0
    },
})

I want to update just 1 coordenate in the putShip fun, so that if it's a ship of x lenght it will occupy x coordinates, something like:

const game = Gameboard({ships: ships}); // Ships is an array of ship objects.
game.putShip(game.ship[0], 0, 0)
game.grid[0][0] // => coordenate object with ship as ship object
game.grid[8][0] // => coordenate object with null ship

But when I do, all coordenates are getting overriden, like:

game.grid[8][8] // => coordenate object with ship object

What am I doing wrong? It's this the right way to OOP in JS?

zedge
  • 81
  • 5
  • 1
    Don't `.fill` with non-primitives, otherwise each element in the array will refer to the same object in memory - instead, create the arrays with `Array.from`, to create the `coordinate` more explicitly on each iteration – CertainPerformance Jan 18 '20 at 00:33

0 Answers0