Battleships
by edgardleal
HTML
<table id="map"></table>
CSS
#map td{
font-size : 10px;
width : 30px;
height : 30px;
}
JavaScript
function Target(_map){
this.x = 1 + Math.round(Math.random() * 9);
this.y = 0;
this.map = _map;
this.mapWidth = _map.find('tr').first().find('td').length;
this.mapHeight = _map.find('tr').length;
this.direction = {x : 0, y : 1};
this.oldCell = null;
this.currentCell = null;
this.currentTr = null;
var self = this;
this.onEndOfMap = null;
console.log(this.mapWidth);
this.move = function(){
if(self.x >= this.mapWidth || self.y >= self.mapHeight)
return;
self.x += self.direction.x;
self.y += self.direction.y;
self.oldCell = self.currentCell;
this.currentTr = $(map).find('tr:nth-child(' +
this.y
+ ')');
this.currentCell = this.currentTr.find('td:nth-child(' +
this.x +
')');
this.draw();
};
this.draw = function(){
if(this.oldCell)
this.oldCell.css('color', 'black');
if(this.currentCell)
this.currentCell.css('color', 'red');
};
};
var map = $('#map');
for(var x = 0; x < 10; x++){
var tr = $('<tr/>').appendTo(map);
for(var y = 0;y < 10;y++ )
$("<td>").appendTo(tr).append($('<a/>').text('X'));
}
var targets = [new Target(map),
new Target(map)];
setInterval(function(){targets[0].move();}, 1000);
setInterval(function(){targets[1].move();}, 800);