Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
77 lines (72 loc) · 2.75 KB
/
Copy pathscript.js
File metadata and controls
77 lines (72 loc) · 2.75 KB
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
document.addEventListener('DOMContentLoaded', () => {
const loadButton = document.getElementById('loadButton');
loadButton.addEventListener('click', async () => {
const levelInput = document.getElementById('levelInput').value;
const level = parseInt(levelInput);
if (level >= 1 && level <= 20) {
const data = await fetchLeaderboardData(level);
verifyData(data);
renderLeaderboard(level, data);
} else {
alert('Please enter a valid level between 1 and 20.');
}
});
// Function to fetch leaderboard data for a specific level
async function fetchLeaderboardData(level) {
try {
const response = await fetch(`https://game-leaderboard.azurewebsites.net/leaderboard/${level}`);
if (!response.ok) {
throw new Error('Failed to fetch data');
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching leaderboard data:', error);
return [];
}
}
// Function to render leaderboard table
function renderLeaderboard(level, data) {
const container = document.querySelector('.leaderboard');
const table = document.createElement('table');
table.innerHTML = `
<caption>Level ${level} Leaderboard</caption>
<thead>
<tr>
<th>Rank</th>
<th>Player</th>
<th>Time</th>
</tr>
</thead>
<tbody>
${data.map(entry => {
const minutes = Math.floor(entry.time / 60000);
const seconds = Math.floor((entry.time % 60000) / 1000).toFixed(0).padStart(2, '0');
const milliseconds = (entry.time % 1000).toFixed(0).padStart(3, '0');
return `
<tr>
<td>${entry.rank}</td>
<td>${entry.player}</td>
<td>${minutes}:${seconds}:${milliseconds}</td>
</tr>
`}).join('')}
</tbody>
`;
container.innerHTML = ''; // Clear existing content
container.appendChild(table);
}
// Check if data only contains letters and numbers, to prevent XSS attacks
function verifyData(data) {
for (const entry of data) {
for (const key in entry) {
if (typeof entry[key] === 'number') {
continue;
}
if (typeof entry[key] === 'string' && /^[a-zA-Z0-9:]+$/.test(entry[key])) {
continue;
}
throw new Error('Invalid data');
}
}
}
});