JSFiddle - React, Tailwind, and code Playground

by Vasilii Chugunov

HTML

<div id="game">
  <div class="score">0</div>
  <div id="stage">
    <div id="man"></div>
    <div id="man2"></div>
  </div>
</div>

CSS

#man {
  position: absolute;
  width: 32px;
  height: 48px;
  background: url(http://untamed.wild-refuge.net/images/rpgxp/discworld/death.png) 0 0;
}

.btn {
  padding: 5px;
  background: #eee;
  border-radius: 30%;
  display: inline;
  cursor: pointer;
}

#man2 {
  width: 32px;
  height: 48px;
  position: absolute;
  background: url(http://untamed.wild-refuge.net/images/rpgxp/discworld/rincewind.png) 0 0;
}

#stage {
  background-color: #eee;
  position: relative;
  overflow: hidden;
}
.score {
  font-size: 20px;
  text-align: center;
}

JavaScript

function Game(jqEl) {
  this.step = 50;
  this.w = 12;
  this.h = 6;
  jqEl.css("width", this.w * this.step + 'px');
  jqEl
  	.find('#stage')
    .css("width", this.w * this.step + 'px')
    .css("height", this.h * this.step + 'px');
	this.scoreEl = jqEl.find('.score');
  this.score = 0;
  this.draw = function() {
		this.scoreEl.html(this.score);
  }
}
var game = new Game($('#game'));
var man = new Man($("#man"), game.step);
var man2 = new Man($("#man2"), game.step);
man2.randomPlace();

function Man(jqEl, step) {
  this.left = 0;
  this.top = 0;
  this.direction = 'bottom';
  this.directions = {
    'bottom': [0, 0],
    'left': [0, 146],
    'right': [0, 96],
    'top': [0, 48]
  }
  this.randomPlace = function() {
    this.left = Math.floor(Math.random() * 12);
    this.top = Math.floor(Math.random() * 6);
  }
  this.goLeft = function() {
    this.left -= 1;
    this.direction = 'left';
  }
  this.goRight = function() {
    this.left += 1;
    this.direction = 'right';
  }
  this.goDown = function() {
    this.top += 1;
    this.direction = 'bottom';
  }
  this.goUp = function() {
    this.top -= 1;
    this.direction = 'top';
  }
  this.draw = function() {
    jqEl
      .css("top", this.top * step + 1 + "px")
      .css("left", this.left * step + 9 + "px")
      .css("background-position", this.directions[this.direction][0] + 'px ' + this.directions[this.direction][1] + 'px')
  }
}

$(document).keyup(function(e) {
  switch (e.keyCode) {
    case 37:
      man.goLeft();
      break;
    case 39:
      man.goRight();
      break;
    case 38:
      man.goUp();
      break;
    case 40:
      man.goDown();
      break;
  }
});

setInterval(function() {
  if ((man.top == man2.top) && (man.left == man2.left)) {
  	game.score += 1;
    man2.randomPlace();
  }
  man.draw();
  man2.draw();
  game.draw();
}, 50)