html网页小游戏代码
body {
background-color: #f7f7f7;
}
#game-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#target {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
cursor: pointer;
}
#score {
font-size: 24px;
text-align: center;
margin-top: 20px;
}
let score = 0;
function moveTarget() {
const container = document.getElementById('game-container');
const target = document.getElementById('target');
const containerWidth = container.offsetWidth;
const containerHeight = container.offsetHeight;
const targetWidth = target.offsetWidth;
const targetHeight = target.offsetHeight;
const posX = Math.floor(Math.random() * (containerWidth - targetWidth));
const posY = Math.floor(Math.random() * (containerHeight - targetHeight));
target.style.left = posX + 'px';
target.style.top = posY + 'px';
}
function increaseScore() {
score++;
document.getElementById('score').innerHTML = 'Score: ' + score;
}
function startGame() {
const target = document.getElementById('target');
target.addEventListener('click'
function() {
increaseScore();
moveTarget();
});
moveTarget();
}
startGame();
这是一个简单的HTML小游戏代码,游戏页面中央有一个红色方块,玩家需要点击该方块以增加分数。游戏开始后,方块会随机移动到页面的任意位置。每次玩家点击方块后,方块会再次随机移动。玩家的分数会在页面上显示。