File size: 5,276 Bytes
2087e37
d09f4c3
 
 
 
2087e37
8209260
3059061
 
 
8db44f2
3059061
d09f4c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3059061
8db44f2
3059061
 
 
e4f988a
 
b28a497
 
 
 
e4f988a
 
 
fb90e7a
e4f988a
8c20f87
e4f988a
 
 
d09f4c3
e4f988a
 
 
d09f4c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01679d6
d09f4c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c20f87
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
const socket = io("https://broadfield-dev-dungeon-game.hf.space", {
    transports: ['websocket', 'polling'], // Try both WebSocket and polling
    reconnection: true,
    reconnectionAttempts: 5,
    reconnectionDelay: 1000
});

socket.on('connect', () => {
    console.log('Connected to the server! Socket ID:', socket.id);
});

socket.on('connect_error', (error) => {
    console.error('Connection error:', error.message || error);
});

socket.on('connect_timeout', (timeout) => {
    console.error('Connection timeout after', timeout, 'ms');
});

socket.on('reconnect_attempt', (attempt) => {
    console.log('Reconnection attempt #', attempt);
});

socket.on('reconnect_error', (error) => {
    console.error('Reconnection error:', error.message || error);
});

socket.on('reconnect_failed', () => {
    console.error('Reconnection failed after all attempts');
});

socket.on('disconnect', (reason) => {
    console.log('Disconnected from the server. Reason:', reason);
});

socket.on('update_game', (state) => {
    console.log('Received game state:', state);
    window.currentState = state;
    if (allImagesLoaded) drawGame(state);
    else console.log('Waiting for images to load...');
    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) => {
    console.log('Received message:', msg);
    const messagesDiv = document.getElementById('messages');
    messagesDiv.innerHTML += `<p>${msg}</p>`;
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
});

const canvas = document.getElementById('gameCanvas');
console.log('Canvas:', canvas);
if (!canvas) console.error('Canvas element not found');
const ctx = canvas.getContext('2d');
console.log('Context:', ctx);
if (!ctx) console.error('Canvas context not available');
const tileSize = 32;

const images = {
    'w': new Image(), 'f': new Image(), 'player': new Image(),
    'goblin': new Image(), 'skeleton': new Image(), 'potion': new Image(),
    'sword': new Image(), 'door': new Image()
};
images['w'].src = '/static/wall.png';
images['f'].src = '/static/floor.png';
images['player'].src = '/static/player.png';
images['goblin'].src = '/static/goblin.png';
images['skeleton'].src = '/static/goblin.png';
images['potion'].src = '/static/potion.png';
images['sword'].src = '/static/sword.png';
images['door'].src = '/static/door.png';

let allImagesLoaded = false;
let imagesLoaded = 0;
const totalImages = Object.keys(images).length;
for (let key in images) {
    images[key].onload = () => {
        imagesLoaded++;
        console.log(`Loaded image: ${images[key].src}`);
        if (imagesLoaded === totalImages) {
            console.log('All images loaded');
            allImagesLoaded = true;
            if (window.currentState) drawGame(window.currentState);
        }
    };
    images[key].onerror = () => {
        console.error(`Failed to load image: ${images[key].src}`);
    };
    console.log(`Attempting to load: ${images[key].src}`);
}

function drawGame(state) {
    console.log('Drawing game with state:', state);
    ctx.fillStyle = 'red'; // Test with a red background
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    if (!state.terrain || !state.entities) {
        console.warn('State missing terrain or entities:', state);
        return;
    }
    for (let y = 0; y < state.terrain.length; y++) {
        for (let x = 0; x < state.terrain[y].length; x++) {
            const terrainType = state.terrain[y][x] || 'f';
            console.log(`Terrain at (${x},${y}): ${terrainType}`);
            const img = images[terrainType];
            if (img && img.complete) {
                console.log(`Drawing ${terrainType} at (${x},${y})`);
                ctx.drawImage(img, x * tileSize, y * tileSize, tileSize, tileSize);
            } else {
                console.warn(`Image not ready for ${terrainType}`);
            }
        }
    }
    for (let y = 0; y < state.entities.length; y++) {
        for (let x = 0; x < state.entities[y].length; x++) {
            const entityType = state.entities[y][x];
            if (entityType) {
                console.log(`Entity at (${x},${y}): ${entityType}`);
                const img = images[entityType];
                if (img && img.complete) {
                    console.log(`Drawing ${entityType} at (${x},${y})`);
                    ctx.drawImage(img, x * tileSize, y * tileSize, tileSize, tileSize);
                } else {
                    console.warn(`Image not ready for ${entityType}`);
                }
            }
        }
    }
}

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');
});