JSFiddle - React, Tailwind, and code Playground

by lastuniverse

HTML

<button id="right">вправо</button>
<button id="left">влево</button>
<button id="up">вверх</button>
<button id="down">вниз</button>

<div id="cote">котэ<div/>

CSS

button {
  width: 100px;
  height: 40px;
}

div#cote {
  width: 40px;
  height: 40px;
  background-color: #777;
  border: solid 1px black;
  position: absolute;
}

JavaScript

class Controller{
	constructor(elementId){
  	this.element = document.getElementById(elementId);
    this.isPressed = false;
    this.element.addEventListener('mousedown', (e)=>{
    	this.isPressed = true;
      console.log(elementId,true);
    });
    this.element.addEventListener('mouseup', (e)=>{
    	this.isPressed = false;
      console.log(elementId,false);
    });
  }
}



class Cote{
  constructor(elementId,speed=10,position={x: 100, y: 100}){
  	this.element = document.getElementById(elementId);
    this.setPosition(position);
    this.setSpeed(speed);
    this.draw();
  }
  setSpeed(speed=10){
  	this.speed=speed;
  }
  setPosition({x, y}){
    this.position = {...(this.position||{}), x, y};
  }
  loop(controllers){
  	if(controllers.right.isPressed){
    	this.position.x+=this.speed;
    }
  	if(controllers.left.isPressed){
    	this.position.x-=this.speed;
    }
  	if(controllers.down.isPressed){
    	this.position.y+=this.speed;
    }
  	if(controllers.up.isPressed){
    	this.position.y-=this.speed;
    }
    
		this.draw();
	}
  draw(){
  	this.element.style.left = this.position.x+"px";
    this.element.style.top = this.position.y+"px";  
  }
}




const controllers = {
	right: new Controller("right"),
  left: new Controller("left"),
  up: new Controller("up"),
  down: new Controller("down")
};

const cote = new Cote("cote",1,{x: 100, y: 100});


function loop(){
  cote.loop(controllers);
  window.requestAnimationFrame(loop);
}

loop();