A basic shooting game where players aim and shoot targets on the screen.
Prompt
create a shooting game
HTML
<h1>Shooting Game</h1>
<div id="game-area">
<div id="target"></div>
<div id="hit-count">Hits: 0</div>
</div>
<button id="start-button">Start Game</button>CSS
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
#game-area {
position: relative;
width: 300px;
height: 300px;
border: 2px solid #333;
margin-top: 20px;
background-color: #fff;
}
#target {
position: absolute;
width: 30px;
height: 30px;
background-color: red;
border-radius: 50%;
transition: left 0.5s, top 0.5s;
}
#hit-count {
margin-top: 10px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}JS
(function() {
const gameArea = document.getElementById('game-area');
const target = document.getElementById('target');
const hitCountDisplay = document.getElementById('hit-count');
const startButton = document.getElementById('start-button');
let hits = 0;
let gameInterval;
function getRandomPosition() {
const x = Math.floor(Math.random() * (gameArea.clientWidth - target.offsetWidth));
const y = Math.floor(Math.random() * (gameArea.clientHeight - target.offsetHeight));
return { x, y };
}
function moveTarget() {
const { x, y } = getRandomPosition();
target.style.left = `${x}px`;
target.style.top = `${y}px`;
}
function startGame() {
hits = 0;
hitCountDisplay.textContent = 'Hits: 0';
moveTarget();
gameInterval = setInterval(moveTarget, 1000);
}
function registerHit() {
hits += 1;
hitCountDisplay.textContent = `Hits: ${hits}`;
}
startButton.addEventListener('click', startGame);
target.addEventListener('click', registerHit);
})();Comments (0)
Log in to comment.
Working...