JSFiddle - React, Tailwind, and code Playground

by casebash

HTML

<!DOCTYPE html>
<html>
<head>
  <title>Jump Over Obstacles</title>
</head>
<body>
  <canvas id="gameCanvas" width="800" height="600"></canvas>
  <script src="game.js"></script>
</body>
</html>

JavaScript

const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");

let x = 50;
let y = 50;
let speed = 5;
let jumping = false;
let jumpHeight = 0;

let xVelocity = 0;
let yVelocity = 0;
let gravity = 1;

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  if (jumping) {
    yVelocity = -10;
    jumpHeight += 10;

    if (jumpHeight >= 100) {
      jumping = false;
      jumpHeight = 0;
    }
  }

  // Reset when hitting the ground
  if (y >= 550 && !jumping) {
    y = 550;
    yVelocity = 0;
    jumpHeight = 0; // Reset jumpHeight
  }

  if (y < 550) {
    yVelocity += gravity;
  }

  x += xVelocity;
  y += yVelocity;

  // Keep the ball within the boundaries
  if (x < 25) x = 25;
  if (x > canvas.width - 25) x = canvas.width - 25;
  if (y < 25) y = 25;
  if (y > canvas.height - 25) y = canvas.height - 25;

  // Draw character as a circle
  ctx.beginPath();
  ctx.arc(x, y, 25, 0, Math.PI * 2);
  ctx.fill();
  ctx.closePath();

  // Draw obstacle
  ctx.fillStyle = 'red';
  ctx.fillRect(400, 550, 50, 50);

  // Draw another obstacle
  ctx.fillRect(600, 550, 50, 50);

  ctx.fillStyle = 'black'; // Reset fill color to black

  if (checkCollision()) {
    alert("You lost!");
    resetGame();
  }
  requestAnimationFrame(draw);
}

document.addEventListener("keydown", function(event) {
  switch (event.keyCode) {
    case 37: // Left arrow key
      xVelocity = -speed;
      break;
    case 39: // Right arrow key
      xVelocity = speed;
      break;
    case 32: // Spacebar
      if (!jumping && y >= 549 && y <= 551) { // More tolerant condition
        jumping = true;
        jumpHeight = 0;
      }
      break;
  }
});

document.addEventListener("keyup", function(event) {
  if (event.keyCode === 37 || event.keyCode === 39) {
    xVelocity = 0;
  }
});

function checkCollision() {
  const obstacles = [{
      x: 400,
      y: 550,
      width: 50,
      height: 50
    },
    {
      x: 600,
      y: 550,
      width: 50,
   ...