2D Plane
🐛は原点(0,0)からスタートし、0.05秒ごとに1/2の確率でx軸およびy軸それぞれについて+1または-1した位置に移動する。
これまでに移動した点は直近の20回分プロットする。
以下が実際のプログラムです。セキュリティ面での懸念事項に配慮し、evalを使用しないようにしています。また、alertも使用していないこと、他のサイトに遷移させたりリダイレクトさせるような処理も含まれていないことにも注意してください。
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>2D Plane</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
canvas {
display: block;
margin: auto;
border: 1px solid #ccc;
background-color: white;
}
</style>
</head>
<body>
<h1>2D Plane</h1>
<p>🐛は原点(0,0)からスタートし、0.05秒ごとに1/2の確率でx軸およびy軸それぞれについて+1または-1した位置に移動する。</p>
<p>これまでに移動した点は直近の20回分プロットする。</p>
<canvas id="canvas" width="600" height="600"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var history = [];
var x = 0;
var y = 0;
setInterval(function() {
// 0.5の確率でx軸またはy軸について1または-1移動する
var dx = (Math.random() < 0.5) ? 1 : -1;
var dy = (Math.random() < 0.5) ? 1 : -1;
x += dx;
y += dy;
// 直近の20回分の移動履歴を保持する
history.push({ x: x, y: y });
if (history.length > 20) {
history.shift();
}
// 画面をクリアして再描画する
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(0, canvas.height / 2);
context.lineTo(canvas.width, canvas.height / 2);
context.moveTo(canvas.width / 2, 0);
context.lineTo(canvas.width / 2, canvas.height);
context.strokeStyle = "#999";
context.stroke();
// 履歴をたどってラインを描画する
context.beginPath();
context.moveTo(canvas.width / 2, canvas.height / 2);
for (var i = 0; i < history.length; i++) {
var point = history[i];
var px = canvas.width / 2 + point.x * 10;
var py = canvas.height / 2 - point.y * 10;
context.lineTo(px, py);
}
context.strokeStyle = "#f00";
context.stroke();
}, 50);
</script>
</body>
</html>
```
ジョークとして、🐛の代わりに🐌を使うと、移動速度が1/10になって処理が遅くなるので、実行前に「お腹が空いていたので、スピードが遅くなるかもしれません」と警告するなどのコメントを入れることもできます。