Spaces:
Sleeping
Sleeping
Create static/script.js
Browse files- static/script.js +62 -0
static/script.js
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const socket = io();
|
2 |
+
const canvas = document.getElementById('gameCanvas');
|
3 |
+
const ctx = canvas.getContext('2d');
|
4 |
+
const tileSize = 32;
|
5 |
+
|
6 |
+
// Preload images
|
7 |
+
const images = {
|
8 |
+
'w': new Image(), 'f': new Image(), 'player': new Image(),
|
9 |
+
'goblin': new Image(), 'potion': new Image(), 'sword': new Image()
|
10 |
+
};
|
11 |
+
images['w'].src = '/static/images/wall.png';
|
12 |
+
images['f'].src = '/static/images/floor.png';
|
13 |
+
images['player'].src = '/static/images/player.png';
|
14 |
+
images['goblin'].src = '/static/images/goblin.png';
|
15 |
+
images['potion'].src = '/static/images/potion.png';
|
16 |
+
images['sword'].src = '/static/images/sword.png';
|
17 |
+
|
18 |
+
socket.on('update_game', (state) => {
|
19 |
+
drawGame(state);
|
20 |
+
document.getElementById('health').textContent = state.health;
|
21 |
+
document.getElementById('attack').textContent = state.attack;
|
22 |
+
document.getElementById('inventory').textContent = state.inventory.join(', ');
|
23 |
+
document.getElementById('usePotion').disabled = !state.inventory.includes('potion');
|
24 |
+
if (state.health <= 0) {
|
25 |
+
alert('Game Over! Refresh to restart.');
|
26 |
+
}
|
27 |
+
});
|
28 |
+
|
29 |
+
socket.on('message', (msg) => {
|
30 |
+
const messagesDiv = document.getElementById('messages');
|
31 |
+
messagesDiv.innerHTML += `<p>${msg}</p>`;
|
32 |
+
messagesDiv.scrollTop = messagesDiv.scrollHeight;
|
33 |
+
});
|
34 |
+
|
35 |
+
function drawGame(state) {
|
36 |
+
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
37 |
+
// Draw terrain
|
38 |
+
for (let y = 0; y < state.terrain.length; y++) {
|
39 |
+
for (let x = 0; x < state.terrain[y].length; x++) {
|
40 |
+
ctx.drawImage(images[state.terrain[y][x]], x * tileSize, y * tileSize);
|
41 |
+
}
|
42 |
+
}
|
43 |
+
// Draw entities
|
44 |
+
for (let y = 0; y < state.entities.length; y++) {
|
45 |
+
for (let x = 0; x < state.entities[y].length; x++) {
|
46 |
+
if (state.entities[y][x] && images[state.entities[y][x]]) {
|
47 |
+
ctx.drawImage(images[state.entities[y][x]], x * tileSize, y * tileSize);
|
48 |
+
}
|
49 |
+
}
|
50 |
+
}
|
51 |
+
}
|
52 |
+
|
53 |
+
document.addEventListener('keydown', (e) => {
|
54 |
+
const directions = { 'ArrowUp': 'up', 'ArrowDown': 'down', 'ArrowLeft': 'left', 'ArrowRight': 'right' };
|
55 |
+
if (directions[e.key]) {
|
56 |
+
socket.emit('move', directions[e.key]);
|
57 |
+
}
|
58 |
+
});
|
59 |
+
|
60 |
+
document.getElementById('usePotion').addEventListener('click', () => {
|
61 |
+
socket.emit('use_item', 'potion');
|
62 |
+
});
|