dungeon_game / static /scripts.js
broadfield-dev's picture
Rename static/script.js to static/scripts.js
9540d00 verified
raw
history blame
2.25 kB
const socket = io();
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const tileSize = 32;
// Preload images
const images = {
'w': new Image(), 'f': new Image(), 'player': new Image(),
'goblin': new Image(), 'potion': new Image(), 'sword': new Image()
};
images['w'].src = '/static/images/wall.png';
images['f'].src = '/static/images/floor.png';
images['player'].src = '/static/images/player.png';
images['goblin'].src = '/static/images/goblin.png';
images['potion'].src = '/static/images/potion.png';
images['sword'].src = '/static/images/sword.png';
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('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 terrain
for (let y = 0; y < state.terrain.length; y++) {
for (let x = 0; x < state.terrain[y].length; x++) {
ctx.drawImage(images[state.terrain[y][x]], x * tileSize, y * tileSize);
}
}
// Draw entities
for (let y = 0; y < state.entities.length; y++) {
for (let x = 0; x < state.entities[y].length; x++) {
if (state.entities[y][x] && images[state.entities[y][x]]) {
ctx.drawImage(images[state.entities[y][x]], x * tileSize, y * 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');
});