Database.cs 30 KB

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