James, a crazy robot

by Farzad YZ

HTML

<div id="game"></div>

SCSS

#game {
  position: relative;
  margin: 20px auto;
}

.robot {
  background-image: url(https://image.ibb.co/dr9pFm/robot.jpg);
  background-repeat: no-repeat;
  background-position: center;
  width: 160px;
  height: 160px;
  position: absolute;
  top: 0;
  left: 0;
  transition: 100ms ease;
}

Babel + JSX

function randomFromArray(array) {
  return array[Math.floor(Math.random() * array.length)];
}

function toPixel(num) {
	return `${num}px`;
}

class Robot {
  static VALID_DIRS = ['RIGHT', 'LEFT', 'BOTTOM', 'UP'];

  constructor(name, stepsLength = 1) {
    this.name = name;
    this.x = 0;
    this.y = 0;
    this.stepsLength = stepsLength; // 1px to move on every step
    this.mover = null;
    this.bound = false; // Bound to parent container
    this.elem = null;
    this.speed = 100; // Milliseconds
  }
  
  getTop() {
  	return this.y;
  }
  setTop(top) {
  	this.elem.style.top = toPixel(top);
  }
  
  getLeft() {
  	return this.x;
  }
  setLeft(left) {
  	this.elem.style.left = toPixel(left);
  }
  
  draw() {
  	const $robot = document.createElement('div');
    $robot.className = 'robot';
    $robot.id = `robot-${this.name}`;
    
    // Styles
    $robot.style.top = toPixel(0);
    $robot.style.left = toPixel(0);
    
    // Save for reference
    this.elem = $robot;
    // Append to DOM
    document.getElementById('game').appendChild($robot);
  }

  goCrazy() {
    this.mover = setInterval(() => {
      this.move(randomFromArray(Robot.VALID_DIRS));
    }, this.speed);
  }

  stop() {
    if (this.mover) {
      clearInterval(this.mover);
      this.mover = null;
    }
  }

  move(dir) {
    if (!Robot.VALID_DIRS.includes(dir)) {
      throw Error(`Invalid dir on robot: ${this.name}`);
    }
    
    if(!this.elem) {
    	this.draw();
    }
    
    console.log(`Moving to ${dir}`);
    const threshold = this.stepsLength;
    switch (dir) {
      case 'UP':
        this.setTop(this.getTop() - threshold);
        this.y -= threshold;
        break;
      case 'RIGHT':
        this.setLeft(this.getLeft() + threshold);
        this.x += threshold;
        break;
      case 'BOTTOM':
        this.setTop(this.getTop() + threshold);
        this.y += threshold;
        break;
      case 'LEFT':
        this.setLeft(this.getLeft() - threshold);
        this.x -=...