Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
194 lines (158 loc) · 4.5 KB
/
Copy pathserver.js
File metadata and controls
194 lines (158 loc) · 4.5 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
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
app.use(cors());
app.use(express.json());
app.use(express.static('public', {
extensions: ['html']
}));
// 比赛项目定义
const PROJECTS = {
'hangman': 'Hangman',
'gridGame': '诗词九宫格',
'soluble_new': '溶解追击战',
'chemical_guess': '化学猜一猜'
};
// 存储选手数据
let players = {};
// 存储项目分数
let projectScores = {};
// 初始化项目分数结构
Object.keys(PROJECTS).forEach(project => {
projectScores[project] = {};
});
// API接口:记录/更新选手项目分数
app.post('/api/score', (req, res) => {
const { playerName, project, score } = req.body;
if (!playerName || !project || typeof score !== 'number') {
return res.status(400).json({
error: '参数错误:需要playerName、project和score'
});
}
if (!PROJECTS[project]) {
return res.status(400).json({
error: `无效的项目: ${project}`
});
}
if(projectScores[project][playerName] === undefined) {
projectScores[project][playerName] = 0;
}
// 更新项目分数
projectScores[project][playerName] += score;
// 更新或添加选手信息
if (!players[playerName]) {
players[playerName] = {
name: playerName,
projects: {}
};
}
// 初始化项目分数
if (!players[playerName].projects[project]) {
players[playerName].projects[project] = 0;
}
players[playerName].projects[project] += score;
players[playerName].lastUpdated = new Date();
// 计算总分数
players[playerName].totalScore = calculateTotalScore(players[playerName]);
// 实时推送更新到所有连接的客户端
io.emit('scoreUpdate', getAllRankings());
res.json({
success: true,
message: `选手 ${playerName} 在${PROJECTS[project]}的分数已增加 ${score}`
});
});
// API接口:添加新选手
app.post('/api/player', (req, res) => {
const { playerName } = req.body;
if (!playerName) {
return res.status(400).json({ error: '需要playerName参数' });
}
if (players[playerName]) {
return res.status(400).json({ error: '选手已存在' });
}
players[playerName] = {
name: playerName,
projects: {},
totalScore: 0,
lastUpdated: new Date()
};
io.emit('scoreUpdate', getAllRankings());
res.json({
success: true,
message: `选手 ${playerName} 已添加`
});
});
// API接口:获取所有排行榜数据
app.get('/api/rankings', (req, res) => {
res.json(getAllRankings());
});
// API接口:重置所有分数
app.post('/api/reset', (req, res) => {
players = {};
// 重置项目分数
Object.keys(PROJECTS).forEach(project => {
projectScores[project] = {};
});
io.emit('scoreUpdate', getAllRankings());
res.json({ success: true, message: '所有分数已重置' });
});
// 计算选手总分数
function calculateTotalScore(player) {
return Object.values(player.projects).reduce((sum, score) => sum + score, 0);
}
// 获取排序后的选手列表
function getSortedPlayers(scoreSource) {
return Object.values(scoreSource)
.sort((a, b) => b.totalScore - a.totalScore)
.map((player, index) => ({
...player,
rank: index + 1
}));
}
// 获取项目排行榜
function getProjectRanking(project) {
const projectPlayers = {};
Object.keys(players).forEach(playerName => {
const player = players[playerName];
if (player.projects[project] !== undefined) {
projectPlayers[playerName] = {
...player,
totalScore: player.projects[project] || 0
};
}
});
return getSortedPlayers(projectPlayers);
}
// 获取所有排行榜数据
function getAllRankings() {
const result = {
total: getSortedPlayers(players),
projects: {}
};
Object.keys(PROJECTS).forEach(project => {
result.projects[project] = getProjectRanking(project);
});
return result;
}
// Socket.io连接处理
io.on('connection', (socket) => {
console.log('客户端已连接:', socket.id);
// 新连接时发送当前排行榜数据
socket.emit('scoreUpdate', getAllRankings());
socket.on('disconnect', () => {
console.log('客户端已断开:', socket.id);
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`服务器运行在端口 ${PORT}`);
});