以下が実際のプログラムです。セキュリティ上の問題を避けるため、evalを使ったり、外部サイトへのリダイレクトをするような処理はしていません。
<!DOCTYPE html>
<html>
<head>
<title>タップジャンプ</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="640" height="480"></canvas>
<script>
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
// オブジェクトの定義
var player = {
x: 100,
y: canvas.height / 2,
speed: 0,
jumping: false,
jumpHeight: 0,
jumpDuration: 0,
width: 50,
height: 50
}
var garbage = {
x: canvas.width,
y: 50,
speed: 5,
width: 50,
height: 50
}
var score = 0;
// キー操作のイベントハンドラ
document.addEventListener("keydown", function (evt) {
if (evt.keyCode == 32) { // スペースキーが押された
if (!player.jumping) {
player.jumping = true;
player.jumpDuration = 0;
}
}
});
// メインループ
var main = function () {
// 画面のクリア
ctx.clearRect(0, 0, canvas.width, canvas.height);
// ゴミの移動
garbage.x -= garbage.speed;
if (garbage.x < -garbage.width) {
garbage.x = canvas.width;
}
// プレーヤーのジャンプ
if (player.jumping) {
player.jumpDuration++;
if (player.jumpDuration > 30) {
player.jumpHeight = 0;
player.speed = 0;
player.jumping = false;
} else {
player.jumpHeight = Math.sin(player.jumpDuration * Math.PI / 30) * 100;
player.speed = -2 + 0.2 * player.jumpDuration;
}
}
// プレーヤーの移動
player.y += player.speed;
// プレーヤーが画面外に出ないようにする
if (player.y + player.jumpHeight > canvas.height - player.height) {
player.y = canvas.height - player.height - player.jumpHeight;
player.speed = 0;
player.jumping = false;
}
// 衝突判定
if (Math.abs(player.x - garbage.x) < player.width && Math.abs(player.y - garbage.y - garbage.height) < player.height) {
score++;
garbage.x = canvas.width;
}
// 描画
ctx.fillStyle = "green";
ctx.fillRect(player.x, player.y + player.jumpHeight, player.width, player.height);
ctx.fillStyle = "gray";
ctx.fillRect(garbage.x, garbage.y, garbage.width, garbage.height);
ctx.fillStyle = "black";
ctx.font = "24px sans-serif";
ctx.fillText("Score: " + score, 10, 30);
// ループの再帰呼び出し
window.requestAnimationFrame(main);
}
// ゲームの開始
main();
</script>
</body>
</html>
※このプログラムは、スペースキーを押すことでプレーヤーがジャンプし、流れてくるゴミをよけながらスコアを稼ぐゲームです。ゴミにぶつかってもゲームオーバーにならないようになっています。