yong html css js 做一个简单的超级马里奥游戏
时间: 2024-02-23 14:03:18 浏览: 20
好的,以下是一个简单的超级马里奥游戏示例,使用HTML、CSS、JS实现。
HTML:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>超级马里奥游戏</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="game-container">
<div class="game-board">
<div class="player"></div>
<div class="coin"></div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
```
CSS:
```
.game-container {
width: 600px;
height: 400px;
margin: 0 auto;
overflow: hidden;
}
.game-board {
position: relative;
width: 1000px;
height: 400px;
background: #ffffff;
}
.player {
position: absolute;
bottom: 0;
width: 50px;
height: 50px;
background-image: url('mario.png');
background-size: 100% 100%;
}
.coin {
position: absolute;
top: 50px;
right: 50px;
width: 30px;
height: 30px;
background-image: url('coin.png');
background-size: 100% 100%;
}
```
JS:
```
var player = document.querySelector(".player");
var coin = document.querySelector(".coin");
var gameBoard = document.querySelector(".game-board");
var score = 0;
// 监听键盘事件
document.addEventListener("keydown", function(event) {
if (event.code === "ArrowLeft") {
moveLeft();
} else if (event.code === "ArrowRight") {
moveRight();
} else if (event.code === "ArrowUp") {
jump();
}
});
// 左移
function moveLeft() {
var leftPosition = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
if (leftPosition > 0) {
player.style.left = leftPosition - 5 + "px";
}
}
// 右移
function moveRight() {
var leftPosition = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
if (leftPosition < 950) {
player.style.left = leftPosition + 5 + "px";
}
}
// 跳跃
function jump() {
var bottomPosition = parseInt(window.getComputedStyle(player).getPropertyValue("bottom"));
if (bottomPosition < 350) {
player.style.bottom = bottomPosition + 50 + "px";
}
setTimeout(function() {
player.style.bottom = "0px";
}, 500);
}
// 检查碰撞
function checkCollision() {
var playerLeft = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
var playerBottom = parseInt(window.getComputedStyle(player).getPropertyValue("bottom"));
var coinLeft = parseInt(window.getComputedStyle(coin).getPropertyValue("left"));
var coinTop = parseInt(window.getComputedStyle(coin).getPropertyValue("top"));
if (playerLeft <= coinLeft + 20 && playerLeft >= coinLeft - 20 && playerBottom <= coinTop + 20 && playerBottom >= coinTop - 20) {
score++;
updateScore();
coin.style.display = "none";
setTimeout(function() {
coin.style.display = "block";
}, 2000);
}
}
// 更新得分
function updateScore() {
var scoreBoard = document.createElement("div");
scoreBoard.classList.add("score-board");
scoreBoard.innerText = "得分:" + score;
gameBoard.appendChild(scoreBoard);
}
// 定时检查碰撞
setInterval(function() {
checkCollision();
}, 100);
```
这个简单的超级马里奥游戏示例实现了角色移动、跳跃、金币得分等基本功能。玩家可以使用方向键控制马里奥的移动和跳跃,通过碰到金币得分。需要注意的是,这只是一个非常简单的游戏示例,如果你想制作一个更完整、更复杂的游戏,需要更多的技术和时间。