junkerstock
 ccc0.0.15 

<!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 (Garde System)</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;
}
/* UIエリア */
#uiContainer {
position: absolute;
top: 10px;
width: 100%;
display: flex;
justify-content: center;
gap: 10px;
z-index: 50;
}
.mode-btn {
background: #333; color: white; border: 1px solid #555;
padding: 5px 10px; cursor: pointer; border-radius: 4px;
font-family: monospace; font-size: 12px;
}
.mode-btn.active { background: #00ffcc; color: black; border-color: #00ffcc; }

/* スコアボード修正: GARDE表示を追加 */
#scoreBoard {
font-size: 24px;
margin-top: 40px;
margin-bottom: 10px;
z-index: 20;
text-shadow: 2px 2px 0 #000;
pointer-events: none;
color: #fff;
font-weight: bold;
display: flex;
gap: 20px; /* POINTとGARDEの間隔 */
}
.stat-label { color: #00ffcc; }
.stat-val { color: white; margin-left: 5px; }

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: 80vh;
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;
}

/* ★新機能: ショップメニュー */
#shopMenu {
display: none; /* 初期は非表示 */
position: absolute;
bottom: 12%; /* ステータスメッセージの少し上 */
z-index: 40;
background: rgba(0, 50, 0, 0.8);
padding: 10px 20px;
border: 1px solid #00ffcc;
border-radius: 8px;
text-align: center;
}
#buyGardeBtn {
background: #00ffcc; color: black;
border: none; padding: 10px 15px;
font-family: monospace; font-weight: bold; font-size: 16px;
cursor: pointer; border-radius: 4px;
}
#buyGardeBtn:active { background: #fff; }
#buyGardeBtn:disabled { background: #555; color: #888; cursor: not-allowed; }

</style>
</head>
<body>

<div id="uiContainer">
<button class="mode-btn" onclick="switchLevel('small')">Map: Wide (20px)</button>
<button class="mode-btn" onclick="switchLevel('medium')">Map: Normal (40px)</button>
<button class="mode-btn" onclick="switchLevel('huge')">Map: Zoom (80px)</button>
</div>

<div id="scoreBoard">
<div><span class="stat-label">POINT:</span><span id="scoreVal" class="stat-val">0</span></div>
<div><span class="stat-label">GARDE:</span><span id="gardeVal" class="stat-val">0</span></div>
</div>

<canvas id="gameCanvas"></canvas>

<div id="shopMenu">
<button id="buyGardeBtn" onclick="buyGarde()">GARDE + : 100 POINT</button>
</div>

<div id="statusMessage">家(中央)で待機中...<br>矢印キーで出発</div>

<div id="gameOverScreen">
<h2 style="color:red; margin:0 0 20px 0;">GAME OVER</h2>
<p>Result: <span id="finalScore">0</span> Point</p>
<button id="replayBtn">REPLAY</button>
</div>

<script>
let canvas, ctx;
let gameInterval;

const levels = {
small: { gs: 20, viewTiles: 35, worldSize: 100, food: 40 },
medium: { gs: 40, viewTiles: 19, worldSize: 60, food: 20 },
huge: { gs: 80, viewTiles: 9, worldSize: 30, food: 10 }
};

let currentConfig = levels['huge'];
let gs, viewTiles, worldSize, targetFoodCount;
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 }
};

const baseSize = 80;

