Subway

 avatar
unknown
plain_text
15 days ago
2.3 kB
4
Indexable
import { useEffect, useRef, useState } from "react";

export default function SubwaySurferClone() {
  const canvasRef = useRef(null);
  const [running, setRunning] = useState(true);
  const [message, setMessage] = useState("");

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    canvas.width = 400;
    canvas.height = 600;

    let player = { x: 180, y: 500, width: 40, height: 40 };
    let obstacle = { x: 180, y: 0, width: 40, height: 40, speed: 5 };

    const draw = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // Player
      ctx.fillStyle = "blue";
      ctx.fillRect(player.x, player.y, player.width, player.height);

      // Obstacle
      ctx.fillStyle = "red";
      ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
    };

    const update = () => {
      obstacle.y += obstacle.speed;

      // Reset obstacle if it goes off screen
      if (obstacle.y > canvas.height) {
        obstacle.y = 0;
        obstacle.x = Math.floor(Math.random() * 360);
      }

      // Check for collision
      if (
        player.x < obstacle.x + obstacle.width &&
        player.x + player.width > obstacle.x &&
        player.y < obstacle.y + obstacle.height &&
        player.height + player.y > obstacle.y
      ) {
        setRunning(false);
        setMessage("g perdu a cause de toi a yanis g izan");
      }
    };

    const gameLoop = () => {
      if (!running) return;
      update();
      draw();
      requestAnimationFrame(gameLoop);
    };

    draw();
    gameLoop();

    const handleKeyDown = (e) => {
      if (e.key === "ArrowLeft" && player.x > 0) {
        player.x -= 40;
      } else if (e.key === "ArrowRight" && player.x < canvas.width - player.width) {
        player.x += 40;
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [running]);

  return (
    <div className="flex flex-col items-center justify-center h-screen">
      <canvas ref={canvasRef} className="border border-black" />
      {!running && (
        <div className="mt-4 text-xl font-bold text-red-600">{message}</div>
      )}
    </div>
  );
}
Editor is loading...
Leave a Comment