Database.cs 30 KB

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