JSFiddle - React, Tailwind, and code Playground

by danielkwood

JavaScript

setBackdropURL('https://www.codemahal.com/s/grass_background.png');

var player = new Image({
  url: 'https://www.codemahal.com/s/player.png',
  width: 32,
  height: 32,
  x: -100,
  y: 0
})

var enemy = new Image({
  url: 'https://www.codemahal.com/s/enemy.png',
  width: 32,
  height: 32,
  x: 100,
  y: 0
})

forever(() => {
  // this is the start of the forever loop
  if (keysDown.includes('UP')) {
    player.y += 5
  }
   if (keysDown.includes('DOWN')) {
    player.y -= 5
  }
  if (keysDown.includes('LEFT')) {
    player.x -= 5
  }
  if (keysDown.includes('RIGHT')) {
    player.x += 5
  }
  
  if (player.touching(enemy)) {
    score = score + 1
    scoreText.text = "Score: " + score
    enemy.x = random(minX, maxX)
    enemy.y = random(minY, maxY)
  }
  
  if(time===0){
    player.hide()
    enemy.hide()
    gameOverText.show()
    playAgainText.show()
  }
  
  if (keysDown.includes('P')) {
    score = 0
    time = 20
    player.show()
    enemy.show()
    scoreText.text = "Score: 0"
    timerText.text = "Time remaining: 20"
    gameOverText.hide()
    playAgainText.hide()
  }

  // this is the end of the forever loop
})

var scoreText = new Text({
  text: () => "Score: 0",
  x: minX+50,
  y: maxY-20,
  size: 18,
  color: "yellow"
})

var timerText = new Text({
  text: () => "Time remaining: 20",
  x: maxX-90,
  y: maxY-20,
  size: 18,
  color: "yellow"
})

var gameOverText = new Text({
  text: () => "GAME OVER",
  x: 0,
  y: 50,
  size: 45,
  color: "red"
})

var playAgainText = new Text({
  text: () => "Press P to play again",
  x: 0,
  y: 0,
  size: 20,
  color: "blue"
})

var score = 0
var time = 20
gameOverText.hide()
playAgainText.hide()

every(1, 'second', () => {
  if (time!==0) {
    time = time - 1
    timerText.text = "Time remaining: " + time
  }
})