RankService.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. using System;
  2. using Mono.Data.Sqlite;
  3. using UnityEngine;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. namespace LocalRank
  7. {
  8. public class RankService
  9. {
  10. private const string DatabaseName = "rank.db";
  11. private static string DbFullPath;
  12. static RankService()
  13. {
  14. #if UNITY_EDITOR
  15. DbFullPath = Path.Combine(Application.streamingAssetsPath, DatabaseName);
  16. #else
  17. var filepath = Path.Combine(Application.persistentDataPath, DatabaseName);
  18. if (!File.Exists(filepath))
  19. {
  20. Debug.Log("Database not in Persistent path, copying from StreamingAssets...");
  21. #if UNITY_ANDROID
  22. var sourcePath = "jar:file://" + Application.dataPath + "!/assets/" + DatabaseName;
  23. var www = new WWW(sourcePath);
  24. while (!www.isDone) { }
  25. File.WriteAllBytes(filepath, www.bytes);
  26. #elif UNITY_IOS
  27. var sourcePath = Path.Combine(Application.dataPath + "/Raw", DatabaseName);
  28. File.Copy(sourcePath, filepath);
  29. #elif UNITY_STANDALONE_OSX
  30. var sourcePath = Path.Combine(Application.dataPath + "/Resources/Data/StreamingAssets", DatabaseName);
  31. File.Copy(sourcePath, filepath);
  32. #else
  33. var sourcePath = Path.Combine(Application.streamingAssetsPath, DatabaseName);
  34. File.Copy(sourcePath, filepath);
  35. #endif
  36. Debug.Log("Database copied to: " + filepath);
  37. }
  38. DbFullPath = filepath;
  39. #endif
  40. }
  41. //private static string DbPath => $"URI=file:{Application.persistentDataPath}/rank.db";
  42. private static string DbPath => $"URI=file:{DbFullPath}";
  43. // 检查表是否存在
  44. public static bool IsTableExists(int gameId)
  45. {
  46. using var conn = new SqliteConnection(DbPath);
  47. conn.Open();
  48. using var cmd = conn.CreateCommand();
  49. cmd.CommandText = $@"
  50. SELECT COUNT(*)
  51. FROM sqlite_master
  52. WHERE type = 'table' AND name = 'rank_game_{gameId}';
  53. ";
  54. return Convert.ToInt32(cmd.ExecuteScalar()) > 0;
  55. }
  56. // 创建表格(如果表不存在)
  57. public static void CreateTableIfNotExists(int gameId)
  58. {
  59. if (IsTableExists(gameId)) return; // 如果表已存在,直接返回
  60. using var conn = new SqliteConnection(DbPath);
  61. conn.Open();
  62. using var cmd = conn.CreateCommand();
  63. cmd.CommandText = $@"
  64. CREATE TABLE IF NOT EXISTS rank_game_{gameId} (
  65. id INTEGER PRIMARY KEY AUTOINCREMENT,
  66. userId INTEGER NOT NULL,
  67. nickname TEXT,
  68. avatarUrl TEXT,
  69. score INTEGER,
  70. update_time DATETIME DEFAULT CURRENT_TIMESTAMP
  71. );
  72. ";
  73. cmd.ExecuteNonQuery();
  74. }
  75. // 清空表格
  76. public static void ClearTable(int gameId)
  77. {
  78. using var conn = new SqliteConnection(DbPath);
  79. conn.Open();
  80. using var cmd = conn.CreateCommand();
  81. cmd.CommandText = $"DELETE FROM rank_game_{gameId};";
  82. cmd.ExecuteNonQuery();
  83. }
  84. // 上传分数(如果是新用户,插入;如果是高分,更新)
  85. public static void UploadScore(int gameId, int userId, string nickname, string avatarUrl, int score)
  86. {
  87. CreateTableIfNotExists(gameId);
  88. using var conn = new SqliteConnection(DbPath);
  89. conn.Open();
  90. using var cmd = conn.CreateCommand();
  91. // 查询旧分数
  92. cmd.CommandText = $"SELECT score FROM rank_game_{gameId} WHERE userId = @userId;";
  93. cmd.Parameters.AddWithValue("@userId", userId);
  94. var reader = cmd.ExecuteReader();
  95. int? oldScore = null;
  96. if (reader.Read()) oldScore = reader.GetInt32(0);
  97. reader.Close();
  98. if (oldScore == null)
  99. {
  100. // 新用户插入
  101. cmd.CommandText = $@"INSERT INTO rank_game_{gameId} (userId, nickname, avatarUrl, score)
  102. VALUES (@userId, @nickname, @avatarUrl, @score);";
  103. }
  104. else if (score > oldScore)
  105. {
  106. // 更新高分
  107. cmd.CommandText = $@"UPDATE rank_game_{gameId}
  108. SET score = @score, update_time = CURRENT_TIMESTAMP
  109. WHERE userId = @userId;";
  110. }
  111. else
  112. {
  113. return; // 分数没提升
  114. }
  115. cmd.Parameters.AddWithValue("@nickname", nickname);
  116. cmd.Parameters.AddWithValue("@avatarUrl", avatarUrl);
  117. cmd.Parameters.AddWithValue("@score", score);
  118. cmd.ExecuteNonQuery();
  119. }
  120. public class RankEntry
  121. {
  122. public string Nickname;
  123. public string AvatarUrl;
  124. public int Score;
  125. public int Rank;
  126. public bool IsSelf;
  127. }
  128. public static (List<RankEntry> resultList, int userRank, int totalCount) GetRankList(int gameId, int userId)
  129. {
  130. var result = new List<RankEntry>();
  131. using var conn = new SqliteConnection(DbPath);
  132. conn.Open();
  133. using var cmd = conn.CreateCommand();
  134. cmd.CommandText = $"SELECT userId, nickname, avatarUrl, score, update_time FROM rank_game_{gameId} ORDER BY score DESC, update_time DESC;";
  135. using var reader = cmd.ExecuteReader();
  136. var allRanks = new List<RankEntry>();
  137. int currentRank = 1;
  138. int userIndex = -1;
  139. while (reader.Read())
  140. {
  141. var entry = new RankEntry
  142. {
  143. Nickname = reader.GetString(1),
  144. AvatarUrl = reader.GetString(2),
  145. Score = reader.GetInt32(3),
  146. Rank = currentRank++,
  147. IsSelf = reader.GetInt32(0) == userId
  148. };
  149. if (entry.IsSelf)
  150. userIndex = allRanks.Count;
  151. allRanks.Add(entry);
  152. }
  153. reader.Close();
  154. // 加入前三名
  155. for (int i = 0; i < Math.Min(3, allRanks.Count); i++)
  156. {
  157. result.Add(allRanks[i]);
  158. }
  159. // 加入中间的自己 + 周围 7 条数据
  160. if (userIndex == -1)
  161. {
  162. // 用户不存在
  163. result.Add(new RankEntry
  164. {
  165. Rank = -1,
  166. IsSelf = true,
  167. Nickname = "None",
  168. AvatarUrl = "",
  169. Score = 0
  170. });
  171. }
  172. else
  173. {
  174. // 起始从第4条开始找
  175. int centerStart = Math.Max(3, userIndex - 3);
  176. int centerEnd = Math.Min(allRanks.Count, centerStart + 7);
  177. for (int i = centerStart; i < centerEnd; i++)
  178. {
  179. result.Add(allRanks[i]);
  180. }
  181. }
  182. return (result, userIndex == -1 ? -1 : allRanks[userIndex].Rank, allRanks.Count);
  183. }
  184. /// <summary>
  185. /// 用设备唯一标识(如 SystemInfo.deviceUniqueIdentifier)做基础,然后加时间戳或随机数避免重复
  186. /// </summary>
  187. /// <returns></returns>
  188. public static int GenerateLocalUserId()
  189. {
  190. return Math.Abs($"{SystemInfo.deviceUniqueIdentifier}_{DateTime.UtcNow.Ticks}".GetHashCode());
  191. }
  192. }
  193. }