网页版羊了个羊游戏代码 - 开始和结束功能实现
羊了个羊游戏
点击开始游戏按钮开始游戏,找到所有隐藏的羊儿并点击,不要点击其他物品。
<script>
var score = 0;
var totalSheep = 10;
function startGame() {
score = 0;
totalSheep = 10;
document.getElementById('scoreArea').innerHTML = '得分:' + score + ' / ' + totalSheep;
document.getElementById('gameArea').innerHTML = '';
for (var i = 0; i < totalSheep; i++) {
var sheep = document.createElement('img');
sheep.setAttribute('src', 'sheep.png');
sheep.setAttribute('id', 'sheep' + i);
sheep.setAttribute('class', 'sheep');
sheep.style.position = 'absolute';
sheep.style.top = Math.floor(Math.random() * 400) + 'px';
sheep.style.left = Math.floor(Math.random() * 600) + 'px';
sheep.onclick = function() {
this.parentNode.removeChild(this);
score++;
document.getElementById('scoreArea').innerHTML = '得分:' + score + ' / ' + totalSheep;
if (score == totalSheep) {
alert('恭喜你找到了所有的羊儿!');
endGame();
}
};
document.getElementById('gameArea').appendChild(sheep);
}
document.getElementById('startBtn').disabled = true;
document.getElementById('endBtn').disabled = false;
}
function endGame() {
score = 0;
totalSheep = 10;
document.getElementById('scoreArea').innerHTML = '';
document.getElementById('gameArea').innerHTML = '';
document.getElementById('startBtn').disabled = false;
document.getElementById('endBtn').disabled = true;
}
</script>
原文地址: https://www.cveoy.top/t/topic/mKr7 著作权归作者所有。请勿转载和采集!