HTML Pacman Game: Simple and Fun
<!DOCTYPE html>
<html>
<head>
<title>Pacman Game</title>
<style>
#pacman {
position: absolute;
top: 10px;
left: 10px;
width: 10px;
height: 10px;
background-color: yellow;
border-radius: 50%;
}
#food {
position: absolute;
top: 50px;
left: 50px;
width: 10px;
height: 10px;
background-color: red;
}
</style>
</head>
<body>
<div id='pacman'></div>
<div id='food'></div>
<script>
// Move pacman
document.onkeydown = function(e) {
var pacman = document.getElementById('pacman');
switch (e.keyCode) {
case 37: // left
if (pacman.offsetLeft > 0) {
pacman.style.left = pacman.offsetLeft - 10 + 'px';
}
break;
case 38: // up
if (pacman.offsetTop > 0) {
pacman.style.top = pacman.offsetTop - 10 + 'px';
}
break;
case 39: // right
if (pacman.offsetLeft < window.innerWidth - 10) {
pacman.style.left = pacman.offsetLeft + 10 + 'px';
}
break;
case 40: // down
if (pacman.offsetTop < window.innerHeight - 10) {
pacman.style.top = pacman.offsetTop + 10 + 'px';
}
break;
}
<pre><code> // Check if pacman has eaten the food
var food = document.getElementById('food');
if (pacman.offsetLeft == food.offsetLeft && pacman.offsetTop == food.offsetTop) {
food.style.top = Math.floor(Math.random() * window.innerHeight) + 'px';
food.style.left = Math.floor(Math.random() * window.innerWidth) + 'px';
}
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lniH 著作权归作者所有。请勿转载和采集!