HTML Pacman Game: Simple and Fun
<!DOCTYPE html>
<html>
<head>
<title>Pacman Game: Simple and Fun</title>
<style type="text/css">
#game {
width: 400px;
height: 400px;
background-color: #000;
position: relative;
}
#pacman {
width: 30px;
height: 30px;
background-color: #FF0;
position: absolute;
}
</style>
</head>
<body>
<div id="game">
<div id="pacman"></div>
</div>
<script type="text/javascript">
var pacman = document.getElementById('pacman');
var game = document.getElementById('game');
var xPosition = 0;
var yPosition = 0;
var speed = 10;
window.addEventListener("keydown", movePacman);
function movePacman(e) {
if (e.keyCode == 37) { //left arrow key
if (xPosition > 0) {
xPosition -= speed;
}
}
if (e.keyCode == 39) { //right arrow key
if (xPosition < game.clientWidth - pacman.clientWidth) {
xPosition += speed;
}
}
if (e.keyCode == 38) { //up arrow key
if (yPosition > 0) {
yPosition -= speed;
}
}
if (e.keyCode == 40) { //down arrow key
if (yPosition < game.clientHeight - pacman.clientHeight) {
yPosition += speed;
}
}
pacman.style.left = xPosition + 'px';
pacman.style.top = yPosition + 'px';
}
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lniD 著作权归作者所有。请勿转载和采集!