RankService.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. // 检查表是否存在
  81. using var checkCmd = conn.CreateCommand();
  82. checkCmd.CommandText = $"SELECT name FROM sqlite_master WHERE type='table' AND name='rank_game_{gameId}';";
  83. var result = checkCmd.ExecuteScalar();
  84. if (result != null)
  85. {
  86. using var cmd = conn.CreateCommand();
  87. cmd.CommandText = $"DELETE FROM rank_game_{gameId};";
  88. cmd.ExecuteNonQuery();
  89. }
  90. // 如果表不存在则跳过,无需操作
  91. }
  92. /// <summary>
  93. /// 获取当前存在的全部id
  94. /// </summary>
  95. /// <returns></returns>
  96. public static List<int> GetAllGameIds()
  97. {
  98. var gameIds = new List<int>();
  99. using var conn = new SqliteConnection(DbPath);
  100. conn.Open();
  101. using var cmd = conn.CreateCommand();
  102. cmd.CommandText = @"
  103. SELECT name
  104. FROM sqlite_master
  105. WHERE type='table' AND name LIKE 'rank_game_%';
  106. ";
  107. using var reader = cmd.ExecuteReader();
  108. while (reader.Read())
  109. {
  110. var tableName = reader.GetString(0); // 例如 "rank_game_5"
  111. if (tableName.StartsWith("rank_game_"))
  112. {
  113. var idPart = tableName.Substring("rank_game_".Length);
  114. if (int.TryParse(idPart, out int gameId))
  115. {
  116. gameIds.Add(gameId);
  117. }
  118. }
  119. }
  120. return gameIds;
  121. }
  122. // 上传分数(如果是新用户,插入;如果是高分,更新)
  123. public static void UploadScore(int gameId, int userId, string nickname, string avatarUrl, int score)
  124. {
  125. CreateTableIfNotExists(gameId);
  126. using var conn = new SqliteConnection(DbPath);
  127. conn.Open();
  128. using var cmd = conn.CreateCommand();
  129. // 查询旧分数
  130. cmd.CommandText = $"SELECT score FROM rank_game_{gameId} WHERE userId = @userId;";
  131. cmd.Parameters.AddWithValue("@userId", userId);
  132. var reader = cmd.ExecuteReader();
  133. int? oldScore = null;
  134. if (reader.Read()) oldScore = reader.GetInt32(0);
  135. reader.Close();
  136. if (oldScore == null)
  137. {
  138. // 新用户插入
  139. cmd.CommandText = $@"INSERT INTO rank_game_{gameId} (userId, nickname, avatarUrl, score)
  140. VALUES (@userId, @nickname, @avatarUrl, @score);";
  141. }
  142. else if (score > oldScore)
  143. {
  144. // 更新高分
  145. cmd.CommandText = $@"UPDATE rank_game_{gameId}
  146. SET score = @score, update_time = CURRENT_TIMESTAMP
  147. WHERE userId = @userId;";
  148. }
  149. else
  150. {
  151. return; // 分数没提升
  152. }
  153. cmd.Parameters.AddWithValue("@nickname", nickname);
  154. cmd.Parameters.AddWithValue("@avatarUrl", avatarUrl);
  155. cmd.Parameters.AddWithValue("@score", score);
  156. cmd.ExecuteNonQuery();
  157. }
  158. public class RankEntry
  159. {
  160. public string Nickname;
  161. public string AvatarUrl;
  162. public int Score;
  163. public int Rank;
  164. public bool IsSelf;
  165. }
  166. public static (List<RankEntry> resultList, int userRank, int totalCount) GetRankList(int gameId, int userId)
  167. {
  168. var result = new List<RankEntry>();
  169. using var conn = new SqliteConnection(DbPath);
  170. conn.Open();
  171. using var cmd = conn.CreateCommand();
  172. cmd.CommandText = $"SELECT userId, nickname, avatarUrl, score, update_time FROM rank_game_{gameId} ORDER BY score DESC, update_time DESC;";
  173. using var reader = cmd.ExecuteReader();
  174. var allRanks = new List<RankEntry>();
  175. int currentRank = 1;
  176. int userIndex = -1;
  177. while (reader.Read())
  178. {
  179. var entry = new RankEntry
  180. {
  181. Nickname = reader.GetString(1),
  182. AvatarUrl = reader.GetString(2),
  183. Score = reader.GetInt32(3),
  184. Rank = currentRank++,
  185. IsSelf = reader.GetInt32(0) == userId
  186. };
  187. if (entry.IsSelf)
  188. userIndex = allRanks.Count;
  189. allRanks.Add(entry);
  190. }
  191. reader.Close();
  192. // 加入前三名
  193. for (int i = 0; i < Math.Min(3, allRanks.Count); i++)
  194. {
  195. result.Add(allRanks[i]);
  196. }
  197. // 加入中间的自己 + 周围 7 条数据
  198. if (userIndex == -1)
  199. {
  200. // 用户不存在
  201. result.Add(new RankEntry
  202. {
  203. Rank = -1,
  204. IsSelf = true,
  205. Nickname = "None",
  206. AvatarUrl = "",
  207. Score = 0
  208. });
  209. }
  210. else
  211. {
  212. // 起始从第4条开始找
  213. int centerStart = Math.Max(3, userIndex - 3);
  214. int centerEnd = Math.Min(allRanks.Count, centerStart + 7);
  215. for (int i = centerStart; i < centerEnd; i++)
  216. {
  217. result.Add(allRanks[i]);
  218. }
  219. }
  220. return (result, userIndex == -1 ? -1 : allRanks[userIndex].Rank, allRanks.Count);
  221. }
  222. /// <summary>
  223. /// 用设备唯一标识(如 SystemInfo.deviceUniqueIdentifier)做基础,然后加时间戳或随机数避免重复
  224. /// </summary>
  225. /// <returns></returns>
  226. public static int GenerateLocalUserId()
  227. {
  228. return Math.Abs($"{SystemInfo.deviceUniqueIdentifier}_{DateTime.UtcNow.Ticks}".GetHashCode());
  229. }
  230. }
  231. }