You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何跨用户对比localStorage/cookie数据?实现网页游戏排行榜

解决网页游戏跨用户排行榜的核心问题

首先得明确:localStorage是浏览器本地存储,每个用户的数据只存在自己的设备里,完全做不到跨用户共享或对比——这就是你找不到解决方案的原因,因为这条路走不通。要实现所有用户能看到实时更新的最高分,必须引入后端服务来存储共享数据。

下面是低成本的实现方案,适合小型网页游戏:

1. 搭建轻量后端服务(以Node.js + Express为例)

后端只需要两个核心接口:提交用户分数、获取当前最高分。可以用内存临时存储(重启会丢失,适合测试),或者用SQLite/JSON文件做持久化存储。

后端代码示例:

const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());

// 初始化最高分数据,用JSON文件存储的话可改成读取文件
let topScore = { username: '匿名用户', coins: 0 };

// 提交分数接口
app.post('/submit-score', (req, res) => {
  const { username, coins } = req.body;
  // 简单校验数据合法性
  if (typeof username !== 'string' || typeof coins !== 'number' || coins < 0) {
    return res.json({ success: false, msg: '数据格式错误' });
  }
  if (coins > topScore.coins) {
    topScore = { username, coins };
    // 持久化到JSON文件(可选)
    // const fs = require('fs');
    // fs.writeFileSync('./top-score.json', JSON.stringify(topScore));
  }
  res.json({ success: true, topScore });
});

// 获取最高分接口
app.get('/get-top-score', (req, res) => {
  res.json(topScore);
});

app.listen(3000, () => console.log('后端服务运行在3000端口'));

2. 前端修改逻辑

前端不再依赖localStorage处理跨用户数据,改为和后端交互:

提交用户分数(比如用户金币变化时调用):

async function submitScore(username, coins) {
  try {
    const response = await fetch('http://localhost:3000/submit-score', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, coins })
    });
    const data = await response.json();
    if (data.success) {
      updateTopScoreDisplay(data.topScore);
    }
  } catch (err) {
    console.error('提交分数失败:', err);
  }
}

获取并实时更新最高分:

async function fetchTopScore() {
  try {
    const response = await fetch('http://localhost:3000/get-top-score');
    const topScore = await response.json();
    updateTopScoreDisplay(topScore);
    // 每30秒自动刷新一次最高分
    setTimeout(fetchTopScore, 30000);
  } catch (err) {
    console.error('获取最高分失败:', err);
  }
}

// 页面加载时初始化最高分显示
window.onload = fetchTopScore;

// 更新页面上的最高分展示
function updateTopScoreDisplay(topScore) {
  const displayEl = document.getElementById('top-score');
  displayEl.textContent = `当前最高分:${topScore.username} - ${topScore.coins}金币`;
}

3. 额外注意点

  • 跨域问题:如果前端和后端不在同一域名下,必须在后端配置CORS(上面示例已经用了cors中间件)
  • 防作弊:小游戏可做简单限制,比如同一IP/用户名的提交频率,或者前端计算金币时加个简单哈希签名,后端验证后再更新分数
  • 持久化:内存存储会在后端重启后丢失数据,正式环境建议用SQLite或者本地JSON文件做持久化

内容的提问来源于stack exchange,提问作者fridays18

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 10:58:26