<!DOCTYPE html>
<html lang="ja">
<!-- 最初のただの蛇ゲーム 画面外は反対側に出現する 体にあたると4にもどるだけ-->
<head>
<meta charset="UTF-8">
<title>Retro Snake Game</title>
<style>
body {
background-color: #222; /* 背景をダークグレーに */
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
color: white;
font-family: 'Courier New', Courier, monospace;
}
canvas {
border: 2px solid #555; /* ゲーム画面の枠線 */
box-shadow: 0 0 20px rgba(0, 255, 0, 0.2); /* 緑色の光彩効果 */
background-color: #000; /* ゲーム画面の背景は黒 */
}
h2 { margin-bottom: 10px; }
</style>
</head>
<body>
<h2>JavaScript Snake</h2>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<p>矢印キーで移動してください</p>
<script>
window.onload = function() {
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
document.addEventListener("keydown", keyPush);
// 1秒間に15回ゲームを更新(ゲームのスピード)
setInterval(game, 1000 / 15);
}
// ゲームの設定
px = py = 10; // プレイヤーの初期位置 (Player X, Player Y)
gs = 20; // グリッドサイズ (Grid Size: 1マスの大きさ)
tc = 20; // タイルカウント (Tile Count: 縦横のマス数 400px/20px = 20)
ax = ay = 15; // りんごの初期位置 (Apple X, Apple Y)
xv = yv = 0; // 移動速度 (X Velocity, Y Velocity)
trail = []; // ヘビの体の軌跡
tail = 5; // ヘビの初期の長さ
function game() {
// 位置の更新
px += xv;
py += yv;
// 壁を抜けたら反対側から出てくる処理
if (px < 0) px = tc - 1;
if (px > tc - 1) px = 0;
if (py < 0) py = tc - 1;
if (py > tc - 1) py = 0;
// 画面を黒で塗りつぶす(リセット)
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// ヘビを描画
ctx.fillStyle = "lime"; // ヘビの色
for (var i = 0; i < trail.length; i++) {
// ヘビの体を1マスずつ描画(少し隙間を空けてグラフィカルに)
ctx.fillRect(trail[i].x * gs, trail[i].y * gs, gs - 2, gs - 2);
// 自分自身に当たったらゲームオーバー(長さをリセット)
if (trail[i].x == px && trail[i].y == py) {
tail = 5;
}
}
// ヘビの軌跡を更新
trail.push({ x: px, y: py });
while (trail.length > tail) {
trail.shift();
}
// りんごを描画
ctx.fillStyle = "red";
ctx.fillRect(ax * gs, ay * gs, gs - 2, gs - 2);
// りんごを食べたときの処理
if (ax == px && ay == py) {
tail++; // 長さを増やす
// 新しいりんごの位置をランダムに決定
ax = Math.floor(Math.random() * tc);
ay = Math.floor(Math.random() * tc);
}
}
// キー入力の処理
function keyPush(evt) {
switch (evt.keyCode) {
case 37: // 左
xv = -1; yv = 0;
break;
case 38: // 上
xv = 0; yv = -1;
break;
case 39: // 右
xv = 1; yv = 0;
break;
case 40: // 下
xv = 0; yv = 1;
break;
}
}
</script>
</body>
</html>
使用変数
| 20px | |
| ax | |
| ay | |
| canvas | |
| charset | |
| ctx | |
| fillStyle | |
| game -------( Function ) | |
| gs | |
| height | |
| i | |
| id | |
| keyPush -------( Function ) | |
| lang | |
| onload | |
| px | |
| py | |
| tail | |
| tc | |
| trail | |
| width | |
| x | |
| xv | |
| y | |
| yv |