-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
998 lines (855 loc) · 25.4 KB
/
main.go
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
/*
Copyright (c) 2025 TootsCharlie
Snake is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
package main
import (
"bytes"
"compress/gzip"
"crypto/hmac"
crand "crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
_ "github.com/mattn/go-sqlite3"
"github.com/russross/blackfriday/v2"
)
// 添加一个用于提交分数的请求结构体
type ScoreSubmission struct {
Name string `json:"name"`
Score int `json:"score"`
SessionID string `json:"sessionId"`
Timestamp int64 `json:"timestamp"`
Nonce string `json:"nonce"`
Hash string `json:"hash"`
Replay string `json:"replay"`
}
// Score 结构体保持不变,用于数据库存储
type Score struct {
ID int `json:"id"`
Name string `json:"name"`
Score int `json:"score"`
TotalScore int `json:"totalScore"`
PlayCount int `json:"playCount"`
CreatedAt time.Time `json:"createdAt"`
}
// 添加提交分数的响应结构体
type ScoreResponse struct {
IsNewRecord bool `json:"isNewRecord"`
HighScore int `json:"highScore"`
}
// 添加版本记录结构
type VersionInfo struct {
Version string `json:"version"`
Date string `json:"date"`
Content string `json:"content"`
}
// 添加获取版本记录的函数
func getVersions() ([]VersionInfo, error) {
versions := []VersionInfo{}
// 读取 versions 目录
files, err := ioutil.ReadDir("versions")
if err != nil {
return nil, err
}
// 遍历版本文件
for _, file := range files {
if !file.IsDir() && strings.HasSuffix(file.Name(), ".md") {
content, err := ioutil.ReadFile(fmt.Sprintf("versions/%s", file.Name()))
if err != nil {
continue
}
// 解析版本号和日期
version := strings.TrimSuffix(file.Name(), ".md")
date := "" // 从文件内容中解析日期
if match := regexp.MustCompile(`\(([^)]+)\)`).FindStringSubmatch(string(content)); len(match) > 1 {
date = match[1]
}
versions = append(versions, VersionInfo{
Version: version,
Date: date,
Content: string(content),
})
}
}
// 按版本号降序排序
sort.Slice(versions, func(i, j int) bool {
return versions[i].Version > versions[j].Version
})
return versions, nil
}
const (
appName = "snake"
secretKey = "your-secret-key-here"
minInterval = 2
maxTimeDiff = 3
// 会话相关的常量
sessionTimeout = 30 * time.Minute // 会话超时时间
cleanupInterval = 5 * time.Minute // 清理间隔
// 数据库连接池配置
maxOpenConns = 25 // 最大打开连接数
maxIdleConns = 5 // 最大空闲连接数
connMaxLifetime = 5 * time.Minute // 连接最大生命周期
// 作弊检测相关常量
MIN_MOVE_INTERVAL = 30 // 降低最小移动间隔(毫秒)
MAX_PERFECT_MOVES = 100 // 增加允许的完美移动次数
MAX_SCORE_PER_FOOD = 10 // 每个食物最大得分
MIN_GAME_DURATION = 1 // 降低最短游戏时长(秒)
)
var (
db *sql.DB
sessions = make(map[string]sessionInfo)
sessionsMap sync.RWMutex
dbWriteLock sync.Mutex
// 添加模板函数映射
templateFuncs = template.FuncMap{
"markdown": func(content string) template.HTML {
unsafe := blackfriday.Run([]byte(content))
return template.HTML(unsafe)
},
}
)
type sessionInfo struct {
StartTime time.Time
LastScore int
LastSubmit time.Time
ExpiresAt time.Time // 添加过期时间字段
}
// 添加回放步骤结构
type GameStep struct {
Snake []Position `json:"snake"`
Food Position `json:"food"`
Dx int `json:"dx"`
Dy int `json:"dy"`
Score int `json:"score"`
}
type Position struct {
X int `json:"x"`
Y int `json:"y"`
}
// 添加作弊检测结果结构
type CheatDetectionResult struct {
IsValid bool
Reason string
Violations []string
}
// 添加数据库版本控制和迁移功能
const currentDBVersion = 2 // 当前数据库版本
type Migration struct {
Version int
Description string
SQL string
}
// 定义数据库迁移列表
var migrations = []Migration{
{
Version: 1,
Description: "Initial schema",
SQL: `
CREATE TABLE IF NOT EXISTS scores (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
score INTEGER NOT NULL,
replay TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 创建版本控制表
CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
`,
},
{
Version: 2,
Description: "Add play_count column",
SQL: `
ALTER TABLE scores ADD COLUMN play_count INTEGER DEFAULT 0;
-- 更新现有记录的游戏次数
UPDATE scores SET play_count = 1 WHERE play_count IS NULL;
`,
},
{
Version: 3,
Description: "Add total_score column",
SQL: `
ALTER TABLE scores ADD COLUMN total_score INTEGER DEFAULT 0;
-- 初始化总分为当前最高分
UPDATE scores SET total_score = score;
`,
},
}
// 修改数据库初始化函数
func initDB() error {
var err error
// 检查数据库文件是否存在
if _, err := os.Stat("./snake.db"); os.IsNotExist(err) {
fmt.Println("Creating new database file...")
}
// 打开或创建数据库
db, err = sql.Open("sqlite3", "./snake.db")
if err != nil {
return fmt.Errorf("failed to open database: %v", err)
}
// 配置连接池
db.SetMaxOpenConns(maxOpenConns)
db.SetMaxIdleConns(maxIdleConns)
db.SetConnMaxLifetime(connMaxLifetime)
// 启用 WAL 模式以提高并发性能
if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil {
return fmt.Errorf("failed to enable WAL mode: %v", err)
}
// 启用外键约束
if _, err := db.Exec("PRAGMA foreign_keys=ON"); err != nil {
return fmt.Errorf("failed to enable foreign keys: %v", err)
}
// 创建基础表结构
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS scores (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
score INTEGER NOT NULL DEFAULT 0,
total_score INTEGER NOT NULL DEFAULT 0,
play_count INTEGER NOT NULL DEFAULT 0,
replay TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
`)
if err != nil {
return fmt.Errorf("failed to create tables: %v", err)
}
// 初始化一些基础数据(如果表是空的)
var count int
err = db.QueryRow("SELECT COUNT(*) FROM scores").Scan(&count)
if err != nil {
return fmt.Errorf("failed to check scores count: %v", err)
}
return nil
}
// 添加数据库迁移函数
func migrateDB() error {
// 创建迁移表(如果不存在)
_, err := db.Exec(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`)
if err != nil {
return fmt.Errorf("failed to create migrations table: %v", err)
}
// 获取当前数据库版本
var currentVersion int
err = db.QueryRow("SELECT COALESCE(MAX(version), 0) FROM schema_migrations").Scan(¤tVersion)
if err != nil {
return fmt.Errorf("failed to get current database version: %v", err)
}
// 执行待执行的迁移
for _, migration := range migrations {
if migration.Version > currentVersion {
fmt.Printf("Applying migration %d: %s\n", migration.Version, migration.Description)
// 开始事务
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("failed to begin transaction: %v", err)
}
// 执行迁移
if _, err := tx.Exec(migration.SQL); err != nil {
tx.Rollback()
return fmt.Errorf("failed to apply migration %d: %v", migration.Version, err)
}
// 记录迁移版本
if _, err := tx.Exec("INSERT INTO schema_migrations (version) VALUES (?)", migration.Version); err != nil {
tx.Rollback()
return fmt.Errorf("failed to record migration %d: %v", migration.Version, err)
}
// 提交事务
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit migration %d: %v", migration.Version, err)
}
fmt.Printf("Successfully applied migration %d\n", migration.Version)
}
}
return nil
}
// 添加统计数据结构
type GameStats struct {
TotalPlayers int `json:"totalPlayers"`
TotalGames int `json:"totalGames"`
TotalScore int `json:"totalScore"`
}
// 修改获取统计数据的处理函数
func handleGetStats(w http.ResponseWriter, r *http.Request) {
stats := GameStats{}
err := db.QueryRow(`
SELECT
COALESCE(COUNT(DISTINCT name), 0) as total_players,
COALESCE(SUM(play_count), 0) as total_games,
COALESCE(SUM(total_score), 0) as total_score
FROM scores
`).Scan(&stats.TotalPlayers, &stats.TotalGames, &stats.TotalScore)
if err != nil {
if err == sql.ErrNoRows {
// 如果没有数据,返回零值
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(stats)
return
}
fmt.Printf("Error getting stats: %v\n", err)
http.Error(w, "Failed to get stats", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(stats)
}
func main() {
// 添加命令行参数
var port int
flag.IntVar(&port, "port", 8080, "服务监听端口")
flag.Parse()
// 初始化数据库
if err := initDB(); err != nil {
fmt.Printf("Failed to initialize database: %v\n", err)
return
}
defer db.Close()
r := mux.NewRouter()
// 添加 SVG MIME 类型
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, ".svg") {
w.Header().Set("Content-Type", "image/svg+xml")
}
http.FileServer(http.Dir("static")).ServeHTTP(w, r)
})))
// 路由处理
r.HandleFunc("/", handleGame)
r.HandleFunc("/submit-score", handleSubmitScore)
r.HandleFunc("/get-scores", validateRequest(handleGetScores))
r.HandleFunc("/get-replay", validateRequest(handleGetReplay))
r.HandleFunc("/get-game-stats", validateRequest(handleGetStats))
// 使用命令行指定的端口
fmt.Printf("Server starting at http://localhost:%d\n", port)
// 启动会话清理协程
go cleanupSessions()
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), r); err != nil {
fmt.Printf("Server failed to start: %v\n", err)
}
}
func handleGame(w http.ResponseWriter, r *http.Request) {
sessionID := generateSessionID()
sessionsMap.Lock()
sessions[sessionID] = sessionInfo{
StartTime: time.Now(),
LastScore: 0,
LastSubmit: time.Time{},
ExpiresAt: time.Now().Add(sessionTimeout),
}
// 获取版本记录
versions, err := getVersions()
if err != nil {
versions = []VersionInfo{} // 使用空数组
}
sessionsMap.Unlock()
// 使用自定义函数创建模板
tmpl := template.Must(template.New("game.html").Funcs(templateFuncs).ParseFiles("templates/game.html"))
tmpl.Execute(w, map[string]interface{}{
"Versions": versions,
"SessionID": sessionID,
"SecretKey": secretKey,
"AppName": appName,
})
}
func handleSubmitScore(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// 解析请求
var submission ScoreSubmission
if err := json.NewDecoder(r.Body).Decode(&submission); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// 验证会话
sessionsMap.Lock()
session, exists := sessions[submission.SessionID]
if exists {
// 验证提交间隔
if time.Since(session.LastSubmit).Seconds() < minInterval && session.LastScore > 0 {
sessionsMap.Unlock()
http.Error(w, "Please wait before submitting again", http.StatusTooManyRequests)
return
}
// 更新会话信息
session.LastSubmit = time.Now()
session.LastScore = submission.Score
session.ExpiresAt = time.Now().Add(sessionTimeout)
sessions[submission.SessionID] = session
}
sessionsMap.Unlock()
if !exists {
http.Error(w, "Invalid session", http.StatusBadRequest)
return
}
// 验证分数提交
if !validateScoreHash(submission) {
http.Error(w, "Invalid score submission", http.StatusBadRequest)
return
}
// 验证时间戳
now := time.Now().Unix()
diff := now - submission.Timestamp
if diff < 0 {
diff = -diff
}
if diff > maxTimeDiff {
http.Error(w, "Invalid timestamp", http.StatusBadRequest)
return
}
// 压缩回放数据
compressedReplay, err := compressReplay(submission.Replay)
if err != nil {
fmt.Printf("Failed to compress replay: %v\n", err)
http.Error(w, "Failed to process replay data", http.StatusInternalServerError)
return
}
// 检查作弊行为
cheatResult := detectCheating(submission.Replay, submission.Score)
if !cheatResult.IsValid {
fmt.Printf("Cheat detected: %v\n", cheatResult.Violations)
http.Error(w, cheatResult.Reason, http.StatusBadRequest)
return
}
// 使用互斥锁保护数据库写操作
dbWriteLock.Lock()
defer dbWriteLock.Unlock()
// 开始事务
tx, err := db.Begin()
if err != nil {
fmt.Printf("Failed to begin transaction: %v\n", err)
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
defer tx.Rollback() // 在出错时回滚事务
// 查询当前玩家的历史最高分
var highScore int
err = tx.QueryRow(`SELECT COALESCE(MAX(score), 0) FROM scores WHERE name = ?`, submission.Name).Scan(&highScore)
if err != nil && err != sql.ErrNoRows {
fmt.Printf("Database error when querying high score: %v\n", err)
http.Error(w, "Failed to check high score", http.StatusInternalServerError)
return
}
// 判断是否破纪录
isNewRecord := submission.Score > highScore
// 更新数据库
_, err = tx.Exec(`
INSERT INTO scores (name, score, total_score, replay, play_count, created_at)
VALUES (?, ?, ?, ?, 1, CURRENT_TIMESTAMP)
ON CONFLICT(name) DO UPDATE SET
score = CASE WHEN excluded.score > score THEN excluded.score ELSE score END,
total_score = total_score + excluded.score,
replay = CASE WHEN excluded.score > score THEN excluded.replay ELSE replay END,
play_count = play_count + 1,
created_at = CASE WHEN excluded.score > score THEN CURRENT_TIMESTAMP ELSE created_at END
`, submission.Name, submission.Score, submission.Score, compressedReplay)
if err != nil {
fmt.Printf("Database error when updating score: %v\n", err)
http.Error(w, "Failed to save score", http.StatusInternalServerError)
return
}
// 提交事务
if err := tx.Commit(); err != nil {
fmt.Printf("Failed to commit transaction: %v\n", err)
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
// 返回响应
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ScoreResponse{
IsNewRecord: isNewRecord,
HighScore: highScore,
})
}
func handleGetScores(w http.ResponseWriter, r *http.Request) {
// 获取昵称参数(可以是多个)
names := r.URL.Query()["name"]
var query string
var args []interface{}
if len(names) > 0 {
// 构建 IN 查询
placeholders := make([]string, len(names))
for i := range names {
placeholders[i] = "?"
args = append(args, names[i])
}
query = fmt.Sprintf(`
SELECT name, score, total_score, play_count, created_at
FROM scores
WHERE name IN (%s)
ORDER BY score DESC
`, strings.Join(placeholders, ","))
} else {
// 不传昵称时只获取前10名记录
query = `
SELECT name, score, total_score, play_count, created_at
FROM scores
ORDER BY score DESC
LIMIT 10
`
}
// 执行查询
rows, err := db.Query(query, args...)
if err != nil {
fmt.Printf("Query error: %v\n", err)
http.Error(w, "Failed to query scores", http.StatusInternalServerError)
return
}
defer rows.Close()
scores := []Score{}
for rows.Next() {
var s Score
if err := rows.Scan(&s.Name, &s.Score, &s.TotalScore, &s.PlayCount, &s.CreatedAt); err != nil {
fmt.Printf("Scan error: %v\n", err)
http.Error(w, "Failed to read scores", http.StatusInternalServerError)
return
}
scores = append(scores, s)
}
// 检查遍历过程中是否有错误
if err = rows.Err(); err != nil {
fmt.Printf("Iteration error: %v\n", err)
http.Error(w, "Error reading scores", http.StatusInternalServerError)
return
}
// 设置响应头
w.Header().Set("Content-Type", "application/json")
// 返回结果
if err := json.NewEncoder(w).Encode(scores); err != nil {
fmt.Printf("Encode error: %v\n", err)
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
}
func handleGetReplay(w http.ResponseWriter, r *http.Request) {
playerName := r.URL.Query().Get("name")
if playerName == "" {
http.Error(w, "Player name is required", http.StatusBadRequest)
return
}
var compressedReplay string
err := db.QueryRow("SELECT replay FROM scores WHERE name = ?", playerName).Scan(&compressedReplay)
if err != nil {
if err == sql.ErrNoRows {
http.Error(w, "Replay not found", http.StatusNotFound)
return
}
fmt.Printf("Database error: %v\n", err)
http.Error(w, "Failed to get replay", http.StatusInternalServerError)
return
}
// 解压缩回放数据
if compressedReplay != "" {
decompressedReplay, err := decompressReplay(compressedReplay)
if err != nil {
fmt.Printf("Failed to decompress replay: %v\n", err)
http.Error(w, "Failed to process replay data", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(decompressedReplay))
} else {
w.Write([]byte("[]"))
}
}
// 生成会话ID
func generateSessionID() string {
b := make([]byte, 32)
crand.Read(b)
return base64.URLEncoding.EncodeToString(b)
}
// 生成分数哈希
func generateScoreHash(sessionID string, score int, timestamp int64, nonce string) string {
h := hmac.New(sha256.New, []byte(secretKey))
message := fmt.Sprintf("nonce=%s&score=%d&sessionId=%s×tamp=%d",
nonce, score, sessionID, timestamp)
h.Write([]byte(message))
return hex.EncodeToString(h.Sum(nil))
}
// 修改验证函数以使用 ScoreSubmission
func validateScoreHash(submission ScoreSubmission) bool {
expectedHash := generateScoreHash(submission.SessionID, submission.Score, submission.Timestamp, submission.Nonce)
return hmac.Equal([]byte(submission.Hash), []byte(expectedHash))
}
// 添加一个新的整数版本的 abs 函数
func absInt(n int) int {
if n < 0 {
return -n
}
return n
}
// 修改检查移动是否合法的函数
func isValidMove(prev, curr GameStep) bool {
// 检查方向变化是否合法(放宽标准)
if absInt(curr.Dx-prev.Dx) > 2 || absInt(curr.Dy-prev.Dy) > 2 {
return false
}
// 检查蛇头位置变化是否合法(放宽标准)
head1 := prev.Snake[0]
head2 := curr.Snake[0]
if absInt(head2.X-head1.X) > 2 || absInt(head2.Y-head1.Y) > 2 {
return false
}
return true
}
// 添加压缩函数
func compressReplay(data string) (string, error) {
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
if _, err := gz.Write([]byte(data)); err != nil {
return "", err
}
if err := gz.Close(); err != nil {
return "", err
}
// 使用 base64 编码压缩后的数据,使其可以安全存储在数据库中
return base64.StdEncoding.EncodeToString(buf.Bytes()), nil
}
// 添加解压缩函数
func decompressReplay(compressed string) (string, error) {
data, err := base64.StdEncoding.DecodeString(compressed)
if err != nil {
return "", err
}
gz, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return "", err
}
defer gz.Close()
decompressed, err := ioutil.ReadAll(gz)
if err != nil {
return "", err
}
return string(decompressed), nil
}
// 添加请求验证中间件
func validateRequest(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 获取请求参数
timestamp := r.URL.Query().Get("timestamp")
nonce := r.URL.Query().Get("nonce")
signature := r.URL.Query().Get("signature")
// 验证参数是否存在
if timestamp == "" || nonce == "" || signature == "" {
http.Error(w, "Missing required parameters", http.StatusBadRequest)
return
}
// 验证时间戳
ts, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
http.Error(w, "Invalid timestamp", http.StatusBadRequest)
return
}
if !validateTimestamp(ts) {
http.Error(w, "Request expired", http.StatusBadRequest)
return
}
// 检查时间戳是否在有效期内
now := time.Now().Unix()
diff := now - ts
if diff < 0 {
diff = -diff
}
if diff > maxTimeDiff {
http.Error(w, "Request expired", http.StatusBadRequest)
return
}
// 构建签名字符串
params := make(map[string]string)
for key, values := range r.URL.Query() {
if key != "signature" { // 排除签名本身
params[key] = values[0]
}
}
// 按字母顺序排序参数
var keys []string
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
// 构建签名字符串
var signParts []string
for _, k := range keys {
signParts = append(signParts, fmt.Sprintf("%s=%s", k, params[k]))
}
signString := strings.Join(signParts, "&")
// 计算预期的签名
h := hmac.New(sha256.New, []byte(secretKey))
h.Write([]byte(signString))
expectedSignature := hex.EncodeToString(h.Sum(nil))
// 验证签名
if !hmac.Equal([]byte(signature), []byte(expectedSignature)) {
http.Error(w, "Invalid signature", http.StatusBadRequest)
return
}
next.ServeHTTP(w, r)
}
}
// 添加会话清理函数
func cleanupSessions() {
for {
time.Sleep(cleanupInterval)
now := time.Now()
sessionsMap.Lock()
// 清理过期的会话
for id, session := range sessions {
if now.After(session.ExpiresAt) {
delete(sessions, id)
}
}
sessionsMap.Unlock()
}
}
// 添加作弊检测函数
func detectCheating(replayData string, finalScore int) CheatDetectionResult {
var steps []GameStep
if err := json.Unmarshal([]byte(replayData), &steps); err != nil {
return CheatDetectionResult{
IsValid: false,
Reason: "回放数据无效",
}
}
violations := []string{}
// 1. 检查游戏时长(只在得分大于0时检查)
if finalScore > 0 {
gameDuration := len(steps) * 100 // 每步100ms
if gameDuration < MIN_GAME_DURATION*1000 {
violations = append(violations, "游戏时长过短")
}
}
// 2. 检查移动间隔和完美移动
perfectMoveCount := 0
for i := 1; i < len(steps); i++ {
// 检查移动是否合法(放宽检查标准)
if !isValidMove(steps[i-1], steps[i]) {
// 只在非碰撞情况下检查
if len(steps) > i+1 {
violations = append(violations, "存在非法移动")
}
}
// 检查完美移动(只在连续移动时检查)
if isPerfectMove(steps[i-1], steps[i]) {
perfectMoveCount++
if perfectMoveCount > MAX_PERFECT_MOVES {
violations = append(violations, "完美移动次数过多")
break
}
} else {
perfectMoveCount = 0
}
}
// 3. 检查得分合理性
if finalScore > 0 {
foodCount := countFoodEaten(steps)
if finalScore > foodCount*MAX_SCORE_PER_FOOD {
violations = append(violations, "得分异常")
}
}
// 4. 检查蛇的移动连续性(只在非碰撞情况下检查)
if len(steps) > 2 && finalScore > 0 {
if !validateSnakeMovement(steps[:len(steps)-1]) {
violations = append(violations, "蛇的移动轨迹异常")
}
}
// 根据违规情况返回结果(需要多个违规才判定为作弊)
if len(violations) > 1 {
return CheatDetectionResult{
IsValid: false,
Reason: getRandomCheatMessage(),
Violations: violations,
}
}
return CheatDetectionResult{IsValid: true}
}
// 检查是否是完美移动
func isPerfectMove(prev, curr GameStep) bool {
head := curr.Snake[0]
food := curr.Food
// 检查是否朝着食物方向移动
isOptimalX := (food.X > head.X && curr.Dx > 0) || (food.X < head.X && curr.Dx < 0)
isOptimalY := (food.Y > head.Y && curr.Dy > 0) || (food.Y < head.Y && curr.Dy < 0)
return isOptimalX || isOptimalY
}
// 统计吃到的食物数量
func countFoodEaten(steps []GameStep) int {
foodCount := 0
for i := 1; i < len(steps); i++ {
if len(steps[i].Snake) > len(steps[i-1].Snake) {
foodCount++
}
}
return foodCount
}
// 修改验证蛇的移动连续性的函数
func validateSnakeMovement(steps []GameStep) bool {
for i := 1; i < len(steps); i++ {
curr := steps[i]
// 检查蛇身的连续性
for j := 0; j < len(curr.Snake)-1; j++ {
dx := absInt(curr.Snake[j].X - curr.Snake[j+1].X)
dy := absInt(curr.Snake[j].Y - curr.Snake[j+1].Y)
if dx+dy != 1 {
return false
}
}
}
return true
}
// 修改随机消息函数,添加 math/rand 包的导入
func init() {
// 初始化随机数生成器
rand.Seed(time.Now().UnixNano())
}
func getRandomCheatMessage() string {
messages := []string{
"检测到异常操作,要诚信游戏哦~ 😊",
"这次的分数可能有点问题,再来一局吧! ��",
"游戏要公平才有趣,继续加油! ��",
"存在作弊嫌疑,本次分数无效~ 🚫",
"要相信自己,不需要使用外挂! ⭐",
}
return messages[rand.Intn(len(messages))]
}
// 修改时间戳验证函数
func validateTimestamp(ts int64) bool {
now := time.Now().Unix()
diff := now - ts
if diff < 0 {
diff = -diff
}
return diff <= maxTimeDiff
}