Database.cs 28 KB

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