realrebelai's picture
Upload 5 files
a776f9d verified
Raw History Blame Contribute Delete
13 kB
import { app } from "../../scripts/app.js";
app.registerExtension({
name: "Comfy.NeonSnake",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "SnakeNode") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined;
const node = this;
setTimeout(() => {
node.setSize([440, 520]);
// --- 1. DOM STRUCTURE ---
const container = document.createElement("div");
Object.assign(container.style, {
display: "flex", flexDirection: "column", alignItems: "center",
backgroundColor: "#050505", width: "100%", height: "100%",
border: "2px solid #333", borderRadius: "8px", boxSizing: "border-box",
fontFamily: "'Courier New', monospace"
});
// HEADER (Score & Level)
const hud = document.createElement("div");
Object.assign(hud.style, {
width: "100%", display: "flex", justifyContent: "space-between",
padding: "10px 20px", color: "#0f0", fontSize: "16px", fontWeight: "bold",
borderBottom: "1px solid #333", boxSizing: "border-box", textShadow: "0 0 5px #0f0"
});
hud.innerHTML = `<span>SCORE: <span id="score">0</span></span> <span>LVL: <span id="lvl">1</span></span>`;
// CANVAS
const canvas = document.createElement("canvas");
canvas.width = 400; canvas.height = 400;
Object.assign(canvas.style, {
backgroundColor: "#000", border: "1px solid #222", marginTop: "10px",
boxShadow: "0 0 20px rgba(0, 255, 0, 0.1)"
});
// CONTROLS (Pause/Reset)
const controls = document.createElement("div");
Object.assign(controls.style, {
display: "flex", gap: "10px", marginTop: "10px", width: "100%", justifyContent: "center"
});
function createBtn(text, color, onClick) {
const b = document.createElement("button");
b.innerText = text;
Object.assign(b.style, {
padding: "8px 20px", border: "none", borderRadius: "4px",
backgroundColor: color, color: "#000", fontWeight: "bold", cursor: "pointer",
fontFamily: "monospace", textTransform: "uppercase"
});
b.onclick = onClick;
return b;
}
const btnPause = createBtn("Pause", "#fb0", () => togglePause());
const btnReset = createBtn("Reset", "#f44", () => resetGame());
controls.appendChild(btnPause);
controls.appendChild(btnReset);
container.appendChild(hud);
container.appendChild(canvas);
container.appendChild(controls);
node.addDOMWidget("snake_game", "game", container, { serialize: false, hideOnZoom: false });
// --- 2. AUDIO ENGINE (8-Bit Synth) ---
let audioCtx = null;
let isMuted = false;
function initAudio() {
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
if (audioCtx.state === 'suspended') audioCtx.resume();
}
function playTone(freq, type="square", duration=0.1) {
if(!audioCtx || isMuted) return;
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = type;
osc.frequency.setValueAtTime(freq, audioCtx.currentTime);
gain.gain.setValueAtTime(0.05, audioCtx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + duration);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start();
osc.stop(audioCtx.currentTime + duration);
}
// Simple looped bassline
let noteIndex = 0;
const melody = [110, 110, 130, 110, 165, 146, 110, 98];
setInterval(() => {
if(game.running && !game.paused) {
playTone(melody[noteIndex % melody.length], "triangle", 0.1);
noteIndex++;
}
}, 200); // 300bpm
// --- 3. GAME ENGINE ---
const ctx = canvas.getContext("2d");
const GRID = 20;
const TILE_COUNT = 20;
let game = {
running: false,
paused: false,
score: 0,
level: 1,
speed: 100, // ms per frame
lastTime: 0,
color: "#0f0" // Snake color
};
let snake = [];
let apple = {x: 15, y: 15};
let velocity = {x: 0, y: 0};
let inputQueue = []; // Buffer inputs to prevent self-collision
function resetGame() {
initAudio();
snake = [{x: 10, y: 10}, {x: 10, y: 11}, {x: 10, y: 12}];
velocity = {x: 0, y: -1};
game.score = 0;
game.level = 1;
game.speed = 120;
game.color = "#0f0";
game.running = true;
game.paused = false;
placeApple();
updateHud();
btnPause.innerText = "PAUSE";
}
function togglePause() {
game.paused = !game.paused;
btnPause.innerText = game.paused ? "RESUME" : "PAUSE";
}
function placeApple() {
apple.x = Math.floor(Math.random() * TILE_COUNT);
apple.y = Math.floor(Math.random() * TILE_COUNT);
// Don't spawn on snake
if(snake.some(s => s.x === apple.x && s.y === apple.y)) placeApple();
}
function updateHud() {
container.querySelector("#score").innerText = game.score;
container.querySelector("#lvl").innerText = game.level;
canvas.style.boxShadow = `0 0 20px ${game.color}44`; // Glow matches level
hud.style.color = game.color;
hud.style.textShadow = `0 0 5px ${game.color}`;
}
// --- 4. INPUT HANDLING (Gamepad + Keyboard) ---
// Keyboard
document.addEventListener("keydown", (e) => {
if(!game.running) return;
const k = e.key;
const lastV = inputQueue.length > 0 ? inputQueue[inputQueue.length-1] : velocity;
if((k === "ArrowUp" || k === "w") && lastV.y === 0) inputQueue.push({x:0, y:-1});
if((k === "ArrowDown" || k === "s") && lastV.y === 0) inputQueue.push({x:0, y:1});
if((k === "ArrowLeft" || k === "a") && lastV.x === 0) inputQueue.push({x:-1, y:0});
if((k === "ArrowRight" || k === "d") && lastV.x === 0) inputQueue.push({x:1, y:0});
});
// Gamepad Poll
function pollGamepad() {
const pads = navigator.getGamepads();
const gp = pads[0];
if(!gp) return;
const lastV = inputQueue.length > 0 ? inputQueue[inputQueue.length-1] : velocity;
// D-Pad or Stick thresholds
if ((gp.axes[1] < -0.5 || gp.buttons[12].pressed) && lastV.y === 0) inputQueue.push({x:0, y:-1});
if ((gp.axes[1] > 0.5 || gp.buttons[13].pressed) && lastV.y === 0) inputQueue.push({x:0, y:1});
if ((gp.axes[0] < -0.5 || gp.buttons[14].pressed) && lastV.x === 0) inputQueue.push({x:-1, y:0});
if ((gp.axes[0] > 0.5 || gp.buttons[15].pressed) && lastV.x === 0) inputQueue.push({x:1, y:0});
}
// --- 5. MAIN LOOP ---
function loop(timestamp) {
requestAnimationFrame(loop);
pollGamepad();
if (!game.running || game.paused) return;
// Speed Control
if (timestamp - game.lastTime < game.speed) return;
game.lastTime = timestamp;
// Process Input
if(inputQueue.length > 0) velocity = inputQueue.shift();
// Move Snake
const head = { x: snake[0].x + velocity.x, y: snake[0].y + velocity.y };
// Wall Collision (Wrap or Die? Let's Die for challenge)
if (head.x < 0 || head.x >= TILE_COUNT || head.y < 0 || head.y >= TILE_COUNT ||
snake.some(s => s.x === head.x && s.y === head.y)) {
// Game Over
game.running = false;
playTone(150, "sawtooth", 0.5); // Death sound
btnPause.innerText = "GAME OVER";
return;
}
snake.unshift(head);
// Eat Apple
if (head.x === apple.x && head.y === apple.y) {
game.score += 10;
playTone(600 + (game.level*50), "square", 0.1); // Eat sound
placeApple();
// Level Up every 50 points (5 apples)
if(game.score % 50 === 0) {
game.level++;
game.speed = Math.max(50, game.speed - 10); // Speed cap at 50ms
// Shift Color
const hues = ["#0f0", "#0ff", "#f0f", "#f00", "#ff0", "#fff"];
game.color = hues[(game.level-1) % hues.length];
updateHud();
}
} else {
snake.pop(); // Remove tail
}
// Draw
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw Apple
ctx.fillStyle = "#f00";
ctx.shadowBlur = 15;
ctx.shadowColor = "#f00";
ctx.fillRect(apple.x * GRID + 2, apple.y * GRID + 2, GRID - 4, GRID - 4);
// Draw Snake
ctx.shadowBlur = 0;
snake.forEach((part, index) => {
ctx.fillStyle = index === 0 ? "#fff" : game.color; // Head is white
ctx.fillRect(part.x * GRID + 1, part.y * GRID + 1, GRID - 2, GRID - 2);
});
}
// Start
resetGame();
requestAnimationFrame(loop);
}, 100);
return r;
};
}
}
});