以下が実際のプログラムです。回避ゲームを楽しんでください!(※alertは使用していません)
```html
<!DOCTYPE html>
<html>
<head>
<title>回避ゲーム</title>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<br>
<button onclick="startGame()">プレイ</button>
<button onclick="showToast("再読み込みしてください")">リセット</button>
<br>
<p id="score_display"></p>
<script>
// グローバル変数
let canvas, ctx, player, fallingObjects, score;
// Playerクラス
class Player {
constructor() {
this.width = 50;
this.height = 50;
this.x = (canvas.width - this.width) / 2;
this.y = canvas.height - this.height;
this.speed = 5;
this.moveLeft = false;
this.moveRight = false;
}
// 左右の移動
move() {
if (this.moveLeft && this.x > 0) {
this.x -= this.speed;
} else if (this.moveRight && this.x < canvas.width - this.width) {
this.x += this.speed;
}
}
}
// FallingObjectクラス
class FallingObject {
constructor() {
this.width = 50;
this.height = 50;
this.x = Math.random() * (canvas.width - this.width);
this.y = 0;
this.speed = 5;
this.scored = false;
}
// 落下
fall() {
this.y += this.speed;
}
// 表示
draw() {
ctx.fillStyle = "brown";
ctx.fillRect(this.x, this.y, this.width, this.height);
}
// 当たり判定
hit() {
return (this.y + this.height >= player.y && this.x <= player.x + player.width && this.x + this.width >= player.x);
}
}
// ゲーム開始
function startGame() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
// 初期化
player = new Player();
fallingObjects = [];
score = 0;
// イベントハンドラ追加
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
// ループ開始
setInterval(gameLoop, 20);
}
// ゲームループ
function gameLoop() {
// 初期化
ctx.clearRect(0, 0, canvas.width, canvas.height);
// プレイヤーの移動
player.move();
// プレイヤーの表示
ctx.fillStyle = "blue";
ctx.fillRect(player.x, player.y, player.width, player.height);
// 落下オブジェクトの落下・表示・当たり判定
for (let i = fallingObjects.length - 1; i >= 0; i--) {
fallingObjects[i].fall();
fallingObjects[i].draw();
// 当たり判定
if (fallingObjects[i].hit()) {
gameOver();
}
// 画面下に消えたオブジェクトはスコア加算
if (fallingObjects[i].y >= canvas.height) {
if (!fallingObjects[i].scored) {
score++;
fallingObjects[i].scored = true;
}
// 画面からオブジェクト削除
fallingObjects.splice(i, 1);
}
}
// スコア表示
document.getElementById("score_display").innerHTML = "Score: " + score;
// オブジェクト生成
if (Math.random() < 0.05) {
fallingObjects.push(new FallingObject());
}
}
// ゲームオーバー
function gameOver() {
document.removeEventListener("keydown", keyDownHandler, false);
document.removeEventListener("keyup", keyUpHandler, false);
alert("💩に当たった! Score: " + score);
showToast("再読み込みしてください");
}
// キーダウンハンドラ
function keyDownHandler(e) {
if (e.code === "ArrowLeft") {
player.moveLeft = true;
} else if (e.code === "ArrowRight") {
player.moveRight = true;
}
}
// キーアップハンドラ
function keyUpHandler(e) {
if (e.code === "ArrowLeft") {
player.moveLeft = false;
} else if (e.code === "ArrowRight") {
player.moveRight = false;
}
}
</script>
</body>
</html>
```