62 lines
1.5 KiB
JavaScript
62 lines
1.5 KiB
JavaScript
class Mapa {
|
|
celdas = [];
|
|
barcos = [];
|
|
|
|
constructor(canvas, size = 320, scale = 1) {
|
|
this.canvas = canvas;
|
|
this.canvas.width = size;
|
|
this.canvas.height = size;
|
|
this.ctx = this.canvas.getContext("2d");
|
|
this.scale = scale;
|
|
this.ctx.scale(this.scale, this.scale);
|
|
|
|
this.casillaSize = 32;
|
|
this.numFilas = 10;
|
|
this.numColumnas = 10;
|
|
|
|
for (let x = 0; x < this.numFilas * this.numColumnas; x++) {
|
|
this.celdas[x] = 0;
|
|
}
|
|
|
|
this.getPosClick = this.getPosClick.bind(this);
|
|
canvas.addEventListener("click", this.getPosClick);
|
|
}
|
|
|
|
setBarcos(barcos) {
|
|
this.barcos.push(...(Array.isArray(barcos) ? barcos : [barcos]));
|
|
}
|
|
|
|
getPosClick(event) {
|
|
const rect = this.canvas.getBoundingClientRect();
|
|
const x = Math.floor(
|
|
(event.x - rect.left) / (this.casillaSize * this.scale)
|
|
);
|
|
const y = Math.floor(
|
|
(event.y - rect.top) / (this.casillaSize * this.scale)
|
|
);
|
|
console.log(x, y);
|
|
}
|
|
|
|
draw() {
|
|
this.barcos.forEach((barco) => {
|
|
barco.draw(this.ctx);
|
|
});
|
|
|
|
this.ctx.beginPath();
|
|
for (let i = 0; i <= this.numFilas; i++) {
|
|
const y = i * this.casillaSize;
|
|
this.ctx.moveTo(0, y);
|
|
this.ctx.lineTo(this.casillaSize * this.numColumnas, y);
|
|
}
|
|
for (let i = 0; i <= this.numColumnas; i++) {
|
|
const x = i * this.casillaSize;
|
|
this.ctx.moveTo(x, 0);
|
|
this.ctx.lineTo(x, this.casillaSize * this.numFilas);
|
|
}
|
|
this.ctx.strokeStyle = "#15ff00";
|
|
this.ctx.stroke();
|
|
}
|
|
}
|
|
|
|
export default Mapa;
|