function createFallbackGraphic(type) {
const c = document.createElement('canvas');
c.width = baseSize; c.height = baseSize;
const x = c.getContext('2d');
const s = baseSize;

if (type === 'head') {
x.fillStyle = "#228B22"; x.fillRect(0, 0, s, s);
x.fillStyle = "white";
x.fillRect(s*0.2, s*0.2, s*0.25, s*0.25); x.fillRect(s*0.55, s*0.2, s*0.25, s*0.25);
x.fillStyle = "black";
x.fillRect(s*0.25, s*0.25, s*0.1, s*0.1); x.fillRect(s*0.6, s*0.25, s*0.1, s*0.1);
}
else if (type === 'body') {
x.fillStyle = "#32CD32"; x.fillRect(0, 0, s, s);
x.strokeStyle = "#228B22"; x.lineWidth = s * 0.05;
x.strokeRect(s*0.02, s*0.02, s*0.96, s*0.96);
}
else if (type === 'food') {
x.beginPath(); x.arc(s/2, s/2, s/2 - (s*0.1), 0, Math.PI*2);
x.fillStyle = "cyan"; x.fill();
x.lineWidth = s * 0.05; x.strokeStyle = "white"; x.stroke();
}
else if (type === 'obstacle') {
x.fillStyle = "#cc0000"; x.fillRect(0, 0, s, s);
x.strokeStyle = "#550000"; x.lineWidth = s * 0.08;
x.strokeRect(s*0.05, s*0.05, s*0.9, s*0.9);
x.beginPath(); x.strokeStyle = "white"; x.lineWidth = s * 0.08;
x.moveTo(s*0.2, s*0.2); x.lineTo(s*0.8, s*0.8);
x.moveTo(s*0.8, s*0.2); x.lineTo(s*0.2, s*0.8); x.stroke();
}
else if (type === 'house') {
x.fillStyle = "#8B4513";
x.fillRect(s*0.1, s*0.3, s*0.8, s*0.6);
x.fillStyle = "#FFD700";
x.beginPath();
x.moveTo(s*0.05, s*0.35); x.lineTo(s*0.5, s*0.05); x.lineTo(s*0.95, s*0.35);
x.fill();
x.fillStyle = "#444";
x.fillRect(s*0.4, s*0.6, s*0.2, s*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 garde; // ★追加: GARDE値
let foods = [];
let obstacles = [];
let isGameOver = false;
let isResting = true;
let animFrame = 0;
let touchStartX = 0;
let touchStartY = 0;
let deliverySequence = 1;

// ★設定: GARDE購入コスト
const GARDE_COST = 100;

window.onload = function() {
canvas = document.getElementById("gameCanvas");
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());

applyConfig(levels['huge']);
document.querySelectorAll('.mode-btn')[2].classList.add('active');

resetGame();
}

function switchLevel(levelKey) {
applyConfig(levels[levelKey]);
document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
if(levelKey === 'small') document.querySelectorAll('.mode-btn')[0].classList.add('active');
if(levelKey === 'medium') document.querySelectorAll('.mode-btn')[1].classList.add('active');
if(levelKey === 'huge') document.querySelectorAll('.mode-btn')[2].classList.add('active');
resetGame();
}

function applyConfig(cfg) {
currentConfig = cfg;
gs = cfg.gs;
viewTiles = cfg.viewTiles;
worldSize = cfg.worldSize;
targetFoodCount = cfg.food;
canvas.width = viewTiles * gs;
canvas.height = viewTiles * gs;
}

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;
garde = 0; // ★リセット
deliverySequence = 1;
isGameOver = false;
isResting = true;
animFrame = 0;

for(let i=0; i<targetFoodCount; i++) {
spawnFood();
}

updateUI(); // 表示更新
updateStatus("家で待機中...<br>矢印キーで出発");

document.getElementById("gameOverScreen").style.display = "none";
document.getElementById("statusMessage").style.visibility = "visible";
document.getElementById("shopMenu").style.display = "block"; // 最初は家にいるので表示

clearInterval(gameInterval);
gameInterval = setInterval(game, 1000 / 6);
}

// ★新機能: GARDE購入処理
function buyGarde() {
if (score >= GARDE_COST) {
score -= GARDE_COST;
garde++;
updateUI();
updateStatus(`強化完了! GARDE: ${garde}`);
} else {
// ポイント不足(ボタン無効化などで対応済みだが念のため)
}
}

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;
}

