<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>左右移動ゲーム</title> <style> body { margin: 0; overflow: hidden; } #game-container { position: relative; width: 100vw; height: 100vh; background-color: #87CEEB; /* 空色 */ } #character { position: absolute; width: 50px; height: 50px; background-color: #FF4500; /* オレンジ色 */ top: 80%; left: 50%; transform: translateX(-50%); } .item { position: absolute; width: 30px; height: 30px; background-color: #FFD700; /* 金色 */ border-radius: 50%; cursor: pointer; } #score { position: fixed; top: 10px; right: 10px; font-size: 24px; color: #fff; } #timer { position: fixed; top: 10px; left: 10px; font-size: 24px; color: #fff; } #start-button { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 15px; font-size: 20px; background-color: #4CAF50; /* Green */ color: white; border: none; border-radius: 5px; cursor: pointer; } </style> </head> <body> <div id="game-container"> <div id="character"></div> <div id="score">スコア: <span id="score-value">0</span></div> <div id="timer">時間: <span id="timer-value">30</span></div> </div> <button id="start-button" onclick="startGame()">スタート</button> <script> const character = document.getElementById("character"); const gameContainer = document.getElementById("game-container"); const scoreValue = document.getElementById("score-value"); const timerValue = document.getElementById("timer-value"); const startButton = document.getElementById("start-button"); let score = 0; let gameStarted = false; // キャラクターの初期位置 let characterX = window.innerWidth / 2; // キャラクターの移動速度 const characterSpeed = 5; // ゲームループ function gameLoop() { if (gameStarted) { // 一定の間隔でアイテムを生成 if (Math.random() < 0.02) { createItem(); } // キャラクターの位置を更新 character.style.left = characterX + "px"; } // 次のフレームを要求 requestAnimationFrame(gameLoop); } // アイテムを生成する関数 function createItem() { const item = document.createElement("div"); item.className = "item"; item.style.left = Math.random() * (window.innerWidth - 30) + "px"; item.style.top = 0; item.addEventListener("click", () => { score++; scoreValue.textContent = score; gameContainer.removeChild(item); }); gameContainer.appendChild(item); // アイテムが下に移動するアニメーション const itemAnimation = item.animate( [ { top: 0 }, { top: window.innerHeight } ], { duration: 3000, // アイテムが画面を横断するまでの時間 easing: "linear" } ); // アニメーション終了時にアイテムを削除 itemAnimation.onfinish = () => { gameContainer.removeChild(item); }; } // キーボードイベントをリッスン document.addEventListener("keydown", (event) => { if (gameStarted) { if (event.code === "ArrowLeft" && characterX > 0) { characterX -= characterSpeed; } else if (event.code === "ArrowRight" && characterX < window.innerWidth - 50) { characterX += characterSpeed; } } }); // スタートボタンがクリックされたときの処理 function startGame() { score = 0; scoreValue.textContent = score; gameStarted = true; gameLoop(); startButton.style.display = "none";