Database.cs 30 KB

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