Spaces:
Sleeping
Sleeping
const socket = io(); | |
const canvas = document.getElementById('gameCanvas'); | |
const ctx = canvas.getContext('2d'); | |
const tileSize = 32; | |
// Load sprite sheet (assuming the same 96x64 sprite sheet) | |
const spriteSheet = new Image(); | |
spriteSheet.src = '/static/images/spritesheet.png'; | |
// Map entity types to sprite sheet coordinates (x, y) | |
const spriteMap = { | |
'w': [0, 0], // Wall | |
'f': [32, 0], // Floor | |
'player': [64, 0], // Player | |
'goblin': [0, 32], // Goblin | |
'skeleton': [0, 32], // Reuse goblin sprite for simplicity (update later if needed) | |
'potion': [32, 32], // Potion | |
'sword': [64, 32], // Sword | |
'door': [64, 32] // Reuse sword sprite for door (update later) | |
}; | |
socket.on('update_game', (state) => { | |
drawGame(state); | |
document.getElementById('health').textContent = state.health; | |
document.getElementById('attack').textContent = state.attack; | |
document.getElementById('inventory').textContent = state.inventory.join(', '); | |
document.getElementById('level').textContent = state.level; | |
document.getElementById('usePotion').disabled = !state.inventory.includes('potion'); | |
if (state.health <= 0) { | |
alert('Game Over! Refresh to restart.'); | |
} | |
}); | |
socket.on('message', (msg) => { | |
const messagesDiv = document.getElementById('messages'); | |
messagesDiv.innerHTML += `<p>${msg}</p>`; | |
messagesDiv.scrollTop = messagesDiv.scrollHeight; | |
}); | |
function drawGame(state) { | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
// Draw visible 10x10 area centered on player | |
for (let y = 0; y < state.terrain.length; y++) { | |
for (let x = 0; x < state.terrain[y].length; x++) { | |
const [sx, sy] = spriteMap[state.terrain[y][x] || 'f']; // Default to floor if empty | |
ctx.drawImage(spriteSheet, sx, sy, tileSize, tileSize, x * tileSize, y * tileSize, tileSize, tileSize); | |
} | |
} | |
// Draw entities on top | |
for (let y = 0; y < state.entities.length; y++) { | |
for (let x = 0; x < state.entities[y].length; x++) { | |
if (state.entities[y][x] && spriteMap[state.entities[y][x]]) { | |
const [sx, sy] = spriteMap[state.entities[y][x]]; | |
ctx.drawImage(spriteSheet, sx, sy, tileSize, tileSize, x * tileSize, y * tileSize, tileSize, tileSize); | |
} | |
} | |
} | |
} | |
document.addEventListener('keydown', (e) => { | |
const directions = { 'ArrowUp': 'up', 'ArrowDown': 'down', 'ArrowLeft': 'left', 'ArrowRight': 'right' }; | |
if (directions[e.key]) { | |
socket.emit('move', directions[e.key]); | |
} | |
}); | |
document.getElementById('usePotion').addEventListener('click', () => { | |
socket.emit('use_item', 'potion'); | |
}); | |
// Ensure sprite sheet is loaded before drawing | |
spriteSheet.onload = () => { | |
console.log('Sprite sheet loaded'); | |
}; |