Database.cs 29 KB

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