// 壁判定 (壁はGARDE対象外=即死とする仕様が一般的ですが、必要ならここもガード可能にできます。今回は「障害物」のみ)
if (px < 0 || px >= worldSize || py < 0 || py >= worldSize) { gameOver(); return; }

// 障害物判定
if (!isResting || (px !== homeX || py !== homeY)) {
for (let i = 0; i < obstacles.length; i++) {
if (px === obstacles[i].x && py === obstacles[i].y) {
// ★変更: GARDE判定
if (garde > 0) {
garde--;
updateUI();
obstacles.splice(i, 1); // 障害物を消す
updateStatus("<b>GARDE発動!</b><br>障害物を破壊しました");
// ゲーム続行
} else {
gameOver(); return;
}
break; // 1ターンに1つ衝突処理
}
}
}

// --- 描画 ---
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 = Math.max(2, gs * 0.1);
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);
}

// 自分の体への衝突はGARDE対象外(即死)とするのが一般的ですが
// ここも防ぎたい場合はここにも if(garde>0)... を入れる必要があります。
// 今回は「障害物にぶつかったとき」という仕様なのでそのままにします。
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);
}

// --- ロジック & UI制御 ---

// 家にいるか判定
if (px === homeX && py === homeY) {
if (trail.length > 0) {
// 納品中
score += deliverySequence;
updateUI();

updateStatus(`納品中... (+${deliverySequence} Pt!)`);
deliverySequence++;
trail.shift();
} else {
// 納品完了・待機中
deliverySequence = 1;
if (!isResting) {
isResting = true;
tail = 0;
updateStatus("休息中... (Safe)<br>矢印キーで再出発");
}
// ★ショップ表示
document.getElementById("shopMenu").style.display = "block";
}
} else {
// 家の外
// ★ショップ非表示
document.getElementById("shopMenu").style.display = "none";

deliverySequence = 1;
trail.push({ x: px, y: py });
while (trail.length > tail) { trail.shift(); }

// ガード発動のメッセージを上書きしないように簡単なチェック
const currentStatus = document.getElementById("statusMessage").innerHTML;
if(!currentStatus.includes("GARDE")) {
updateStatus("探索中...");
}
}

for (let i = 0; i < foods.length; i++) {
if (px === foods[i].x && py === foods[i].y) {
tail++;
score += 1;
updateUI();
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;
}

// UI一括更新関数
function updateUI() {
document.getElementById("scoreVal").innerText = score;
document.getElementById("gardeVal").innerText = garde;

// ボタンの有効/無効切り替え
const btn = document.getElementById("buyGardeBtn");
if (score >= GARDE_COST) {
btn.disabled = false;
btn.innerText = `GARDE + (${GARDE_COST} Pt)`;
} else {
btn.disabled = true;
btn.innerText = `GARDE + (不足: ${GARDE_COST} Pt)`;
}
}

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";
document.getElementById("shopMenu").style.display = "none";
}

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 === "buyGardeBtn") 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
applyConfig -------( Function )
assets
attempt
b
baseSize
bodyImg
btn
buyGarde -------( Function )
c
canvas
centerTileIndex
charset
class
content
createFallbackGraphic -------( Function )
ctx
currentConfig
currentStatus
deliverySequence
disabled
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 )
garde
GARDE_COST
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
levelKey
levels
lineWidth
loaded
name
obstacleImg
obstacles
offsetX
offsetY
onclick
onload
ox
oy
pulseOffsetXY
pulseScale
pulseSize
px
py
resetGame -------( Function )
s
safeZone
scalable
scale
score
spawnFood -------( Function )
spawnObstacle -------( Function )
src
startX
startY
strokeStyle
style
switchLevel -------( Function )
tagName
tail
targetFoodCount
touchStartX
touchStartY
trail
type
updateStatus -------( Function )
updateUI -------( Function )
viewTiles
visibility
width
worldSize
x
xDiff
xv
y
yDiff
yv