ドジっ娘ジャックのまんぷく日記

11年連れ添った愛犬を癌で亡くし新しい犬を迎え入れてからの思いです。新しい子ドジでおっとりしていて食いしん坊です。

// ゲームオブジェクトを定義 let Player = function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; }; let Obstacle = function(x, y, width, height, speed) { this.x = x; this.y = y; this.width = width; this.height = height; this.speed = speed; }; // ゲームオブジェクトの描画メソッドを定義 Player.prototype.draw = function() { context.fillStyle = '#000'; // プレイヤーの色 context.fillRect(this.x, this.y, this.width, this.height); }; Obstacle.prototype.draw = function() { context.fillStyle = '#f00'; // 障害物の色 context.fillRect(this.x, this.y, this.width, this.height); }; // キャンバスのセットアップ let canvas = document.getElementById('gameCanvas'); let context = canvas.getContext('2d'); canvas.width = 800; // キャンバスの幅 canvas.height = 600; // キャンバスの高さ // ゲームオブジェクトのインスタンスを作成 let player = new Player(375, 550, 50, 50); // プレイヤーの初期位置とサイズ let obstacles = []; // ゲームループ function gameLoop() { // キャンバスをクリア context.clearRect(0, 0, canvas.width, canvas.height); // プレイヤーを描画 player.draw(); // 障害物を描画 for (let i = 0; i < obstacles.length; i++) { let obstacle = obstacles[i]; obstacle.draw(); // 障害物を下に移動 obstacle.y += obstacle.speed; // 障害物がキャンバス外に出たら削除 if (obstacle.y > canvas.height) { obstacles.splice(i, 1); i--; } } // ゲームループを再帰的に呼び出し requestAnimationFrame(gameLoop); } // ゲームループを開始 gameLoop(); // キーボードイベントを監視し、プレイヤーの移動を制御 document.addEventListener('keydown', function(event) { // 左矢印キーまたは'A'キーで左に移動 if (event.keyCode === 37 || event.key === 'a') { player.x -= 10; } // 右矢印キーまたは'D'キーで右に移動 else if (event.keyCode === 39 || event.key === 'd') { player.x += 10; } }); // 新しい障害物を作成して障害物リストに追加 function createObstacle() { let x = Math.random() * (canvas.width - 50); // X座標をランダムに選択 let width = 50; // 障害物の幅 let height = 20; // 障害物の高さ let speed = 2 + Math.random() * 3; // 障害物の速度 let obstacle = new Obstacle(x, 0, width, height, speed); obstacles.push(obstacle); // 一定の時間間隔で新しい障害物を作成 setTimeout(createObstacle, 1000 + Math.random() * 1000); } // 初めに1つの障害物を作成し、その後はタイマーで定期的に新しい障害物を作成 createObstacle();