JSFiddle - React, Tailwind, and code Playground

by marlanga

HTML

<canvas id="canvas"></canvas>

JavaScript

var DIRECCION={arriba:0, derecha:1, abajo:2, izquierda:3 };
function TRON(canvas, filas, columnas, pos){
    this.timer=100;
    this.ancho=columnas;
    this.alto=filas;
    this.canvas=canvas;
    this.ctx=this.canvas.getContext("2d");
    this.ladoCelda=10;
    this.colores=["white","black","red"];
    this.mapa=null;
    
    this.jugador=pos;
    this.muerto=false;
    this.puntos=0;
    
    this.canvas.width=this.ancho*this.ladoCelda;
    this.canvas.height=this.alto*this.ladoCelda;
    
    this.generarMapa();
    this.mapa[this.jugador[0]][this.jugador[1]]=2;
    this.run();
}
TRON.prototype.generarMapa=function()
{
    this.mapa=[];
    for (var y=0;y<this.alto;y++)
    {
        var arr=[];
        for (var x=0;x<this.ancho;x++)
        {
            if (y==0 || y==this.alto-1 || x==0 || x==this.ancho-1) arr.push(1);
            else arr.push(0);
        }
        this.mapa.push(arr);
    }
}
TRON.prototype.dibujar=function()
{
    var ny=this.mapa.length;
    var nx=this.mapa[0].length;
    for (var x=0;x<nx;x++)
    {
        for (var y=0;y<ny;y++)
        {
            this.ctx.fillStyle=this.colores[this.mapa[y][x]];
            this.ctx.strokeStyle="#333";
            this.ctx.lineWidth=0.2;
            this.ctx.fillRect(x*this.ladoCelda,y*this.ladoCelda,this.ladoCelda,this.ladoCelda);
            this.ctx.strokeRect(x*this.ladoCelda,y*this.ladoCelda,this.ladoCelda,this.ladoCelda);
        }
    }
};
TRON.prototype.run=function()
{
    var self=this;
    
    var direccion=this.ia();
    this.mover(direccion);
    
    this.mapa[this.jugador[0]][this.jugador[1]]=2;
    this.dibujar();
    
    if (!this.muerto) setTimeout(function(){ self.run(); },self.timer);
    else alert("¡MUERTO! Puntos: "+this.puntos);
};
TRON.prototype.mover=function(direccion)
{
    this.puntos++;
    switch(direccion)
    {
        case DIRECCION.arriba:
            this.jugador[0]--;
            break;
        case DIRECCION.derecha:
            this.jugador[1]++;
      ...