JSFiddle - React, Tailwind, and code Playground

by Nicolas PUJOL

JavaScript

"use strict";

const DIRECTION_VERTICAL = 1,
    GRID_SIZE = 10,
    EMPTY_POSITIION = 0,
    DESTROYED_SHIP_POSITION = 1,
    SHIP_POSITION = 2;

var x,
    grid = [],
    ships = [5, 4, 4],
    gameFinished = false;

function createGrid(cols, rows) {
    var i, j;
    for (i = 0; i < cols; i++) {
        grid[i] = [];
        for (j = 0; j < rows; j++) {
            grid[i][j] = 0;
        }
    }
}

function addShips(ships) {
    ships.forEach(function(ship, index) {
        addShip(ship, index);
    });
}

function createShipPosition(ship) {
    let dir = Math.floor(Math.random() * 2),
        col,
        row;

    if (dir === DIRECTION_VERTICAL) {
        col = Math.floor(Math.random() * GRID_SIZE);
        row = Math.floor(Math.random() * (GRID_SIZE - ship + 1));
    } else {
        col = Math.floor(Math.random() * (GRID_SIZE - ship + 1));
        row = Math.floor(Math.random() * GRID_SIZE);
    }
    return {
        'col': col,
        'row': row,
        'dir': dir,
        'size': ship,
        'number': 0
    };
}

function isValidShipPosition(pos) {
    var i;

    for (i = 0; i < pos.size; i++) {
        if ((pos.dir === DIRECTION_VERTICAL && grid[0][pos.row + i] !== EMPTY_POSITIION) ||
            (!pos.dir === DIRECTION_VERTICAL && grid[pos.col + i][0] !== EMPTY_POSITIION)) {
            return false;
        }
    }
    return true;
}

function addShip(ship, index) {
    var position,
        isValidPosition = false;
    do {
        position = createShipPosition(ship);
        if (isValidShipPosition(position)) {
            placeShip(position, index);
            isValidPosition = true;
        }
    } while (!isValidPosition);
}

function placeShip(pos, index) {
    var i;

    for (i = 0; i < pos.size; i++) {
        if (pos.dir === DIRECTION_VERTICAL) {
            grid[pos.col][pos.row + i] = SHIP_POSITION + index;
        } else {
            grid[pos.col + i][pos.row] = SHIP_POSITION + index;
        }
    }
}

function isValidPos(pos)...