Database.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.IO;
  6. using Mono.Data.Sqlite;
  7. using UnityEngine;
  8. using UnityEngine.Networking;
  9. public class Database : MonoBehaviour
  10. {
  11. private const string onlineQuestionsUrl = "narkampen.nordh.xyz/narKampen/dbFiles/Question.php"; // TODO update
  12. string connectionType;
  13. string databaseUrl;
  14. string gameMode;
  15. int winAmount = -1;
  16. int questionTimer = -1;
  17. public GameObject questionCardPrefab;
  18. private static Database instance;
  19. public static Database Instance
  20. {
  21. get
  22. {
  23. if (instance == null)
  24. {
  25. instance = GameObject.FindObjectOfType<Database>();
  26. if (instance == null)
  27. {
  28. GameObject container = new GameObject("Database");
  29. instance = container.AddComponent<Database>();
  30. }
  31. }
  32. return instance;
  33. }
  34. }
  35. IDbConnection conn;
  36. internal void GetCategories(List<CategoryPanel.Category> list, string gameMode, int gameId)
  37. {
  38. if (gameMode.Equals(Constants.ONLINE))
  39. {
  40. OnlineDatabase.Instance.GetCategories(list, gameId);
  41. }
  42. else
  43. {
  44. //string sql = "SELECT name, r, g, b, a, id FROM category";
  45. string sql = "SELECT category.*, count(*) as count FROM questions " +
  46. "INNER JOIN questionToCategory ON questions.id = questionToCategory.questionId " +
  47. "INNER JOIN category ON questionToCategory.categoryId = category.id " +
  48. "GROUP BY category.name";
  49. IDbCommand cmd = GetConnection();
  50. cmd.CommandText = sql;
  51. IDataReader reader = cmd.ExecuteReader();
  52. while (reader.Read())
  53. {
  54. CategoryPanel.Category cat = new CategoryPanel.Category();
  55. byte r = (byte)reader.GetInt32(2);
  56. byte g = (byte)reader.GetInt32(3);
  57. byte b = (byte)reader.GetInt32(4);
  58. byte a = (byte)reader.GetInt32(5);
  59. cat.color = new Color32(r, g, b, a);
  60. cat.name = reader.GetString(1);
  61. cat.id = reader.GetInt32(0);
  62. cat.questionCount = reader.GetInt32(6);
  63. list.Add(cat);
  64. }
  65. CloseConnection();
  66. }
  67. }
  68. [Serializable]
  69. public class Question
  70. {
  71. public string question;
  72. public string answer;
  73. public string id;
  74. public string category;
  75. }
  76. [Serializable]
  77. public class Questions
  78. {
  79. public List<Question> questionsList = new List<Question>();
  80. }
  81. [Serializable]
  82. public class PlayerInfo
  83. {
  84. public string username;
  85. public string status;
  86. }
  87. [Serializable]
  88. public class PlayerInfos
  89. {
  90. public List<PlayerInfo> playerInfoList = new List<PlayerInfo>();
  91. }
  92. [Serializable]
  93. public class Category
  94. {
  95. public int r;
  96. public int g;
  97. public int b;
  98. public int a;
  99. public int id;
  100. public string name;
  101. }
  102. [Serializable]
  103. public class Categories
  104. {
  105. public List<Category> categoryList = new List<Category>();
  106. }
  107. [Serializable]
  108. public class UserName
  109. {
  110. public string id;
  111. public string username;
  112. }
  113. [Serializable]
  114. public class UserNames
  115. {
  116. public List<UserName> usernamesList = new List<UserName>();
  117. }
  118. internal void SetLastPlayedDate(int gameId)
  119. {
  120. if (gameMode.Equals(Constants.ONLINE))
  121. {
  122. }
  123. string sql = "UPDATE game SET lastPlayedDate = DATE() WHERE id = " + gameId;
  124. IDbCommand cmd = GetConnection();
  125. cmd.CommandText = sql;
  126. cmd.ExecuteNonQuery();
  127. cmd.Dispose();
  128. CloseConnection();
  129. }
  130. internal List<OnlineDatabase.UserName> FindRandomPlayer(int playerId)
  131. {
  132. return OnlineDatabase.Instance.FindRandomPlayer(playerId);
  133. }
  134. private IDbCommand GetConnection()
  135. {
  136. if (databaseUrl == null)
  137. { // TODO ej bra lösning för online
  138. SetLocalOrOnline(Constants.LOCAL);
  139. }
  140. Debug.Log("Database url " + databaseUrl);
  141. conn = new SqliteConnection(databaseUrl);
  142. conn.Open();
  143. IDbCommand cmd = conn.CreateCommand();
  144. return cmd;
  145. }
  146. private void CloseConnection()
  147. {
  148. conn.Close();
  149. }
  150. string questionString = "";
  151. string answerString = "";
  152. string idString = "";
  153. string categoryString = "";
  154. private int round = -1;
  155. public string QuestionString { get => questionString; set => questionString = value; }
  156. private void Start()
  157. {
  158. if (instance == null)
  159. {
  160. instance = this;
  161. }
  162. if (databaseUrl == null || databaseUrl.Equals(""))
  163. {
  164. SetLocalOrOnline(Constants.LOCAL); // Temporary, should not be needed after local testing
  165. }
  166. }
  167. internal void SignIn(string username, int userId, bool keepSigendIn)
  168. {
  169. int ksi = 0;
  170. if (keepSigendIn)
  171. {
  172. ksi = 1;
  173. }
  174. string sql = "INSERT OR REPLACE INTO userSettings (username, userId, keepSignedIn) VALUES ('" + username + "', " + userId + "," + ksi + ")";
  175. IDbCommand cmd = GetConnection();
  176. cmd.CommandText = sql;
  177. cmd.ExecuteNonQuery();
  178. sql = "INSERT OR REPLACE INTO settings (name, value) VALUES ('signedInUser', '" + username + "')";
  179. cmd.CommandText = sql;
  180. cmd.ExecuteNonQuery();
  181. CloseConnection();
  182. }
  183. internal void SetGameFinished(int gameId, string gameMode)
  184. {
  185. if (gameMode.Equals(Constants.ONLINE))
  186. {
  187. OnlineDatabase.Instance.SetGameFinished(gameId);
  188. }
  189. else
  190. {
  191. string sql = "UPDATE game SET finishedDate = DATETIME() WHERE id = " + gameId;
  192. IDbCommand cmd = GetConnection();
  193. cmd.CommandText = sql;
  194. cmd.ExecuteNonQuery();
  195. }
  196. }
  197. internal bool IsKeepSignedIn()
  198. {
  199. string sql = "SELECT keepSignedIn FROM userSettings";
  200. IDbCommand cmd = GetConnection();
  201. cmd.CommandText = sql;
  202. IDataReader reader = cmd.ExecuteReader();
  203. int res = 0;
  204. while (reader.Read())
  205. {
  206. res = reader.GetInt32(0);
  207. }
  208. return res == 1;
  209. }
  210. internal KeyValuePair<int, string> GetSignedInUser()
  211. {
  212. // string sql = "SELECT userId, username FROM userSettings";
  213. string sql = "SELECT userId, username FROM userSettings WHERE username = (SELECT value FROM settings WHERE name = 'signedInUser')";
  214. IDbCommand cmd = GetConnection();
  215. cmd.CommandText = sql;
  216. int userId = -1;
  217. string username = "";
  218. IDataReader reader = cmd.ExecuteReader();
  219. while (reader.Read())
  220. {
  221. userId = reader.GetInt32(0);
  222. username = reader.GetString(1);
  223. }
  224. CloseConnection();
  225. return new KeyValuePair<int, string>(userId, username);
  226. }
  227. internal void LogoutUser()
  228. {
  229. // string sql = "UPDATE userSettings SET keepSignedIn = 0";
  230. string sql = "DELETE FROM userSettings";
  231. IDbCommand cmd = GetConnection();
  232. cmd.CommandText = sql;
  233. cmd.ExecuteNonQuery();
  234. sql = "DELETE FROM settings WHERE name = 'signedInUser'";
  235. cmd.CommandText = sql;
  236. cmd.ExecuteNonQuery();
  237. CloseConnection();
  238. }
  239. internal int GetQuestionTimer(int gameId)
  240. {
  241. if (questionTimer == -1)
  242. {
  243. string sql = "SELECT answerTimer FROM game WHERE id = " + gameId;
  244. if (databaseUrl == null)
  245. {
  246. SetLocalOrOnline(Constants.LOCAL);
  247. }
  248. IDbCommand cmd = GetConnection();
  249. cmd.CommandText = sql;
  250. IDataReader reader = cmd.ExecuteReader();
  251. while (reader.Read())
  252. {
  253. questionTimer = reader.GetInt32(0);
  254. }
  255. reader.Close();
  256. cmd.Dispose();
  257. }
  258. CloseConnection();
  259. return this.questionTimer;
  260. }
  261. internal List<LocalGameScript> GetLocalGames(GameObject prefab)
  262. {
  263. List<LocalGameScript> games = new List<LocalGameScript>();
  264. string sql = "SELECT game.*, name, localUsers.id as userId FROM game INNER JOIN localGamePlayers on game.id = localGamePlayers.gameId INNER JOIN localUsers on playerId = localUsers.id order by game.id ASC, userId ASC";
  265. IDbConnection conn = new SqliteConnection(databaseUrl);
  266. conn.Open();
  267. IDbCommand cmd = conn.CreateCommand();
  268. cmd.CommandText = sql;
  269. IDataReader reader = cmd.ExecuteReader();
  270. int currentGame = -1;
  271. GameObject localGame;
  272. LocalGameScript lgs = null;
  273. string currentPlayerName;
  274. int currentPoints;
  275. while (reader.Read())
  276. {
  277. if (currentGame != reader.GetInt32(0))
  278. {
  279. localGame = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  280. lgs = localGame.GetComponent<LocalGameScript>();
  281. lgs.GameId = reader.GetInt32(0);
  282. lgs.GameMode = reader.GetString(1);
  283. lgs.QuestionsNeededToWin = reader.GetInt32(2).ToString();
  284. lgs.AnswerTimer = reader.GetInt32(3);
  285. lgs.NumberOfPlayers = reader.GetInt32(4).ToString();
  286. lgs.CurrentPlayer = reader.GetString(5);
  287. lgs.Round = reader.GetInt32(6).ToString();
  288. lgs.StartDate = reader.GetString(7);
  289. lgs.LastPlayedDate = reader.GetString(8);
  290. lgs.FinishedDate = reader.IsDBNull(9) ? "" : reader.GetString(9);
  291. currentPlayerName = reader.GetString(10);
  292. currentPoints = GetPlayerPoints(reader.GetInt32(0), currentPlayerName);
  293. lgs.AddPlayer(currentPlayerName, currentPoints);
  294. games.Add(lgs);
  295. }
  296. else if (currentGame == reader.GetInt32(0))
  297. {
  298. currentPlayerName = reader.GetString(10);
  299. currentPoints = GetPlayerPoints(currentGame, currentPlayerName);
  300. lgs.AddPlayer(currentPlayerName, currentPoints);
  301. }
  302. currentGame = reader.GetInt32(0);
  303. }
  304. reader.Close();
  305. cmd.Dispose();
  306. conn.Close();
  307. return games;
  308. }
  309. internal void IncreasePlayerRound(int gameId, string currentPlayer)
  310. {
  311. if (gameMode.Equals(Constants.ONLINE))
  312. {
  313. OnlineDatabase.Instance.IncreasePlayerRound(gameId, currentPlayer);
  314. }
  315. else
  316. {
  317. String sql = "UPDATE localGamePlayers SET playerRound = playerRound + 1 WHERE gameId = " + gameId + " AND playerId = (SELECT id FROM localUsers WHERE name = '" + currentPlayer + "')";
  318. IDbConnection conn = new SqliteConnection(databaseUrl);
  319. conn.Open();
  320. IDbCommand cmd = conn.CreateCommand();
  321. cmd.CommandText = sql;
  322. cmd.ExecuteNonQuery();
  323. cmd.Dispose();
  324. conn.Close();
  325. }
  326. }
  327. internal void SetQuestionsLost(int gameId, string playerName, int questionsLost)
  328. {
  329. string sql = "UPDATE localGamePlayers SET questionsLost = questionsLost + " + questionsLost + " WHERE gameId = " + gameId + " AND playerId = (SELECT id FROM localUsers WHERE name = '" + playerName + "')";
  330. IDbConnection conn = new SqliteConnection(databaseUrl);
  331. conn.Open();
  332. IDbCommand cmd = conn.CreateCommand();
  333. cmd.CommandText = sql;
  334. cmd.ExecuteNonQuery();
  335. cmd.Dispose();
  336. conn.Close();
  337. }
  338. internal void RemoveGame(int gameId)
  339. {
  340. string sql = "DELETE FROM game WHERE id = " + gameId;
  341. IDbConnection conn = new SqliteConnection(databaseUrl);
  342. conn.Open();
  343. IDbCommand cmd = conn.CreateCommand();
  344. cmd.CommandText = sql;
  345. cmd.ExecuteNonQuery();
  346. string deleteLockedQuestionsSql = "DELETE FROM usersLockedQuestions WHERE gameId = " + gameId;
  347. cmd.CommandText = deleteLockedQuestionsSql;
  348. cmd.ExecuteNonQuery();
  349. cmd.Dispose();
  350. conn.Close();
  351. }
  352. public string GetCurrentPlayer(int gameId, string gameMode)
  353. {
  354. if (gameMode.Equals(Constants.ONLINE))
  355. {
  356. return OnlineDatabase.Instance.GetCurrentPlayer(gameId);
  357. }
  358. string sql = "SELECT currentPlayer FROM game WHERE id = " + gameId;
  359. IDbConnection conn = new SqliteConnection(databaseUrl);
  360. conn.Open();
  361. IDbCommand cmd = conn.CreateCommand();
  362. cmd.CommandText = sql;
  363. IDataReader reader = cmd.ExecuteReader();
  364. string currentPlayer = "";
  365. while (reader.Read())
  366. {
  367. currentPlayer = reader.GetString(0);
  368. }
  369. reader.Close();
  370. cmd.Dispose();
  371. conn.Close();
  372. return currentPlayer;
  373. }
  374. public void SetCurrentPlayer(int gameId, string currentPlayer, string gameMode)
  375. {
  376. if (gameMode.Equals(Constants.ONLINE))
  377. {
  378. OnlineDatabase.Instance.SetCurrentPlayer(gameId, currentPlayer);
  379. }
  380. else
  381. {
  382. string sql = "UPDATE game SET currentPlayer = '" + currentPlayer + "' WHERE id = " + gameId;
  383. IDbConnection conn = new SqliteConnection(databaseUrl);
  384. conn.Open();
  385. IDbCommand cmd = conn.CreateCommand();
  386. cmd.CommandText = sql;
  387. cmd.ExecuteNonQuery();
  388. cmd.Dispose();
  389. conn.Close();
  390. }
  391. }
  392. internal int GetPlayerPoints(int gameId, string playerName)
  393. {
  394. string sql = "SELECT count(*) FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerName + "'";
  395. IDbConnection conn = new SqliteConnection(databaseUrl);
  396. conn.Open();
  397. IDbCommand cmd = conn.CreateCommand();
  398. cmd.CommandText = sql;
  399. IDataReader reader = cmd.ExecuteReader();
  400. int points = 0;
  401. while (reader.Read())
  402. {
  403. points = reader.GetInt32(0);
  404. }
  405. reader.Close();
  406. cmd.Dispose();
  407. conn.Close();
  408. return points;
  409. }
  410. internal void SetFinishedDate(int gameId, string finishedDate, string gameMode)
  411. {
  412. if (gameMode.Equals(Constants.ONLINE))
  413. {
  414. OnlineDatabase.Instance.SetFinishedDate(gameId, finishedDate);
  415. }
  416. else
  417. {
  418. string sql = "UPDATE game SET finishedDate = '" + finishedDate + "' WHERE id = " + gameId;
  419. IDbConnection conn = new SqliteConnection(databaseUrl);
  420. conn.Open();
  421. IDbCommand cmd = conn.CreateCommand();
  422. cmd.CommandText = sql;
  423. cmd.ExecuteNonQuery();
  424. cmd.Dispose();
  425. conn.Close();
  426. }
  427. }
  428. internal void SetRoundValue(int gameId, int round, string gameMode)
  429. {
  430. if (gameMode.Equals(Constants.ONLINE))
  431. {
  432. OnlineDatabase.Instance.SetRoundValue(gameId, round);
  433. }
  434. else
  435. {
  436. string sql = "UPDATE game SET round = " + round + " WHERE id = " + gameId;
  437. IDbConnection conn = new SqliteConnection(databaseUrl);
  438. conn.Open();
  439. IDbCommand cmd = conn.CreateCommand();
  440. cmd.CommandText = sql;
  441. cmd.ExecuteNonQuery();
  442. cmd.Dispose();
  443. conn.Close();
  444. }
  445. }
  446. internal int GetRoundValue(int gameId, string gameMode)
  447. {
  448. if (gameMode.Equals(Constants.ONLINE))
  449. {
  450. return OnlineDatabase.Instance.GetRoundValue(gameId);
  451. }
  452. if (this.round == -1)
  453. {
  454. SetLocalOrOnline(Constants.LOCAL);
  455. string sql = "SELECT round FROM game WHERE id = " + gameId;
  456. IDbConnection conn = new SqliteConnection(databaseUrl);
  457. conn.Open();
  458. IDbCommand cmd = conn.CreateCommand();
  459. cmd.CommandText = sql;
  460. IDataReader reader = cmd.ExecuteReader();
  461. while (reader.Read())
  462. {
  463. this.round = reader.GetInt32(0);
  464. }
  465. reader.Close();
  466. cmd.Dispose();
  467. conn.Close();
  468. }
  469. return this.round;
  470. }
  471. internal List<KeyValuePair<string, int>> GetPlayersForGame(int gameId, string gameMode)
  472. {
  473. if (gameMode.Equals(Constants.ONLINE))
  474. {
  475. return OnlineDatabase.Instance.GetPlayersForGame(gameId);
  476. }
  477. string sql = "SELECT name, (SELECT count(*) FROM usersLockedQuestions WHERE playerName = localUsers.name AND gameId = " + gameId + ") as numAnswers FROM localGamePlayers " +
  478. "LEFT JOIN localUsers ON localGamePlayers.playerId = localUsers.id " +
  479. "WHERE gameId = " + gameId;
  480. IDbConnection conn = new SqliteConnection(databaseUrl);
  481. conn.Open();
  482. IDbCommand cmd = conn.CreateCommand();
  483. cmd.CommandText = sql;
  484. IDataReader reader = cmd.ExecuteReader();
  485. List<KeyValuePair<string, int>> returnList = new List<KeyValuePair<string, int>>();
  486. while (reader.Read())
  487. {
  488. KeyValuePair<string, int> player = new KeyValuePair<string, int>(reader.GetString(0), reader.GetInt32(1));
  489. returnList.Add(player);
  490. }
  491. return returnList;
  492. }
  493. public string AnswerString { get => answerString; set => answerString = value; }
  494. public string IdString { get => idString; set => idString = value; }
  495. public string CategoryString { get => categoryString; set => categoryString = value; }
  496. public void SetLocalOrOnline(string type)
  497. {
  498. gameMode = type;
  499. if (type.Equals(Constants.LOCAL))
  500. {
  501. string databaseName = "narKampenLocal.db";
  502. if (Application.platform == RuntimePlatform.Android)
  503. {
  504. databaseUrl = Application.persistentDataPath + "/" + databaseName;
  505. if (!File.Exists(databaseUrl))
  506. {
  507. UnityWebRequest load = UnityWebRequest.Get("jar:file://" + Application.dataPath + "!/assets/" + databaseName);
  508. load.SendWebRequest();
  509. while (!load.isDone) { }
  510. File.WriteAllBytes(databaseUrl, load.downloadHandler.data);
  511. }
  512. databaseUrl = "URI=file:" + databaseUrl;
  513. }
  514. else
  515. {
  516. databaseUrl = "URI=file:" + Application.dataPath + "/" + databaseName;
  517. }
  518. }
  519. else
  520. {
  521. databaseUrl = onlineQuestionsUrl;
  522. }
  523. connectionType = type;
  524. Debug.Log("Database url " + databaseUrl);
  525. }
  526. internal int GetQuestionsLost(int gameId, string playerName, string gameMode)
  527. {
  528. if (gameMode.Equals(Constants.ONLINE))
  529. {
  530. return OnlineDatabase.Instance.GetQuestionsLost(gameId, playerName);
  531. }
  532. string sql = "SELECT questionsLost FROM localGamePlayers WHERE gameId = " + gameId + " AND playerId = (SELECT id from localUsers WHERE name = '" + playerName + "')";
  533. IDbConnection conn = new SqliteConnection(databaseUrl);
  534. conn.Open();
  535. IDbCommand cmd = conn.CreateCommand();
  536. cmd.CommandText = sql;
  537. IDataReader reader = cmd.ExecuteReader();
  538. int returnValue = 0;
  539. while (reader.Read())
  540. {
  541. returnValue = reader.GetInt32(0);
  542. }
  543. reader.Close();
  544. cmd.Dispose();
  545. conn.Close();
  546. return returnValue;
  547. }
  548. public string GetGameMode(int gameId)
  549. {
  550. if (this.gameMode == null)
  551. {
  552. string sql = "SELECT gameMode FROM game WHERE id = " + gameId;
  553. IDbConnection conn = new SqliteConnection(databaseUrl);
  554. conn.Open();
  555. IDbCommand cmd = conn.CreateCommand();
  556. cmd.CommandText = sql;
  557. IDataReader reader = cmd.ExecuteReader();
  558. while (reader.Read())
  559. {
  560. this.gameMode = reader.GetString(0);
  561. }
  562. reader.Close();
  563. cmd.Dispose();
  564. conn.Close();
  565. }
  566. return this.gameMode;
  567. }
  568. public void LinkPlayersToLocalGame(List<string> playerNames, int gameId)
  569. {
  570. IDbConnection conn = new SqliteConnection(databaseUrl);
  571. conn.Open();
  572. string questionSql = "SELECT id FROM questions order by random() limit 1";
  573. IDbCommand cmd = conn.CreateCommand();
  574. cmd.CommandText = questionSql;
  575. IDataReader reader = cmd.ExecuteReader();
  576. int questionId = -1;
  577. while (reader.Read())
  578. {
  579. questionId = reader.GetInt32(0);
  580. }
  581. List<int> l = new List<int>();
  582. l.Add(questionId);
  583. foreach (string player in playerNames)
  584. {
  585. string sql = "SELECT id FROM localUsers WHERE name = '" + player + "'";
  586. int playerId;
  587. cmd = conn.CreateCommand();
  588. cmd.CommandText = sql;
  589. reader = cmd.ExecuteReader();
  590. if (reader.Read())
  591. {
  592. playerId = reader.GetInt32(0);
  593. }
  594. else
  595. {
  596. reader.Close();
  597. sql = "INSERT INTO localUsers (name) VALUES ('" + player + "')";
  598. cmd.CommandText = sql;
  599. cmd.ExecuteNonQuery();
  600. cmd.CommandText = "SELECT last_insert_rowid()";
  601. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  602. playerId = (int)lastInsert64;
  603. }
  604. cmd.Dispose();
  605. reader.Close();
  606. LinkPlayerToGame(playerId, gameId);
  607. SavePlayersQuestion(l, player, gameId, Constants.LOCAL);
  608. }
  609. IDbCommand cmd2 = conn.CreateCommand();
  610. cmd2.CommandText = "UPDATE game SET currentPlayer = '" + playerNames[0] + "' WHERE id = " + gameId;
  611. cmd2.ExecuteNonQuery();
  612. cmd2.Dispose();
  613. conn.Close();
  614. }
  615. private void LinkPlayerToGame(int playerId, int gameId)
  616. {
  617. string sql = "INSERT INTO localGamePlayers (gameId, playerId) VALUES (" + gameId + ", " + playerId + ")";
  618. SqliteConnection conn2 = new SqliteConnection(databaseUrl);
  619. conn2.Open();
  620. IDbCommand cmd = conn2.CreateCommand();
  621. cmd.CommandText = sql;
  622. cmd.ExecuteNonQuery();
  623. cmd.Dispose();
  624. conn2.Close();
  625. }
  626. internal int GetWinCondition(int gameId, string gameMode)
  627. {
  628. if (gameMode.Equals(Constants.ONLINE))
  629. {
  630. return OnlineDatabase.Instance.GetWinCondition(gameId);
  631. }
  632. if (winAmount == -1)
  633. {
  634. string sql = "SELECT winNumber FROM game WHERE id = " + gameId;
  635. IDbConnection conn = new SqliteConnection(databaseUrl);
  636. conn.Open();
  637. IDbCommand cmd = conn.CreateCommand();
  638. cmd.CommandText = sql;
  639. IDataReader reader = cmd.ExecuteReader();
  640. while (reader.Read())
  641. {
  642. this.winAmount = reader.GetInt32(0);
  643. }
  644. reader.Close();
  645. cmd.Dispose();
  646. conn.Close();
  647. }
  648. return this.winAmount;
  649. }
  650. public int SetupNewLocalGame(int winNumber, int numberOfPlayers, int questionTimer)
  651. {
  652. string sql = "INSERT INTO game (winNumber, numberOfPlayers, answerTimer, gameMode, startedDate) VALUES (" + winNumber + "," + numberOfPlayers + "," + questionTimer + ", 'Local', DATE())";
  653. IDbConnection conn = new SqliteConnection(databaseUrl);
  654. conn.Open();
  655. IDbCommand cmd = conn.CreateCommand();
  656. cmd.CommandText = sql;
  657. cmd.ExecuteNonQuery();
  658. cmd.CommandText = "SELECT last_insert_rowid()";
  659. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  660. return (int)lastInsert64;
  661. }
  662. public NewQuestionData GetNewQuestion(List<int> userAnsweredQuestions, KeyValuePair<int, String> user, string gameMode)
  663. {
  664. if (gameMode.Equals(Constants.ONLINE))
  665. {
  666. return OnlineDatabase.Instance.GetNewQuestion(user.Key);
  667. }
  668. int gameId = GameObject.Find("GameManager").GetComponent<GameManagerScript>().GameId;
  669. Color32 questionCategoryColor = new Color32(0, 0, 20, 20);
  670. if (connectionType == null)
  671. {
  672. SetLocalOrOnline(GetGameMode(gameId));
  673. }
  674. int id = -1;
  675. int categoryId = -1;
  676. string categoryName = "";
  677. if (connectionType == Constants.LOCAL)
  678. {
  679. IDbConnection conn = new SqliteConnection(databaseUrl);
  680. conn.Open();
  681. IDbCommand cmd = conn.CreateCommand();
  682. string answeredIds = String.Join(",", userAnsweredQuestions);
  683. string sql = "SELECT questions.id, question, answer, categoryId as category, name, category.R, category.G, category.B, category.A FROM questions INNER JOIN questionToCategory ON questions.id = questionToCategory.questionId INNER JOIN category on category.id = questionToCategory.categoryId WHERE questions.id NOT IN (" + answeredIds + ") AND questions.id NOT IN (SELECT questionId FROM questionsInGame WHERE gameId = " + gameId + " AND userId = (SELECT id from localUsers WHERE name = '" + user.Value + "')) ORDER BY RANDOM() limit 1";
  684. cmd.CommandText = sql;
  685. IDataReader reader = cmd.ExecuteReader();
  686. while (reader.Read())
  687. {
  688. id = reader.GetInt32(0);
  689. string question = reader.GetString(1);
  690. int answer = reader.GetInt32(2);
  691. categoryId = reader.GetInt32(3);
  692. categoryName = reader.GetString(4);
  693. idString = id.ToString();
  694. questionString = question;
  695. categoryString = categoryId.ToString();
  696. answerString = answer.ToString();
  697. byte r = (byte)reader.GetInt32(5);
  698. byte g = (byte)reader.GetInt32(6);
  699. byte b = (byte)reader.GetInt32(7);
  700. byte a = (byte)reader.GetInt32(8);
  701. questionCategoryColor = new Color32(r, g, b, a);
  702. }
  703. reader.Close();
  704. string saveSentQuestionSql = "INSERT INTO questionsInGame (gameId, questionId, userId) VALUES (" + gameId + ", " + id + ", (SELECT id FROM localUsers WHERE name = '" + user.Value + "'))";
  705. cmd.CommandText = saveSentQuestionSql;
  706. cmd.ExecuteNonQuery();
  707. cmd.Dispose();
  708. conn.Close();
  709. }
  710. NewQuestionData q = new NewQuestionData(answerString, questionString, categoryName, categoryId, id, questionCategoryColor, false);
  711. return q;
  712. }
  713. public void SavePlayersQuestion(List<int> questionsToSave, string playerNameValue, int gameId, string gameMode)
  714. {
  715. if (gameMode.Equals(Constants.ONLINE))
  716. {
  717. OnlineDatabase.Instance.SavePlayersQuestion(questionsToSave, playerNameValue, gameId);
  718. }
  719. else
  720. {
  721. SetLocalOrOnline(gameMode);
  722. string values = "";
  723. foreach (int questionId in questionsToSave)
  724. {
  725. values += "('" + playerNameValue + "'," + questionId + "," + gameId + "),";
  726. }
  727. values = values.Substring(0, values.Length - 1);
  728. string sql = "INSERT OR IGNORE INTO usersLockedQuestions (playerName, questionId, gameId) VALUES " + values;
  729. IDbConnection conn = new SqliteConnection(databaseUrl);
  730. conn.Open();
  731. IDbCommand cmd = conn.CreateCommand();
  732. cmd.CommandText = sql;
  733. cmd.ExecuteReader();
  734. cmd.Dispose();
  735. conn.Close();
  736. }
  737. }
  738. public List<NewQuestionData> GetPlayerQuestions(int gameId, string playerNameValue, string gameMode)
  739. {
  740. if (gameMode.Equals(Constants.ONLINE))
  741. {
  742. return OnlineDatabase.Instance.GetPlayerQuestions(gameId, playerNameValue);
  743. }
  744. if (databaseUrl == null)
  745. {
  746. SetLocalOrOnline(GetGameMode(gameId));
  747. }
  748. List<NewQuestionData> questions = new List<NewQuestionData>();
  749. if (connectionType.Equals(Constants.LOCAL))
  750. {
  751. string sql = "SELECT * FROM questions inner join questionToCategory on questions.id = questionToCategory.questionId INNER JOIN category ON category.id = questionToCategory.categoryId WHERE questions.id IN ( SELECT questionId FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerNameValue + "') ORDER BY answer ASC";
  752. IDbConnection conn = new SqliteConnection(databaseUrl);
  753. conn.Open();
  754. IDbCommand cmd = conn.CreateCommand();
  755. cmd.CommandText = sql;
  756. IDataReader reader = cmd.ExecuteReader();
  757. while (reader.Read())
  758. {
  759. Color32 questionCategoryColor = new Color32((byte)reader.GetInt32(7), (byte)reader.GetInt32(8), (byte)reader.GetInt32(9), (byte)reader.GetInt32(10));
  760. NewQuestionData questionData = new NewQuestionData(
  761. reader.GetInt32(2).ToString(),
  762. reader.GetString(1),
  763. reader.GetString(6),
  764. reader.GetInt32(5),
  765. reader.GetInt32(0),
  766. questionCategoryColor,
  767. true);
  768. questions.Add(questionData);
  769. }
  770. cmd.Dispose();
  771. conn.Close();
  772. }
  773. return questions;
  774. }
  775. /* private IEnumerator GetQuestionData(bool showAnswer) {
  776. UnityWebRequest www = UnityWebRequest.Get("narkampen.nordh.xyz/narKampen/dbFiles/Question.php");
  777. yield return www.SendWebRequest();
  778. if (www.isNetworkError || www.isHttpError) {
  779. Debug.Log(www.error);
  780. } else {
  781. while (!www.isDone) {
  782. yield return null;
  783. }
  784. // Show result
  785. string jsonData = www.downloadHandler.text;
  786. jsonData = "{\"questionsList\" : [ " + jsonData + " ]}";
  787. Questions qe = new Questions();
  788. JsonUtility.FromJsonOverwrite(jsonData, qe);
  789. questionString = qe.questionsList[0].question;
  790. answerString = qe.questionsList[0].answer;
  791. idString = qe.questionsList[0].id;
  792. categoryString = qe.questionsList[0].category;
  793. }
  794. } */
  795. }