Here's an HTML5 traditional roguelike, "The Glitch Dungeon," where items can truly mess with the game's code and visuals. It's designed to handle these changes without crashing, using function reassignments, variable manipulations, and careful try...catch blocks.
How to Play:
- Goal: Survive as long as you can, explore the dungeon, and experiment with glitch items.
- Movement: Use Numpad keys (8=Up, 2=Down, 4=Left, 6=Right, 7=Up-Left, 9=Up-Right, 1=Down-Left, 3=Down-Right).
- Wait: Numpad 5 to skip a turn.
- Inventory: Press Numpad + to open/close your inventory.
- While inventory is open, use Numpad 8 (Up) and Numpad 2 (Down) to select an item.
- Press Numpad Enter to use the selected item.
- Help: Press Numpad - to toggle the help menu.
- Combat: Just move into an enemy to attack them.
- Items: Move onto an item (?) to pick it up. Be careful, they might glitch your game!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The Glitch Dungeon</title>
<style>
body {
background-color: #1a1a1a;
color: #e0e0e0;
font-family: 'Hack', 'Fira Code', 'Lucida Console', monospace;
display: flex;
justify-content: center;
align-items: flex-start;
min-height: 100vh;
margin: 0;
padding: 20px;
box-sizing: border-box;
flex-wrap: wrap; /* Allow wrapping on smaller screens */
}
#game-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 15px;
margin-right: 20px; /* Space between game and info */
}
canvas {
background-color: #000;
border: 2px solid #555;
image-rendering: pixelated; /* Sharp pixels for retro feel */
}
#info-panel {
width: 300px;
display: flex;
flex-direction: column;
gap: 15px;
}
.panel {
background-color: #2a2a2a;
border: 1px solid #444;
padding: 10px;
border-radius: 5px;
}
#messages, #inventory-display, #help-display, #description-box {
max-height: 200px;
overflow-y: auto;
font-size: 0.9em;
white-space: pre-wrap; /* Preserve formatting for help/desc */
}
#messages p, #inventory-display p {
margin: 0;
padding: 2px 0;
}
#inventory-display .selected {
background-color: #555;
}
h2 {
margin-top: 0;
font-size: 1.2em;
color: #a0a0a0;
}
#help-toggle {
position: absolute;
top: 10px;
right: 10px;
background-color: #333;
color: #eee;
border: none;
padding: 8px 12px;
border-radius: 4px;
cursor: pointer;
}
#help-toggle:hover {
background-color: #444;
}
#controls-panel {
width: 100%;
max-width: 600px;
text-align: center;
margin-top: 20px;
}
#controls-panel table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
font-size: 0.9em;
}
#controls-panel th, #controls-panel td {
border: 1px solid #444;
padding: 8px;
text-align: left;
}
#controls-panel th {
background-color: #3a3a3a;
color: #ccc;
}
@media (max-width: 900px) {
body {
flex-direction: column;
align-items: center;
}
#game-container {
margin-right: 0;
margin-bottom: 20px;
}
#info-panel {
width: 100%;
max-width: 600px;
}
}
</style>
</head>
<body>
<div id="game-container">
<canvas id="gameCanvas"></canvas>
<div id="hp-display" class="panel">
<p>HP: <span id="player-hp">10</span>/<span id="player-max-hp">10</span></p>
</div>
<div id="messages" class="panel">
<h2>Messages</h2>
</div>
</div>
<div id="info-panel">
<div id="inventory-display" class="panel">
<h2>Inventory (Numpad +)</h2>
<p>Press Numpad + to open/close.</p>
</div>
<div id="description-box" class="panel">
<h2>Description</h2>
<p>Hover over items in inventory for description.</p>
</div>
<div id="help-display" class="panel" style="display: none;">
<h2>Help (Numpad -)</h2>
<pre>
Welcome to The Glitch Dungeon!
Your goal is to survive and explore.
Items can profoundly change the game.
CONTROLS:
Numpad 8: Move Up
Numpad 2: Move Down
Numpad 4: Move Left
Numpad 6: Move Right
Numpad 7: Move Up-Left
Numpad 9: Move Up-Right
Numpad 1: Move Down-Left
Numpad 3: Move Down-Right
Numpad 5: Wait (Do Nothing)
Numpad +: Open/Close Inventory
(When open, Numpad 8/2 to select)
(When open, Numpad Enter to Use Item)
Numpad -: Toggle Help Menu
GAME MECHANICS:
- Move into enemies to attack them.
- Move onto items to pick them up.
- Beware: Glitch items can alter
game logic, visuals, or behavior!
The game tries not to crash,
but things might get weird.
Good luck!
</pre>
</div>
</div>
<div id="controls-panel">
<p>Using Numpad for movement and actions. See Help for details.</p>
</div>
<script>
// --- Core Game Setup ---
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const TILE_SIZE = 24; // Size of each character/tile in pixels
const MAP_WIDTH = 40;
const MAP_HEIGHT = 20;
canvas.width = MAP_WIDTH * TILE_SIZE;
canvas.height = MAP_HEIGHT * TILE_SIZE;
let map = [];
let player = {};
let entities = [];
let items = [];
let messages = [];
// Game State Management
const GameState = {
PLAYING: 'playing',
INVENTORY: 'inventory',
HELP: 'help',
DEAD: 'dead'
};
let currentGameState = GameState.PLAYING;
let selectedInventoryItem = 0;
// Glitchable Global Variables and Functions
let playerSightRange = 8;
let gameLoopInterval = null;
let currentLoopDelay = 150; // Milliseconds per turn
let defaultTileColors = {
'.': '#222', // Floor
'#': '#555', // Wall
'@': '#0f0', // Player
'G': '#f00', // Goblin
'?': '#0ff', // Item
' ': '#000' // Fog/Void
};
let inverseControls = false;
let visualGlitchActive = false;
let messageEchoCount = 1;
let entityTeleportChance = 0; // 0-1.0
let itemDropRateMultiplier = 1.0;
// Store original functions for potential reversion or wrapping
const originalGameFunctions = {};
function storeOriginalFunctions() {
originalGameFunctions.drawMap = drawMap;
originalGameFunctions.drawPlayer = drawPlayer;
originalGameFunctions.drawEntities = drawEntities;
originalGameFunctions.addMessage = addMessage;
originalGameFunctions.isWalkable = isWalkable;
originalGameFunctions.getTileAt = getTileAt;
// Add other core functions you might glitch
}
// --- Utility Functions ---
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function addMessage(msg, color = '#eee') {
try {
// Apply glitch effect to messages
for (let i = 0; i < messageEchoCount; i++) {
messages.push({ text: msg, color: color });
}
while (messages.length > 10) { // Keep message log to max 10
messages.shift();
}
updateUI();
} catch (e) {
console.error("Error in addMessage (glitched?):", e);
// Fallback to original if glitched function fails
messages.push({ text: "MESSAGE GLITCH: " + msg, color: '#f88' });
while (messages.length > 10) {
messages.shift();
}
updateUI();
}
}
function isWalkable(x, y) {
try {
if (x < 0 || x >= MAP_WIDTH || y < 0 || y >= MAP_HEIGHT) return false;
const tile = getTileAt(x, y); // Use glitched getTileAt
return tile === '.' || tile === '?' || tile === 'G'; // Can walk on floor, items, or into enemies
} catch (e) {
console.error("Error in isWalkable (glitched?):", e);
// Default safe behavior if glitched function fails
return false;
}
}
function getTileAt(x, y) {
try {
if (x < 0 || x >= MAP_WIDTH || y < 0 || y >= MAP_HEIGHT) return ' '; // Out of bounds is void
return map[y][x];
} catch (e) {
console.error("Error in getTileAt (glitched?):", e);
return ' '; // Default safe behavior if glitched function fails
}
}
function getEntityAt(x, y) {
return entities.find(e => e.x === x && e.y === y);
}
function getItemAt(x, y) {
return items.find(i => i.x === x && i.y === y);
}
// --- Map Generation ---
function generateMap() {
map = Array(MAP_HEIGHT).fill(null).map(() => Array(MAP_WIDTH).fill('#')); // Fill with walls
// Simple room generation
const numRooms = getRandomInt(5, 10);
const rooms = [];
for (let i = 0; i < numRooms; i++) {
const roomW = getRandomInt(5, 12);
const roomH = getRandomInt(5, 10);
const roomX = getRandomInt(1, MAP_WIDTH - roomW - 1);
const roomY = getRandomInt(1, MAP_HEIGHT - roomH - 1);
rooms.push({ x: roomX, y: roomY, w: roomW, h: roomH });
for (let y = roomY; y < roomY + roomH; y++) {
for (let x = roomX; x < roomX + roomW; x++) {
map[y][x] = '.'; // Carve out floor
}
}
}
// Connect rooms with corridors
for (let i = 0; i < rooms.length - 1; i++) {
const r1 = rooms[i];
const r2 = rooms[i + 1];
const p1x = getRandomInt(r1.x, r1.x + r1.w - 1);
const p1y = getRandomInt(r1.y, r1.y + r1.h - 1);
const p2x = getRandomInt(r2.x, r2.x + r2.w - 1);
const p2y = getRandomInt(r2.y, r2.y + r2.h - 1);
// Horizontal corridor
for (let x = Math.min(p1x, p2x); x <= Math.max(p1x, p2x); x++) {
map[p1y][x] = '.';
}
// Vertical corridor
for (let y = Math.min(p1y, p2y); y <= Math.max(p1y, p2y); y++) {
map[y][p2x] = '.';
}
}
// Place player in the first room
const startRoom = rooms[0];
player = {
x: getRandomInt(startRoom.x + 1, startRoom.x + startRoom.w - 2),
y: getRandomInt(startRoom.y + 1, startRoom.y + startRoom.h - 2),
hp: 10,
maxHp: 10,
inventory: [],
damage: 2
};
// Place enemies and items
entities = [];
items = [];
for (let i = 0; i < 5; i++) {
let gx, gy;
do {
gx = getRandomInt(0, MAP_WIDTH - 1);
gy = getRandomInt(0, MAP_HEIGHT - 1);
} while (getTileAt(gx, gy) !== '.' || (gx === player.x && gy === player.y) || getEntityAt(gx, gy));
entities.push(new Enemy(gx, gy, 'Goblin', 'G', '#f00', 5, 2));
}
for (let i = 0; i < 3; i++) { // Fewer items, they're potent!
let ix, iy;
do {
ix = getRandomInt(0, MAP_WIDTH - 1);
iy = getRandomInt(0, MAP_HEIGHT - 1);
} while (getTileAt(ix, iy) !== '.' || (ix === player.x && iy === player.y) || getEntityAt(ix, iy) || getItemAt(ix, iy));
items.push(createRandomGlitchItem(ix, iy));
}
}
// --- Game Entities ---
class Enemy {
constructor(x, y, name, char, color, hp, damage) {
this.x = x;
this.y = y;
this.name = name;
this.char = char;
this.color = color;
this.hp = hp;
this.damage = damage;
}
takeDamage(amount) {
this.hp -= amount;
if (this.hp <= 0) {
addMessage(`${this.name} is defeated!`);
// Randomly drop an item
if (Math.random() < 0.5 * itemDropRateMultiplier) { // 50% chance normally
const droppedItem = createRandomGlitchItem(this.x, this.y);
items.push(droppedItem);
addMessage(`${this.name} dropped a ${droppedItem.name}!`, '#0ff');
}
return true; // Is dead
}
return false; // Not dead
}
act() {
// Simple AI: Move towards player if in range, otherwise random
const dx = player.x - this.x;
const dy = player.y - this.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < playerSightRange + 3) { // Chase if player is somewhat close
let targetX = this.x;
let targetY = this.y;
if (Math.abs(dx) > Math.abs(dy)) {
targetX += Math.sign(dx);
} else {
targetY += Math.sign(dy);
}
this.moveTo(targetX, targetY);
} else { // Random movement
const moveX = getRandomInt(-1, 1);
const moveY = getRandomInt(-1, 1);
this.moveTo(this.x + moveX, this.y + moveY);
}
}
moveTo(newX, newY) {
try {
// Glitched entity teleportation chance
if (Math.random() < entityTeleportChance) {
newX = getRandomInt(0, MAP_WIDTH - 1);
newY = getRandomInt(0, MAP_HEIGHT - 1);
addMessage(`${this.name} flickers and teleports!`, '#f8f');
}
if (originalGameFunctions.isWalkable(newX, newY)) {
const targetEntity = getEntityAt(newX, newY);
if (targetEntity === player) {
player.takeDamage(this.damage);
addMessage(`${this.name} hits you for ${this.damage}!`, '#f88');
} else if (!targetEntity) { // No other entity, just move
this.x = newX;
this.y = newY;
}
}
} catch (e) {
console.error("Error in Enemy.moveTo (glitched?):", e);
// If movement logic glitched, enemy just stays put for a turn
}
}
}
class Item {
constructor(x, y, name, description, glitchFn) {
this.x = x;
this.y = y;
this.name = name;
this.char = '?';
this.color = '#0ff';
this.description = description;
this.glitchFn = glitchFn; // Function to call when used
}
use() {
addMessage(`You use the ${this.name}.`, '#0f0');
try {
this.glitchFn(); // Execute the glitch effect
} catch (e) {
addMessage(`The ${this.name} failed to glitch! Error: ${e.message}`, '#f00');
console.error(`Glitch item '${this.name}' failed:`, e);
}
}
}
// --- Glitch Item Definitions ---
function createRandomGlitchItem(x, y) {
const itemTypes = [
{
name: "Corrupted Lens",
desc: "Focuses your perception in strange ways, changing your sight range.",
glitch: () => {
playerSightRange = getRandomInt(1, 20);
addMessage(`Your sight range is now ${playerSightRange}!`, '#00f');
}
},
{
name: "Warping Potion",
desc: "Speeds up or slows down time itself. May cause disorientation.",
glitch: () => {
currentLoopDelay = Math.max(50, getRandomInt(10, 500)); // Min 50ms, max 500ms
clearInterval(gameLoopInterval);
gameLoopInterval = setInterval(gameLoop, currentLoopDelay);
addMessage(`Time flows at a new pace (${currentLoopDelay}ms/turn)!`, '#f0f');
}
},
{
name: "Color Shift Dust",
desc: "The world's hues seem to... rearrange themselves.",
glitch: () => {
for (const key in defaultTileColors) {
if (key !== '@' && key !== 'G') { // Don't glitch player/enemy colors
defaultTileColors[key] = '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
}
}
addMessage(`The colors of the dungeon shifted!`, '#ff0');
}
},
{
name: "Inverse Logic Chip",
desc: "For a few turns, your movements will be strangely inverted.",
glitch: () => {
inverseControls = !inverseControls; // Toggle for simplicity, or add timer
addMessage(`Movement controls are now ${inverseControls ? 'INVERTED' : 'NORMAL'}!`, '#0f0');
}
},
{
name: "Recursive Echo Stone",
desc: "Causes your messages to echo, and echo, and echo...",
glitch: () => {
messageEchoCount = getRandomInt(1, 3); // 1, 2, or 3 echoes
addMessage(`Your words now echo ${messageEchoCount} time(s)!`, '#8f8');
}
},
{
name: "Visual Glitch Gem",
desc: "The world appears to stutter or distort itself on screen.",
glitch: () => {
visualGlitchActive = !visualGlitchActive; // Toggle visual glitch
if (visualGlitchActive) {
addMessage(`Visual glitches are now active!`, '#f8f');
// Redefine drawMap to add a visual glitch
drawMap = function() {
originalGameFunctions.drawMap(); // Draw original map
ctx.globalAlpha = 0.1 + Math.random() * 0.2; // Semi-transparent overlay
ctx.fillStyle = `hsl(${Math.random() * 360}, 100%, 50%)`; // Random color
ctx.fillRect(0, 0, canvas.width, canvas.height); // Draw a colored rectangle
ctx.globalAlpha = 1.0; // Reset alpha
if (Math.random() < 0.1) { // Occasionally shift the whole canvas
ctx.translate(getRandomInt(-5, 5), getRandomInt(-5, 5));
setTimeout(() => ctx.translate(-getRandomInt(-5, 5), -getRandomInt(-5, 5)), 50); // Shift back
}
};
} else {
addMessage(`Visual glitches have subsided.`, '#8f8');
drawMap = originalGameFunctions.drawMap; // Revert to original drawMap
}
}
},
{
name: "Entropic Shard",
desc: "Entities might randomly flicker out of existence or reappear.",
glitch: () => {
entityTeleportChance = Math.min(0.5, entityTeleportChance + 0.1); // Max 50% chance
addMessage(`Entities might now randomly teleport! Chance: ${Math.round(entityTeleportChance * 100)}%`, '#f80');
}
},
{
name: "Reality Anchor",
desc: "Temporarily stabilizes the code, undoing some glitches.",
glitch: () => {
// Reset some common glitches
addMessage("Reality stabilizes... for now.", "#0f0");
playerSightRange = 8;
currentLoopDelay = 150;
clearInterval(gameLoopInterval);
gameLoopInterval = setInterval(gameLoop, currentLoopDelay);
Object.assign(defaultTileColors, { '.': '#222', '#': '#555', ' ': '#000' });
inverseControls = false;
messageEchoCount = 1;
if (visualGlitchActive) {
visualGlitchActive = false;
drawMap = originalGameFunctions.drawMap;
}
entityTeleportChance = 0;
itemDropRateMultiplier = 1.0;
}
}
];
const chosenType = itemTypes[getRandomInt(0, itemTypes.length - 1)];
return new Item(x, y, chosenType.name, chosenType.desc, chosenType.glitch);
}
// --- Drawing Functions ---
function clearScreen() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = defaultTileColors[' '];
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawChar(char, x, y, color = '#fff') {
ctx.fillStyle = color;
ctx.font = `${TILE_SIZE}px monospace`;
ctx.textBaseline = 'top';
ctx.fillText(char, x * TILE_SIZE, y * TILE_SIZE);
}
function drawMap() {
try {
// This function might be redefined by visualGlitchGem
for (let y = 0; y < MAP_HEIGHT; y++) {
for (let x = 0; x < MAP_WIDTH; x++) {
const dist = Math.sqrt(Math.pow(x - player.x, 2) + Math.pow(y - player.y, 2));
if (dist <= playerSightRange) {
drawChar(map[y][x], x, y, defaultTileColors[map[y][x]]);
} else {
drawChar(' ', x, y, defaultTileColors[' ']); // Fog of war
}
}
}
} catch (e) {
console.error("Error in drawMap (glitched?):", e);
// Fallback to a basic drawing if glitched function fails
for (let y = 0; y < MAP_HEIGHT; y++) {
for (let x = 0; x < MAP_WIDTH; x++) {
drawChar('E', x, y, '#ff0'); // Draw 'E' for Error
}
}
}
}
function drawEntities() {
try {
// This function might be redefined by other glitches
entities.forEach(entity => {
const dist = Math.sqrt(Math.pow(entity.x - player.x, 2) + Math.pow(entity.y - player.y, 2));
if (dist <= playerSightRange) {
drawChar(entity.char, entity.x, entity.y, entity.color);
}
});
} catch (e) {
console.error("Error in drawEntities (glitched?):", e);
// Draw a fallback if glitched function fails
drawChar('!', player.x, player.y, '#f00');
}
}
function drawItems() {
try {
items.forEach(item => {
const dist = Math.sqrt(Math.pow(item.x - player.x, 2) + Math.pow(item.y - player.y, 2));
if (dist <= playerSightRange) {
drawChar(item.char, item.x, item.y, item.color);
}
});
} catch (e) {
console.error("Error in drawItems (glitched?):", e);
// Draw a fallback if glitched function fails
drawChar('?', player.x + 1, player.y, '#f0f');
}
}
function drawPlayer() {
try {
drawChar(player.char || '@', player.x, player.y, defaultTileColors['@']);
} catch (e) {
console.error("Error in drawPlayer (glitched?):", e);
drawChar('X', player.x, player.y, '#f00'); // Draw 'X' for Error
}
}
function redrawGame() {
clearScreen();
drawMap(); // Potentially glitched version
drawItems();
drawEntities(); // Potentially glitched version
drawPlayer(); // Potentially glitched version
}
// --- UI Updates ---
function updateUI() {
document.getElementById('player-hp').textContent = player.hp;
document.getElementById('player-max-hp').textContent = player.maxHp;
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML = '<h2>Messages</h2>' + messages.map(msg => `<p style="color:${msg.color}">${msg.text}</p>`).join('');
messagesDiv.scrollTop = messagesDiv.scrollHeight; // Scroll to bottom
const inventoryDiv = document.getElementById('inventory-display');
inventoryDiv.innerHTML = '<h2>Inventory (Numpad +)</h2>';
if (currentGameState === GameState.INVENTORY) {
if (player.inventory.length === 0) {
inventoryDiv.innerHTML += '<p>Inventory is empty.</p>';
document.getElementById('description-box').innerHTML = '<h2>Description</h2><p>No item selected.</p>';
} else {
player.inventory.forEach((item, index) => {
const p = document.createElement('p');
p.textContent = `${index + 1}. ${item.name}`;
if (index === selectedInventoryItem) {
p.classList.add('selected');
document.getElementById('description-box').innerHTML = `<h2>Description</h2><p>${item.name}</p><p>${item.description}</p>`;
}
inventoryDiv.appendChild(p);
});
}
} else {
inventoryDiv.innerHTML += '<p>Press Numpad + to open/close.</p>';
document.getElementById('description-box').innerHTML = '<h2>Description</h2><p>Hover over items in inventory for description.</p>';
}
}
function toggleHelp() {
const helpDisplay = document.getElementById('help-display');
if (currentGameState === GameState.HELP) {
currentGameState = GameState.PLAYING;
helpDisplay.style.display = 'none';
} else {
currentGameState = GameState.HELP;
helpDisplay.style.display = 'block';
}
redrawGame(); // Redraw game to show/hide help overlay visually if needed
}
function toggleInventory() {
if (currentGameState === GameState.INVENTORY) {
currentGameState = GameState.PLAYING;
} else {
currentGameState = GameState.INVENTORY;
selectedInventoryItem = 0; // Reset selection
}
updateUI();
redrawGame();
}
// --- Player Actions ---
function playerMove(dx, dy) {
let targetX = player.x + dx;
let targetY = player.y + dy;
if (inverseControls) {
targetX = player.x - dx;
targetY = player.y - dy;
}
if (isWalkable(targetX, targetY)) {
const targetEntity = getEntityAt(targetX, targetY);
const targetItem = getItemAt(targetX, targetY);
if (targetEntity) {
// Attack entity
addMessage(`You attack the ${targetEntity.name}!`);
const isDead = targetEntity.takeDamage(player.damage);
if (isDead) {
entities = entities.filter(e => e !== targetEntity);
}
} else if (targetItem) {
// Pick up item
addMessage(`You pick up a ${targetItem.name}.`, '#0ff');
player.inventory.push(targetItem);
items = items.filter(i => i !== targetItem);
player.x = targetX;
player.y = targetY;
} else {
// Move to empty tile
player.x = targetX;
player.y = targetY;
}
return true; // Turn taken
}
return false; // No turn taken
}
player.takeDamage = function(amount) {
this.hp -= amount;
if (this.hp <= 0) {
this.hp = 0;
addMessage("You collapse, the dungeon consumes your code.", '#f00');
currentGameState = GameState.DEAD;
stopLoop();
}
updateUI();
};
// --- Game Loop ---
function gameLoop() {
if (currentGameState === GameState.PLAYING) {
// Player's turn is handled by input.
// This loop is for entity turns.
entities.forEach(entity => {
entity.act();
});
redrawGame();
updateUI();
}
}
function startLoop() {
if (!gameLoopInterval) {
gameLoopInterval = setInterval(gameLoop, currentLoopDelay);
}
}
function stopLoop() {
clearInterval(gameLoopInterval);
gameLoopInterval = null;
}
// --- Input Handling ---
document.addEventListener('keydown', (e) => {
if (currentGameState === GameState.DEAD) return;
let turnTaken = false;
let dx = 0, dy = 0;
const key = e.key;
// Numpad mappings
const numpadMoves = {
'Numpad8': { dx: 0, dy: -1 },
'Numpad2': { dx: 0, dy: 1 },
'Numpad4': { dx: -1, dy: 0 },
'Numpad6': { dx: 1, dy: 0 },
'Numpad7': { dx: -1, dy: -1 },
'Numpad9': { dx: 1, dy: -1 },
'Numpad1': { dx: -1, dy: 1 },
'Numpad3': { dx: 1, dy: 1 },
};
if (currentGameState === GameState.PLAYING) {
if (numpadMoves[key]) {
dx = numpadMoves[key].dx;
dy = numpadMoves[key].dy;
turnTaken = playerMove(dx, dy);
} else if (key === 'Numpad5') { // Wait
addMessage("You wait a turn.");
turnTaken = true;
} else if (key === 'NumpadAdd') { // + key
toggleInventory();
} else if (key === 'NumpadSubtract') { // - key
toggleHelp();
}
} else if (currentGameState === GameState.INVENTORY) {
if (key === 'Numpad8') { // Up
selectedInventoryItem = Math.max(0, selectedInventoryItem - 1);
updateUI();
} else if (key === 'Numpad2') { // Down
selectedInventoryItem = Math.min(player.inventory.length - 1, selectedInventoryItem + 1);
updateUI();
} else if (key === 'NumpadEnter') { // Use item
if (player.inventory.length > 0) {
const itemToUse = player.inventory[selectedInventoryItem];
itemToUse.use();
player.inventory.splice(selectedInventoryItem, 1); // Remove item
selectedInventoryItem = Math.max(0, Math.min(selectedInventoryItem, player.inventory.length - 1));
addMessage(`Used ${itemToUse.name}.`, '#0ff');
toggleInventory(); // Close inventory after use
turnTaken = true;
}
} else if (key === 'NumpadAdd') { // Close inventory
toggleInventory();
}
} else if (currentGameState === GameState.HELP) {
if (key === 'NumpadSubtract') { // Close help
toggleHelp();
}
}
if (turnTaken) {
gameLoop(); // Advance game state
}
});
// --- Game Initialization ---
function initGame() {
storeOriginalFunctions(); // Store original function references first
generateMap();
addMessage("Welcome to The Glitch Dungeon!", '#0f0');
addMessage("Press Numpad - for Help.");
addMessage("Be wary of strange items...", '#ff0');
updateUI();
redrawGame();
startLoop();
}
initGame(); // Start the game!
</script>
</body>
</html>