JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<title>Arrow Game</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Arrow Game</h1>
<canvas id="game-canvas" width="400" height="400"></canvas>
<script src="arrow-game.js"></script>
</body>
</html>
JavaScript
// get canvas and context
const canvas = document.getElementById("game-canvas");
const ctx = canvas.getContext("2d");
// set initial score
let score = 0;
// create arrow object
const arrow = {
x: 0,
y: 0,
direction: "",
color: ""
};
// create arrow direction array
const directions = ["left", "right", "up", "down"];
// create color array
const colors = ["red", "green", "blue", "yellow", "pink", "purple", "orange"];
// set game state
let gameState = "start";
// set timer variable
let timer = null;
// function to draw arrow on canvas
function drawArrow(x, y, direction, color) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "50px Arial";
ctx.fillStyle = color;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(direction.toUpperCase(), x, y);
}
// function to update arrow direction and position
function updateArrow() {
// set random direction
const index = Math.floor(Math.random() * 4);
arrow.direction = directions[index];
// set random position
switch (arrow.direction) {
case "left":
arrow.x = canvas.width / 2;
arrow.y = canvas.height / 2;
break;
case "right":
arrow.x = canvas.width / 2;
arrow.y = canvas.height / 2;
break;
case "up":
arrow.x = canvas.width / 2;
arrow.y = canvas.height / 2;
break;
case "down":
arrow.x = canvas.width / 2;
arrow.y = canvas.height / 2;
break;
default:
break;
}
// set random color that is different from the previous one
let index2;
do {
index2 = Math.floor(Math.random() * 7);
} while (colors[index2] === arrow.color);
arrow.color = colors[index2];
// draw arrow on canvas
drawArrow(arrow.x, arrow.y, arrow.direction, arrow.color);
// start timer to check if user presses the right key within two seconds
timer = setTimeout(function() {
// if not, end the game and show the game over screen
endGame();
},2000);
}
// function to handle user input
function handleInput(event)...