// 排行榜刷新功能
document.addEventListener('DOMContentLoaded', () => {
// 初始加载排行榜
refreshLeaderboard();
// 每60秒刷新一次排行榜
setInterval(refreshLeaderboard, 60000);
// 添加视觉效果
addVisualEffects();
});
// 从服务器获取最新排行榜数据
function refreshLeaderboard() {
fetch('/api/leaderboard')
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
updateLeaderboardUI(data);
})
.catch(error => {
console.error('获取排行榜数据失败:', error);
const tbody = document.getElementById('leaderboard-body');
if (tbody) {
tbody.innerHTML = `
| 获取数据失败: ${error.message} |
`;
}
});
}
// 更新排行榜UI
function updateLeaderboardUI(leaderboardData) {
const tbody = document.getElementById('leaderboard-body');
if (!tbody) return;
// 清空现有内容
tbody.innerHTML = '';
// 限制只显示前100名
const limitedData = leaderboardData.slice(0, 100);
// 获取当前用户名
const currentUser = document.getElementById('username').textContent;
// 添加新数据
limitedData.forEach((user, index) => {
const row = document.createElement('tr');
// 如果是当前用户,添加高亮类
if (user.username === currentUser) {
row.classList.add('current-user');
}
// 添加排名、用户名、分数和游戏次数
row.innerHTML = `
${index + 1} |
${user.username} |
${user.high_score} |
${user.total_games} |
`;
tbody.appendChild(row);
});
// 如果排行榜为空,显示提示信息
if (limitedData.length === 0) {
const emptyRow = document.createElement('tr');
emptyRow.innerHTML = `
尚无数据 |
`;
tbody.appendChild(emptyRow);
}
// 添加提示信息,表明这只是前100名玩家
if (leaderboardData.length > 100) {
const infoRow = document.createElement('tr');
infoRow.innerHTML = `
(仅显示前100名) |
`;
tbody.appendChild(infoRow);
}
// 添加渐入动画效果
const rows = tbody.querySelectorAll('tr');
rows.forEach((row, index) => {
row.style.opacity = '0';
row.style.transform = 'translateY(10px)';
row.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
setTimeout(() => {
row.style.opacity = '1';
row.style.transform = 'translateY(0)';
}, 30 * index); // 每行有细微的延迟,创造级联效果
});
}
// 添加一些视觉效果
function addVisualEffects() {
// 为标题添加光晕效果
const title = document.querySelector('.leaderboard h2');
if (title) {
let intensity = 0;
let increasing = true;
setInterval(() => {
if (increasing) {
intensity += 0.5;
if (intensity >= 10) increasing = false;
} else {
intensity -= 0.5;
if (intensity <= 0) increasing = true;
}
title.style.textShadow = `0 0 ${intensity}px rgba(212, 175, 55, 0.7)`;
}, 100);
}
// 为帝国公告添加打字机效果
const scrollingText = document.querySelector('.scrolling-text p');
if (scrollingText) {
const originalText = scrollingText.textContent;
scrollingText.textContent = '';
let charIndex = 0;
const typeSpeed = 30; // 每个字符的打字速度(毫秒)
function typeWriter() {
if (charIndex < originalText.length) {
scrollingText.textContent += originalText.charAt(charIndex);
charIndex++;
setTimeout(typeWriter, typeSpeed);
}
}
// 开始打字效果
typeWriter();
}
}