JSFiddle - React, Tailwind, and code Playground
by Nicolas PUJOL
HTML
<div id="battleships"></div>
CSS
.td {
width: 30px;
height: 30px;
border: 1px solid #000;
}
.boat {
background-color: red;
}
JavaScript
//Battleships
function createGrid() {
var grid = '<table>';
for (var row = 1; row <= 10; row++) {
grid += '<tr>';
for (var col = 0; col <= 9; col++) {
grid += '<td class="td" id="square-' + ((row - 1) * 10 + col) + '">' + ((row - 1) * 10 + col) + '</td>';
}
grid += '</tr>';
}
grid += '</table>'
//$('#battleships').append(grid);
}
function getBoats() {
var startPos,
dir,
boats = [{
'squares': 5,
'name': 'Battleship'
}, {
'squares': 4,
'name': 'Destroyer 1'
}, {
'squares': 4,
'name': 'Destroyer 2'
}];
$.each(boats, function() {
//pas de chevauchements a faire
this.start = Math.floor(Math.random() * 99);
this.dir = Math.floor(Math.random() * 2) ? 1 : 10;
if (this.dir === 1 && parseInt((this.start + this.squares) / 10) !== parseInt(this.start / 10)) {
this.start = parseInt(parseInt(this.start / 10) + '9') - this.squares;
}
if (this.dir === 10 && this.start + (this.squares * this.dir) > 99) {
this.start = (9 - this.squares) + this.start.toString().substr(-1);
}
});
createGrid();
}
function init() {
getBoats();
}
init();