以下は、ユーザーの要望に合わせて作成した横スクロールゲームのサンプルコードです。スマートフォンをタップしている時間に応じてジャンプする高さが変わります。流れてくるゴミをよけながら人が進むゲームです。ゴミにあたってもゲームオーバーにはなりません。
<!DOCTYPE html>
<html>
<head>
<style>
#game-container {
width: 100%;
height: 400px;
overflow: hidden;
position: relative;
background-color: #f1f1f1;
}
#player {
width: 50px;
height: 50px;
position: absolute;
bottom: 0;
left: 50px;
background-color: #ff0000;
}
.obstacle {
width: 50px;
height: 50px;
position: absolute;
background-color: #000000;
}
</style>
</head>
<body>
<div id="game-container">
<div id="player"></div>
</div>
<script>
let tapStartTime;
let playerPositionY = 0;
let playerJumpHeight = 100;
let obstacleSpeed = 2;
let obstacleInterval = 4000;
let obstacleElementId = 0;
function startGame() {
// プレイヤーのジャンプ処理
document.getElementById("game-container").addEventListener("touchstart", function(e) {
tapStartTime = Date.now();
});
document.getElementById("game-container").addEventListener("touchend", function(e) {
let tapEndTime = Date.now();
let tapTime = tapEndTime - tapStartTime;
if (tapTime > 0 && tapTime <= 500) {
playerJumpHeight = 100;
} else if (tapTime > 500 && tapTime <= 1000) {
playerJumpHeight = 200;
} else if (tapTime > 1000) {
playerJumpHeight = 300;
}
});
// ゴミを生成
setInterval(function() {
let obstacleTop = Math.floor(Math.random() * 350) + 1;
let obstacle = document.createElement("div");
obstacle.className = "obstacle";
obstacle.id = "obstacle" + obstacleElementId;
obstacle.style.bottom = obstacleTop + "px";
obstacle.style.left = "100%";
document.getElementById("game-container").appendChild(obstacle);
let obstacleMoveInterval = setInterval(function() {
let obstacleElement = document.getElementById("obstacle" + obstacleElementId);
let obstacleLeft = parseInt(obstacleElement.style.left);
obstacleElement.style.left = (obstacleLeft - obstacleSpeed) + "px";
if (obstacleLeft < -50) {
obstacleElement.parentNode.removeChild(obstacleElement);
clearInterval(obstacleMoveInterval);
}
// 衝突判定
let playerElement = document.getElementById("player");
let obstacleRect = obstacleElement.getBoundingClientRect();
let playerRect = playerElement.getBoundingClientRect();
if (obstacleRect.left < playerRect.right &&
obstacleRect.right > playerRect.left &&
obstacleRect.top < playerRect.bottom &&
obstacleRect.bottom > playerRect.top) {
// 衝突した場合の処理
console.log("怒りのゴミ");
// ゲームオーバーにする処理を書く
}
}, 10);
obstacleElementId++;
}, obstacleInterval);
}
startGame();
</script>
</body>
</html>
ジョーク:なぜプログラマーはゴミをよけるゲームを作るのですか?
答え:彼らは常にエラーを避ける訓練をしているので、それが得意なのです!