<!DOCTYPE html>
<html lang="ja">
<!-- 蛇ゲーム 家を追加 -->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Snake Game (Configurable)</title>
<style>
body {
background-color: #111;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
color: white;
font-family: 'Courier New', Courier, monospace;
overflow: hidden;
touch-action: none; user-select: none; -webkit-user-select: none;
}
#scoreBoard {
font-size: 24px;
margin-bottom: 10px;
z-index: 20; /* 前面に表示 */
position: absolute;
top: 20px;
text-shadow: 2px 2px 0 #000;
pointer-events: none; /* クリックを邪魔しない */
}
canvas {
border: 4px solid #333;
background-color: #0a0a0a;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.8);
border-radius: 8px;
max-width: 98vw;
max-height: 85vh;
object-fit: contain;
z-index: 10;
}
#gameOverScreen {
display: none;
position: absolute; top: 50%; left: 50%;
transform: translate(-50%, -50%);
text-align: center;
background-color: rgba(0, 0, 0, 0.9);
padding: 30px; border: 2px solid #fff;
z-index: 30; min-width: 220px; border-radius: 10px;
}
#replayBtn {
padding: 15px 20px; font-size: 20px; cursor: pointer;
background-color: #00ffcc; border: none; width: 100%;
border-radius: 5px; font-weight: bold; margin-top: 20px;
}
#statusMessage {
position: absolute;
bottom: 5%;
color: #fff; /* より見やすく白に */
font-size: 18px;
font-weight: bold;
text-align: center; width: 100%;
text-shadow: 2px 2px 4px #000;
z-index: 20; /* ★ここを追加して最前面へ */
pointer-events: none;
}
</style>
</head>
<body>
<div id="scoreBoard">Score: <span id="scoreVal">0</span></div>
<canvas id="gameCanvas"></canvas>
<div id="statusMessage">家(中央)で待機中...<br>矢印キーで出発</div>
<div id="gameOverScreen">
<h2 style="color:red; margin:0 0 20px 0;">GAME OVER</h2>
<p>Score: <span id="finalScore">0</span></p>
<button id="replayBtn">REPLAY</button>
</div>
<script>
let canvas, ctx;
let gameInterval;
// --- 設定 (可変変数) ---
const gs = 80;
const viewTiles = 9;
// ★ワールドサイズ (初期30)
let worldSize = 30;
// ★維持する餌の数 (初期10)
let targetFoodCount = 10;
// 家の座標
let homeX, homeY;
// --- アセット管理 ---
const assets = {
head: { src: 'head.png', img: new Image(), loaded: false, fallback: null },
body: { src: 'body.png', img: new Image(), loaded: false, fallback: null },
food: { src: 'food.png', img: new Image(), loaded: false, fallback: null },
obstacle: { src: 'obstacle.png', img: new Image(), loaded: false, fallback: null },
house: { src: 'house.png', img: new Image(), loaded: false, fallback: null }
};
function createFallbackGraphic(type) {
const c = document.createElement('canvas');
c.width = gs; c.height = gs;
const x = c.getContext('2d');
if (type === 'head') {
x.fillStyle = "#228B22"; x.fillRect(0, 0, gs, gs);
x.fillStyle = "white";
x.fillRect(gs*0.2, gs*0.2, gs*0.25, gs*0.25); x.fillRect(gs*0.55, gs*0.2, gs*0.25, gs*0.25);
x.fillStyle = "black";
x.fillRect(gs*0.25, gs*0.25, gs*0.1, gs*0.1); x.fillRect(gs*0.6, gs*0.25, gs*0.1, gs*0.1);
}
else if (type === 'body') {
x.fillStyle = "#32CD32"; x.fillRect(0, 0, gs, gs);
x.strokeStyle = "#228B22"; x.lineWidth = gs * 0.05;
x.strokeRect(gs*0.02, gs*0.02, gs*0.96, gs*0.96);
}
else if (type === 'food') {
x.beginPath(); x.arc(gs/2, gs/2, gs/2 - (gs*0.1), 0, Math.PI*2);
x.fillStyle = "cyan"; x.fill();
x.lineWidth = gs * 0.05; x.strokeStyle = "white"; x.stroke();
}
else if (type === 'obstacle') {
x.fillStyle = "#cc0000"; x.fillRect(0, 0, gs, gs);
x.strokeStyle = "#550000"; x.lineWidth = gs * 0.08;
x.strokeRect(gs*0.05, gs*0.05, gs*0.9, gs*0.9);
x.beginPath(); x.strokeStyle = "white"; x.lineWidth = gs * 0.08;
x.moveTo(gs*0.2, gs*0.2); x.lineTo(gs*0.8, gs*0.8);
x.moveTo(gs*0.8, gs*0.2); x.lineTo(gs*0.2, gs*0.8); x.stroke();
}
else if (type === 'house') {
x.fillStyle = "#8B4513";
x.fillRect(gs*0.1, gs*0.3, gs*0.8, gs*0.6);
x.fillStyle = "#FFD700";
x.beginPath();
x.moveTo(gs*0.05, gs*0.35); x.lineTo(gs*0.5, gs*0.05); x.lineTo(gs*0.95, gs*0.35);
x.fill();
x.fillStyle = "#444";
x.fillRect(gs*0.4, gs*0.6, gs*0.2, gs*0.3);
}
return c;
}
function initAssets() {
Object.keys(assets).forEach(type => {
assets[type].fallback = createFallbackGraphic(type);
assets[type].img.onload = () => { assets[type].loaded = true; };
assets[type].img.src = assets[type].src;
});
}
function getAsset(type) { return assets[type].loaded ? assets[type].img : assets[type].fallback; }
// --- ゲーム変数 ---
let px, py;
let xv, yv;
let trail;
let tail;
let score;
let foods = [];
let obstacles = [];
let isGameOver = false;
let isResting = true;
let animFrame = 0;
let touchStartX = 0;
let touchStartY = 0;
window.onload = function() {
canvas = document.getElementById("gameCanvas");
canvas.width = viewTiles * gs;
canvas.height = viewTiles * gs;
ctx = canvas.getContext("2d");
initAssets();
document.addEventListener("keydown", keyPush);
document.addEventListener("touchstart", handleTouchStart, {passive: false});
document.addEventListener("touchend", handleTouchEnd, {passive: false});
document.getElementById("replayBtn").addEventListener("click", resetGame);
resetGame();
}
function resetGame() {
// 変数に基づいて再計算
homeX = Math.floor(worldSize / 2);
homeY = Math.floor(worldSize / 2);
px = homeX;
py = homeY;
xv = 0; yv = 0;
trail = [];
obstacles = [];
foods = [];
tail = 0;
score = 0;
isGameOver = false;
isResting = true;
animFrame = 0;
// ★設定された数だけ餌を生成
for(let i=0; i<targetFoodCount; i++) {
spawnFood();
}
updateScore(0);
updateStatus("家で待機中...<br>矢印キーで出発");
document.getElementById("gameOverScreen").style.display = "none";
document.getElementById("statusMessage").style.visibility = "visible"; // 明示的に表示
clearInterval(gameInterval);
gameInterval = setInterval(game, 1000 / 6);
}
function isNearPlayer(x, y) {
const safeZone = Math.ceil(viewTiles / 2) + 1;
if (Math.abs(x - px) < safeZone && Math.abs(y - py) < safeZone) return true;
return false;
}
function isOccupied(x, y) {
if (x === homeX && y === homeY) return true;
if (isPositionOnSnake(x, y)) return true;
if (x === px && y === py) return true;
for (let f of foods) if (f.x === x && f.y === y) return true;
for (let obs of obstacles) if (obs.x === x && obs.y === y) return true;
return false;
}
function spawnFood() {
let fx, fy; let attempt = 0;
do {
fx = Math.floor(Math.random() * worldSize);
fy = Math.floor(Math.random() * worldSize);
attempt++; if (attempt > 1000) break;
} while(isOccupied(fx, fy) || isNearPlayer(fx, fy));
foods.push({x: fx, y: fy});
}
function spawnObstacle() {
let ox, oy; let attempt = 0;
do {
ox = Math.floor(Math.random() * worldSize);
oy = Math.floor(Math.random() * worldSize);
attempt++; if (attempt > 1000) return;
} while(isOccupied(ox, oy) || isNearPlayer(ox, oy));
obstacles.push({x: ox, y: oy});
}
function game() {
// 移動処理
if (!isResting) {
px += xv; py += yv;
if (px === homeX && py === homeY) {
xv = 0; yv = 0;
}
} else {
xv = 0; yv = 0;
}
// 壁衝突
if (px < 0 || px >= worldSize || py < 0 || py >= worldSize) { gameOver(); return; }
// 障害物衝突 (帰還時は無敵)
if (!isResting || (px !== homeX || py !== homeY)) {
for (let obs of obstacles) { if (px === obs.x && py === obs.y) { gameOver(); return; } }
}
// --- 描画 ---
ctx.fillStyle = "#222"; ctx.fillRect(0, 0, canvas.width, canvas.height);
const centerTileIndex = Math.floor(viewTiles / 2);
const offsetX = centerTileIndex - px;
const offsetY = centerTileIndex - py;
// グリッド
ctx.fillStyle = "#0a0a0a";
ctx.fillRect(offsetX * gs, offsetY * gs, worldSize * gs, worldSize * gs);
ctx.strokeStyle = "#333"; ctx.lineWidth = 1; ctx.beginPath();
let startX = Math.floor(-offsetX) - 1; let endX = startX + viewTiles + 2;
let startY = Math.floor(-offsetY) - 1; let endY = startY + viewTiles + 2;
for (let x = startX; x <= endX; x++) {
if(x >= 0 && x <= worldSize) {
let drawX = (x + offsetX) * gs;
ctx.moveTo(drawX, (0 + offsetY) * gs); ctx.lineTo(drawX, (worldSize + offsetY) * gs);
}
}
for (let y = startY; y <= endY; y++) {
if(y >= 0 && y <= worldSize) {
let drawY = (y + offsetY) * gs;
ctx.moveTo((0 + offsetX) * gs, drawY); ctx.lineTo((worldSize + offsetX) * gs, drawY);
}
}
ctx.stroke();
// ワールド外枠
ctx.strokeStyle = "#cc0000"; ctx.lineWidth = 8;
ctx.strokeRect(offsetX * gs, offsetY * gs, worldSize * gs, worldSize * gs);
// 障害物
animFrame++;
const pulseScale = 1 + 0.05 * Math.sin(animFrame * 0.2);
const pulseSize = gs * pulseScale;
const pulseOffsetXY = (gs - pulseSize) / 2;
const obstacleImg = getAsset('obstacle');
for (let obs of obstacles) {
let drawOx = (obs.x + offsetX) * gs;
let drawOy = (obs.y + offsetY) * gs;
if (drawOx >= -gs && drawOx <= canvas.width && drawOy >= -gs && drawOy <= canvas.height) {
ctx.drawImage(obstacleImg, drawOx + pulseOffsetXY, drawOy + pulseOffsetXY, pulseSize, pulseSize);
}
}
// エサ
const foodImg = getAsset('food');
for (let f of foods) {
let drawFx = (f.x + offsetX) * gs;
let drawFy = (f.y + offsetY) * gs;
if (drawFx >= -gs && drawFx <= canvas.width && drawFy >= -gs && drawFy <= canvas.height) {
ctx.drawImage(foodImg, drawFx, drawFy, gs, gs);
}
}
// 蛇の体
const bodyImg = getAsset('body');
for (var i = 0; i < trail.length; i++) {
let drawTx = (trail[i].x + offsetX) * gs;
let drawTy = (trail[i].y + offsetY) * gs;
if (trail[i].x === homeX && trail[i].y === homeY) continue;
if (drawTx >= -gs && drawTx <= canvas.width && drawTy >= -gs && drawTy <= canvas.height) {
ctx.drawImage(bodyImg, drawTx, drawTy, gs, gs);
}
if (!isResting && trail[i].x == px && trail[i].y == py) { gameOver(); return; }
}
// 蛇の頭
ctx.drawImage(getAsset('head'), (px + offsetX) * gs, (py + offsetY) * gs, gs, gs);
// 家 (最前面)
let drawHomeX = (homeX + offsetX) * gs;
let drawHomeY = (homeY + offsetY) * gs;
if (drawHomeX >= -gs && drawHomeX <= canvas.width && drawHomeY >= -gs && drawHomeY <= canvas.height) {
ctx.drawImage(getAsset('house'), drawHomeX, drawHomeY, gs, gs);
}
// --- ロジック ---
if (px === homeX && py === homeY) {
if (trail.length > 0) {
updateStatus("戦利品を納品中...");
trail.shift();
} else {
if (!isResting) {
isResting = true;
tail = 0;
updateStatus("休息中... (Safe)<br>矢印キーで再出発");
}
}
} else {
trail.push({ x: px, y: py });
while (trail.length > tail) { trail.shift(); }
updateStatus("探索中...");
}
// 捕食判定
for (let i = 0; i < foods.length; i++) {
if (px === foods[i].x && py === foods[i].y) {
tail++;
score += 10;
updateScore(score);
foods.splice(i, 1);
spawnFood();
spawnObstacle();
spawnObstacle();
break;
}
}
}
function isPositionOnSnake(x, y) {
if (!trail) return false;
for (let i = 0; i < trail.length; i++) { if (trail[i].x === x && trail[i].y === y) return true; }
return false;
}
function updateScore(newScore) { document.getElementById("scoreVal").innerText = newScore; }
function updateStatus(msg) {
const el = document.getElementById("statusMessage");
if(el) el.innerHTML = msg;
}
function gameOver() {
isGameOver = true; clearInterval(gameInterval);
document.getElementById("finalScore").innerText = score;
document.getElementById("gameOverScreen").style.display = "block";
document.getElementById("statusMessage").style.visibility = "hidden";
}
function keyPush(evt) {
if (isGameOver) return;
if (isResting) {
const k = evt.keyCode;
if (k >= 37 && k <= 40) isResting = false;
else return;
}
switch (evt.keyCode) {
case 37: if (xv !== 1) { xv = -1; yv = 0; } break;
case 38: if (yv !== 1) { xv = 0; yv = -1; } break;
case 39: if (xv !== -1) { xv = 1; yv = 0; } break;
case 40: if (yv !== -1) { xv = 0; yv = 1; } break;
}
}
function handleTouchStart(evt) {
if(evt.target.id === "gameCanvas" || evt.target.tagName === "BODY") evt.preventDefault();
touchStartX = evt.touches[0].clientX; touchStartY = evt.touches[0].clientY;
}
function handleTouchEnd(evt) {
if (isGameOver) return;
if(evt.target.id === "gameCanvas" || evt.target.tagName === "BODY") evt.preventDefault();
const xDiff = touchStartX - evt.changedTouches[0].clientX;
const yDiff = touchStartY - evt.changedTouches[0].clientY;
if (Math.abs(xDiff) < 10 && Math.abs(yDiff) < 10) return;
if (isResting) isResting = false;
if (Math.abs(xDiff) > Math.abs(yDiff)) {
if (xDiff > 0) { if (xv !== 1) { xv = -1; yv = 0; } } else { if (xv !== -1) { xv = 1; yv = 0; } }
} else {
if (yDiff > 0) { if (yv !== 1) { xv = 0; yv = -1; } } else { if (yv !== -1) { xv = 0; yv = 1; } }
}
}
</script>
</body>
</html>
使用変数
| animFrame | |
| assets | |
| attempt | |
| bodyImg | |
| c | |
| canvas | |
| centerTileIndex | |
| charset | |
| content | |
| createFallbackGraphic -------( Function ) | |
| ctx | |
| display | |
| drawFx | |
| drawFy | |
| drawHomeX | |
| drawHomeY | |
| drawOx | |
| drawOy | |
| drawTx | |
| drawTy | |
| drawX | |
| drawY | |
| el | |
| endX | |
| endY | |
| fallback | |
| fillStyle | |
| foodImg | |
| foods | |
| fx | |
| fy | |
| game -------( Function ) | |
| gameInterval | |
| gameOver -------( Function ) | |
| getAsset -------( Function ) | |
| gs | |
| handleTouchEnd -------( Function ) | |
| handleTouchStart -------( Function ) | |
| height | |
| homeX | |
| homeY | |
| i | |
| id | |
| initAssets -------( Function ) | |
| innerHTML | |
| innerText | |
| isGameOver | |
| isNearPlayer -------( Function ) | |
| isOccupied -------( Function ) | |
| isPositionOnSnake -------( Function ) | |
| isResting | |
| k | |
| keyPush -------( Function ) | |
| lang | |
| lineWidth | |
| loaded | |
| name | |
| obstacleImg | |
| obstacles | |
| offsetX | |
| offsetY | |
| onload | |
| ox | |
| oy | |
| pulseOffsetXY | |
| pulseScale | |
| pulseSize | |
| px | |
| py | |
| resetGame -------( Function ) | |
| safeZone | |
| scalable | |
| scale | |
| score | |
| spawnFood -------( Function ) | |
| spawnObstacle -------( Function ) | |
| src | |
| startX | |
| startY | |
| strokeStyle | |
| style | |
| tagName | |
| tail | |
| targetFoodCount | |
| touchStartX | |
| touchStartY | |
| trail | |
| type | |
| updateScore -------( Function ) | |
| updateStatus -------( Function ) | |
| viewTiles | |
| visibility | |
| width | |
| worldSize | |
| x | |
| xDiff | |
| xv | |
| y | |
| yDiff | |
| yv |