| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using Mono.Data.Sqlite;
- using System.Data;
- using System;
- using UnityEngine.Networking;
- using System.IO;
- public class Database : MonoBehaviour {
- private const string onlineQuestionsUrl = "nordh.xyz/narKampen/dbFiles/Question.php";
- private const string serverUrl = "nordh.xyz/narKampen/dbFiles/";
- string connectionType;
- string databaseUrl;
- string gameMode;
- int winAmount = -1;
- int questionTimer = -1;
- public GameObject questionCardPrefab;
- private static Database instance;
- public static Database Instance { get { return instance; } }
- IDbConnection conn;
- private void Awake() {
- if (instance == null) {
- instance = this;
- }
- }
- internal List<CategoryPanel.Category> GetCategories() {
- List<CategoryPanel.Category> list = new List<CategoryPanel.Category>();
- string sql = "SELECT name, r, g, b, a, id FROM category";
- IDbCommand cmd = GetConnection();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- while (reader.Read()) {
- CategoryPanel.Category cat = new CategoryPanel.Category();
- byte r = (byte)reader.GetInt32(1);
- byte g = (byte)reader.GetInt32(2);
- byte b = (byte)reader.GetInt32(3);
- byte a = (byte)reader.GetInt32(4);
- cat.color = new Color32(r, g, b, a);
- cat.name = reader.GetString(0);
- cat.id = reader.GetInt32(5);
- list.Add(cat);
- }
- CloseConnection();
- return list;
- }
- internal void SetupNewOnlineGame(int limitPerQuestion, int limitPerPlayer, int toWin, List<InviteSearchResult> inviteUsers) {
- List<int> playerIds = new List<int>();
- inviteUsers.ForEach(i => playerIds.Add(i.GetId()));
- int currentUser = Database.Instance.GetSignedInUser().Key;
- playerIds.Add(currentUser);
- var form = new WWWForm();
- form.AddField("currentUser", currentUser);
- form.AddField("winNumber", toWin);
- form.AddField("limitPerQuestion", limitPerQuestion);
- form.AddField("limitPerPlayer", limitPerPlayer);
- form.AddField("playerIds", String.Join(",", playerIds));
- Debug.Log(CallOnlineDatabaseWithResponse("NewOnlineGame.php", form));
- }
- [Serializable]
- public class Question {
- public string question;
- public string answer;
- public string id;
- public string category;
- }
- [Serializable]
- public class Questions {
- public List<Question> questionsList = new List<Question>();
- }
- [Serializable]
- public class PlayerInfo {
- public string username;
- public string status;
- }
- [Serializable]
- public class PlayerInfos {
- public List<PlayerInfo> playerInfoList = new List<PlayerInfo>();
- }
- [Serializable]
- public class OnlineGame {
- public string id;
- public string winNumber;
- public string answerTimer;
- public string roundTimeLimit;
- public string currentPlayer;
- public string round;
- public string startDate;
- public string LastPlayedDate;
- public string finishedDate;
- public string status;
- }
- [Serializable]
- public class OnlineGames {
- public List<OnlineGame> onlineGamesList = new List<OnlineGame>();
- }
-
- [Serializable]
- public class UserName {
- public string id;
- public string username;
- }
- [Serializable]
- public class UserNames {
- public List<UserName> usernamesList = new List<UserName>();
- }
- private void CallDatabase(string filename, WWWForm formData) {
- string postUrl = serverUrl + filename;
- UnityWebRequest www = UnityWebRequest.Post(postUrl, formData);
- www.SendWebRequest();
- if (www.isNetworkError || www.isHttpError) {
- Debug.Log(www.error);
- } else {
- while (!www.isDone) {
- }
- }
- }
- private string CallOnlineDatabaseWithResponse(string filename, WWWForm formData) {
- string postUrl = serverUrl + filename;
- UnityWebRequest www = UnityWebRequest.Post(postUrl, formData);
- www.SendWebRequest();
- if (www.isNetworkError || www.isHttpError) {
- Debug.Log(www.error);
- } else {
- while (!www.isDone) {
- }
- }
- return www.downloadHandler.text;
- }
- internal void SetLastPlayedDate(int gameId) {
- string sql = "UPDATE game SET lastPlayedDate = DATE() WHERE id = " + gameId;
- IDbCommand cmd = GetConnection();
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- CloseConnection();
- }
- private IDbCommand GetConnection() {
- if (databaseUrl == null) { // ej bra lösning för online
- SetLocalOrOnline("Local");
- }
- conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- return cmd;
- }
- private void CloseConnection() {
- conn.Close();
- }
- string questionString = "";
- string answerString = "";
- string idString = "";
- string categoryString = "";
- private int round = -1;
- private string SearchString;
- public string QuestionString { get => questionString; set => questionString = value; }
- private void Start() {
- if (instance == null) {
- instance = this;
- }
- if (databaseUrl == null || databaseUrl.Equals("")) {
- SetLocalOrOnline("Local"); // Temporary, should not be needed after local testing
- }
- }
- internal void KeepSignedIn(string username, int userId, bool keepSigendIn) {
- int ksi = 0;
- if (keepSigendIn) {
- ksi = 1;
- }
- string sql = "INSERT OR REPLACE INTO userSettings (username, userId, keepSignedIn) VALUES ('" + username + "', " + userId + "," + ksi + ")";
- IDbCommand cmd = GetConnection();
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- CloseConnection();
- }
- internal bool IsKeepSignedIn() {
- string sql = "SELECT keepSignedIn FROM userSettings";
- IDbCommand cmd = GetConnection();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- int res = 0;
- while (reader.Read()) {
- res = reader.GetInt32(0);
- }
- return res == 1;
- }
- internal KeyValuePair<int, string> GetSignedInUser() {
- string sql = "SELECT userId, username FROM userSettings";
- IDbCommand cmd = GetConnection();
- cmd.CommandText = sql;
- int userId = -1;
- string username = "";
- IDataReader reader = cmd.ExecuteReader();
- while (reader.Read()) {
- userId = reader.GetInt32(0);
- username = reader.GetString(1);
- }
- CloseConnection();
- return new KeyValuePair<int, string>(userId, username);
- }
- internal void LogoutUser() {
- // string sql = "UPDATE userSettings SET keepSignedIn = 0";
- string sql = "DELETE FROM userSettings";
- IDbCommand cmd = GetConnection();
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- CloseConnection();
- }
- internal int GetQuestionTimer(int gameId) {
- if (questionTimer == -1) {
- string sql = "SELECT answerTimer FROM game WHERE id = " + gameId;
- if (databaseUrl == null) {
- SetLocalOrOnline("Local");
- }
- IDbCommand cmd = GetConnection();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- while (reader.Read()) {
- questionTimer = reader.GetInt32(0);
- }
- reader.Close();
- cmd.Dispose();
- }
- CloseConnection();
- return this.questionTimer;
- }
- internal void DeclineOnlineGame(string userName, int gameId) {
- WWWForm formData = new WWWForm();
- formData.AddField("userId", -1);
- formData.AddField("f", "decline");
- formData.AddField("gameId", gameId);
- formData.AddField("userName", userName);
- CallDatabase("OnlineGames.php", formData);
- }
- internal void AcceptOnlineGame(string userName, int gameId) {
- WWWForm formData = new WWWForm();
- formData.AddField("userId", -1);
- formData.AddField("f", "accept");
- formData.AddField("gameId", gameId);
- formData.AddField("userName", userName);
- CallDatabase("OnlineGames.php", formData);
- }
- internal List<OnlineGameScript> GetOnlineGames(int userId, string userName, GameObject prefab) {
- WWWForm formData = new WWWForm();
- formData.AddField("userId", userId);
- formData.AddField("f", "list");
- formData.AddField("gameId", -1);
- formData.AddField("userName", userName);
- string response = CallOnlineDatabaseWithResponse("OnlineGames.php", formData);
- if (response.Equals("No games found for user")) {
- return null;
- }
- response = "{\"onlineGamesList\" : " + response + " }";
- OnlineGames og = new OnlineGames();
- JsonUtility.FromJsonOverwrite(response, og);
- GameObject onlineGameObject;
- OnlineGameScript ogs = null;
- List<OnlineGameScript> games = new List<OnlineGameScript>();
- foreach (OnlineGame game in og.onlineGamesList) {
- onlineGameObject = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
- ogs = onlineGameObject.GetComponent<OnlineGameScript>();
- ogs.SetGameStatus(game.status);
- Int32.TryParse(game.id, out int gameId);
- List<KeyValuePair<string, string>> playerInfos = GetGameInfo(gameId);
- if (game.status.Equals("PENDING")) {
- string extraInfo = "";
- foreach (KeyValuePair<string, string> s in playerInfos) {
- if (s.Value.Equals("WAITING") && s.Key.Equals(userName)) {
- ogs.SetGameStatus("INVITED");
- extraInfo += s.Key + ",";
- } else if (s.Value.EndsWith("WAITING")) {
- extraInfo += s.Key + ",";
- }
- }
- extraInfo = extraInfo.TrimEnd(',');
- ogs.SetGameStatusText(extraInfo);
- } else if (game.status.Equals("OTHERS_TURN")) { // Wont work
- ogs.SetGameStatusText(game.currentPlayer);
- } else {
- ogs.SetGameStatusText();
- }
- ogs.SetId(game.id);
- ogs.SetWinNumber(game.winNumber);
- ogs.SetAnswerTimer(game.answerTimer);
- ogs.SetRoundTimeLimit(game.roundTimeLimit);
- ogs.CurrentPlayer = game.currentPlayer;
- ogs.SetRound(game.round);
- ogs.StartDate = game.startDate;
- games.Add(ogs);
- ogs.PlayerInfos = playerInfos;
- }
- return games;
- }
- internal List<KeyValuePair<string, string>> GetGameInfo(int gameId) {
- List<KeyValuePair<string, string>> returnList = new List<KeyValuePair<string, string>>();
- WWWForm form = new WWWForm();
- form.AddField("gameId", gameId);
- string response = CallOnlineDatabaseWithResponse("OnlineGameInfo.php", form);
- response = "{\"playerInfoList\" : " + response + " }";
- PlayerInfos pi = new PlayerInfos();
- JsonUtility.FromJsonOverwrite(response, pi);
- foreach (PlayerInfo p in pi.playerInfoList) {
- KeyValuePair<string, string> player = new KeyValuePair<string, string>(p.username, p.status);
- returnList.Add(player);
- }
- return returnList;
- }
- internal List<LocalGameScript> GetLocalGames(GameObject prefab) {
- List<LocalGameScript> games = new List<LocalGameScript>();
- 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";
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- int currentGame = -1;
- GameObject localGame;
- LocalGameScript lgs = null;
- string currentPlayerName = "";
- int currentPoints = 0;
- while (reader.Read()) {
- if (currentGame != reader.GetInt32(0)) {
- localGame = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
- lgs = localGame.GetComponent<LocalGameScript>();
- lgs.GameId = reader.GetInt32(0);
- lgs.GameMode = reader.GetString(1);
- lgs.QuestionsNeededToWin = reader.GetInt32(2).ToString();
- lgs.AnswerTimer = reader.GetInt32(3);
- lgs.NumberOfPlayers = reader.GetInt32(4).ToString();
- lgs.CurrentPlayer = reader.GetString(5);
- lgs.Round = reader.GetInt32(6).ToString();
- lgs.StartDate = reader.GetString(7);
- lgs.LastPlayedDate = reader.GetString(8);
- lgs.FinishedDate = reader.IsDBNull(9) ? "" : reader.GetString(9);
- currentPlayerName = reader.GetString(10);
- currentPoints = GetPlayerPoints(reader.GetInt32(0), currentPlayerName);
- lgs.AddPlayer(currentPlayerName, currentPoints);
- games.Add(lgs);
- } else if (currentGame == reader.GetInt32(0)) {
- currentPlayerName = reader.GetString(10);
- currentPoints = GetPlayerPoints(currentGame, currentPlayerName);
- lgs.AddPlayer(currentPlayerName, currentPoints);
- }
- currentGame = reader.GetInt32(0);
- }
- reader.Close();
- cmd.Dispose();
- conn.Close();
- return games;
- }
- internal void SetQuestionsLost(int gameId, string playerName, int questionsLost) {
- string sql = "UPDATE localGamePlayers SET questionsLost = questionsLost + " + questionsLost + " WHERE gameId = " + gameId + " AND playerId = (SELECT id FROM localUsers WHERE name = '" + playerName + "')";
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- conn.Close();
- }
- internal void RemoveGame(int gameId) {
- string sql = "DELETE FROM game WHERE id = " + gameId;
- List<LocalGameScript> games = new List<LocalGameScript>();
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- string deleteLockedQuestionsSql = "DELETE FROM usersLockedQuestions WHERE gameId = " + gameId;
- cmd.CommandText = deleteLockedQuestionsSql;
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- conn.Close();
- }
- public string GetCurrentPlayer(int gameId) {
- string sql = "SELECT currentPlayer FROM game WHERE id = " + gameId;
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- string currentPlayer = "";
- while (reader.Read()) {
- currentPlayer = reader.GetString(0);
- }
- reader.Close();
- cmd.Dispose();
- conn.Close();
- return currentPlayer;
- }
- public void SetCurrentPlayer(int gameId, string currentPlayer) {
- string sql = "UPDATE game SET currentPlayer = '" + currentPlayer + "' WHERE id = " + gameId;
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- conn.Close();
- }
- internal int GetPlayerPoints(int gameId, string playerName) {
- string sql = "SELECT count(*) FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerName + "'";
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- int points = 0;
- while (reader.Read()) {
- points = reader.GetInt32(0);
- }
- reader.Close();
- cmd.Dispose();
- conn.Close();
- return points;
- }
- internal void SetFinishedDate(int gameId, string finishedDate) {
- string sql = "UPDATE game SET finishedDate = '" + finishedDate + "' WHERE id = " + gameId;
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- conn.Close();
- }
- internal void SetRoundValue(int gameId, int round) {
- string sql = "UPDATE game SET round = " + round + " WHERE id = " + gameId;
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- conn.Close();
- }
- internal int GetRoundValue(int gameId) {
- if (this.round == -1) {
- string sql = "SELECT round FROM game WHERE id = " + gameId;
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- while (reader.Read()) {
- this.round = reader.GetInt32(0);
- }
- reader.Close();
- cmd.Dispose();
- conn.Close();
- }
- return this.round;
- }
- internal List<KeyValuePair<string, int>> GetPlayersForGame(int gameId) {
- string sql = "SELECT name, (SELECT count(*) FROM usersLockedQuestions WHERE playerName = localUsers.name AND gameId = " + gameId + ") as numAnswers FROM localGamePlayers " +
- "LEFT JOIN localUsers ON localGamePlayers.playerId = localUsers.id " +
- "WHERE gameId = " + gameId;
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- List<KeyValuePair<string, int>> returnList = new List<KeyValuePair<string, int>>();
- while (reader.Read()) {
- KeyValuePair<string, int> player = new KeyValuePair<string, int>(reader.GetString(0), reader.GetInt32(1));
- returnList.Add(player);
- }
- return returnList;
- }
- public string AnswerString { get => answerString; set => answerString = value; }
- public string IdString { get => idString; set => idString = value; }
- public string CategoryString { get => categoryString; set => categoryString = value; }
- public void SetLocalOrOnline(string type) {
- gameMode = type;
- if (type.Equals("Local")) {
- string databaseName = "narKampenLocal.db";
- if (Application.platform == RuntimePlatform.Android) {
- databaseUrl = Application.persistentDataPath + "/" + databaseName;
- if (!File.Exists(databaseUrl)) {
- UnityWebRequest load = UnityWebRequest.Get("jar:file://" + Application.dataPath + "!/assets/" + databaseName);
- load.SendWebRequest();
- while (!load.isDone) { }
- File.WriteAllBytes(databaseUrl, load.downloadHandler.data);
- }
- databaseUrl = "URI=file:" + databaseUrl;
- } else {
- databaseUrl = "URI=file:" + Application.dataPath + "/narKampenLocal.db";
- }
- } else {
- databaseUrl = onlineQuestionsUrl;
- }
- connectionType = type;
- }
- internal int GetQuestionsLost(int gameId, string playerName) {
- string sql = "SELECT questionsLost FROM localGamePlayers WHERE gameId = " + gameId + " AND playerId = (SELECT id from localUsers WHERE name = '" + playerName + "')";
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- int returnValue = 0;
- while (reader.Read()) {
- returnValue = reader.GetInt32(0);
- }
- reader.Close();
- cmd.Dispose();
- conn.Close();
- return returnValue;
- }
- public string GetGameMode(int gameId) {
- if (this.gameMode == null) {
- string sql = "SELECT gameMode FROM game WHERE id = " + gameId;
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- while (reader.Read()) {
- this.gameMode = reader.GetString(0);
- }
- reader.Close();
- cmd.Dispose();
- conn.Close();
- }
- return this.gameMode;
- }
- public void LinkPlayersToLocalGame(List<string> playerNames, int gameId) {
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- string questionSql = "SELECT id FROM questions order by random() limit 1";
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = questionSql;
- IDataReader reader = cmd.ExecuteReader();
- int questionId = -1;
- while (reader.Read()) {
- questionId = reader.GetInt32(0);
- }
- foreach (string player in playerNames) {
- string sql = "SELECT id FROM localUsers WHERE name = '" + player + "'";
- int playerId;
- cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- reader = cmd.ExecuteReader();
- if (reader.Read()) {
- playerId = reader.GetInt32(0);
- } else {
- reader.Close();
- sql = "INSERT INTO localUsers (name) VALUES ('" + player + "')";
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- cmd.CommandText = "SELECT last_insert_rowid()";
- Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
- playerId = (int)lastInsert64;
- }
- cmd.Dispose();
- reader.Close();
- LinkPlayerToGame(playerId, gameId);
- SavePlayersQuestion(questionId.ToString(), player, gameId);
- }
- IDbCommand cmd2 = conn.CreateCommand();
- cmd2.CommandText = "UPDATE game SET currentPlayer = '" + playerNames[0] + "' WHERE id = " + gameId;
- cmd2.ExecuteNonQuery();
- cmd2.Dispose();
- conn.Close();
- }
- private void LinkPlayerToGame(int playerId, int gameId) {
- string sql = "INSERT INTO localGamePlayers (gameId, playerId) VALUES (" + gameId + ", " + playerId + ")";
- SqliteConnection conn2 = new SqliteConnection(databaseUrl);
- conn2.Open();
- IDbCommand cmd = conn2.CreateCommand();
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- conn2.Close();
- }
- internal int GetWinCondition(int gameId) {
- if (winAmount == -1) {
- string sql = "SELECT winNumber FROM game WHERE id = " + gameId;
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- while (reader.Read()) {
- this.winAmount = reader.GetInt32(0);
- }
- reader.Close();
- cmd.Dispose();
- conn.Close();
- }
- return this.winAmount;
- }
- public int SetupNewLocalGame(int winNumber, int numberOfPlayers, int questionTimer) {
- string sql = "INSERT INTO game (winNumber, numberOfPlayers, answerTimer, gameMode, startedDate) VALUES (" + winNumber + "," + numberOfPlayers + "," + questionTimer + ", 'Local', DATE())";
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- int status = cmd.ExecuteNonQuery();
- cmd.CommandText = "SELECT last_insert_rowid()";
- Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
- return (int)lastInsert64;
- }
- public NewQuestion GetNewQuestion(List<int> userAnsweredQuestions, string userName) {
- int gameId = GameObject.Find("GameManager").GetComponent<GameManagerScript>().GameId;
- Color32 questionCategoryColor = new Color32(0, 0, 20, 20);
- if (connectionType == null) {
- SetLocalOrOnline(GetGameMode(gameId));
- }
- if (connectionType == "Local") {
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- string answeredIds = String.Join(",", userAnsweredQuestions);
- 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";
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- int id = -1;
- while (reader.Read()) {
- id = reader.GetInt32(0);
- string question = reader.GetString(1);
- int answer = reader.GetInt32(2);
- int catergoryId = reader.GetInt32(3);
- string categoryName = reader.GetString(4);
- idString = id.ToString();
- questionString = question;
- categoryString = catergoryId.ToString();
- answerString = answer.ToString();
- byte r = (byte)reader.GetInt32(5);
- byte g = (byte)reader.GetInt32(6);
- byte b = (byte)reader.GetInt32(7);
- byte a = (byte)reader.GetInt32(8);
- questionCategoryColor = new Color32(r, g, b, a);
- }
- reader.Close();
- string saveSentQuestionSql = "INSERT INTO questionsInGame (gameId, questionId, userId) VALUES (" + gameId + ", " + id + ", (SELECT id FROM localUsers WHERE name = '" + userName + "'))";
- cmd.CommandText = saveSentQuestionSql;
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- conn.Close();
- } else { // Connect Through db
- Debug.Log("Online Call");
- StartCoroutine(GetQuestionData(false));
- }
- NewQuestion q = NewQuestion.Instance();
- q.questionString = questionString;
- q.answerString = answerString;
- q.categoryString = categoryString;
- q.idString = idString;
- q.SetQuestionCategoryColor(questionCategoryColor);
- return q;
- }
- public void SavePlayersQuestion(string questionId, string playerNameValue, int gameId) {
- if (databaseUrl == null) {
- SetLocalOrOnline(GetGameMode(gameId));
- }
- Int32.TryParse(questionId, out int qId);
- string sql = "INSERT OR IGNORE INTO usersLockedQuestions (playerName, questionId, gameId) VALUES ('" + playerNameValue + "'," + qId + "," + gameId + ")";
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- cmd.ExecuteReader();
- cmd.Dispose();
- conn.Close();
- }
- public List<QuestionCard> GetPlayerQuestions(int gameId, string playerNameValue) {
- if (databaseUrl == null) {
- SetLocalOrOnline(GetGameMode(gameId));
- }
- List<QuestionCard> questions = new List<QuestionCard>();
- if (connectionType.Equals("Local")) {
- 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";
- IDbConnection conn = new SqliteConnection(databaseUrl);
- conn.Open();
- IDbCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- IDataReader reader = cmd.ExecuteReader();
- while (reader.Read()) {
- GameObject question = Instantiate(questionCardPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
- QuestionCard q = question.GetComponent<QuestionCard>();
- q.SetAnswerText(reader.GetInt32(2).ToString());
- q.SetQuestionText(reader.GetString(1));
- q.idString = reader.GetInt32(0).ToString();
- Color32 questionCategoryColor = new Color32((byte)reader.GetInt32(7), (byte)reader.GetInt32(8), (byte)reader.GetInt32(9), (byte)reader.GetInt32(10));
- q.SetQuestionCategoryColor(questionCategoryColor);
- questions.Add(q);
- }
- cmd.Dispose();
- conn.Close();
- }
- return questions;
- }
- private IEnumerator GetQuestionData(bool showAnswer) {
- UnityWebRequest www = UnityWebRequest.Get("nordh.xyz/narKampen/dbFiles/Question.php");
- yield return www.SendWebRequest();
- if (www.isNetworkError || www.isHttpError) {
- Debug.Log(www.error);
- } else {
- while (!www.isDone) {
- yield return null;
- }
- // Show result
- string jsonData = www.downloadHandler.text;
- jsonData = "{\"questionsList\" : [ " + jsonData + " ]}";
- Questions qe = new Questions();
- JsonUtility.FromJsonOverwrite(jsonData, qe);
- questionString = qe.questionsList[0].question;
- answerString = qe.questionsList[0].answer;
- idString = qe.questionsList[0].id;
- categoryString = qe.questionsList[0].category;
- }
- }
- public List<UserName> GetUsersToInvite(string searchString) {
- string postUrl = "nordh.xyz/narKampen/dbFiles/PlayerSearch.php?";
- postUrl += "search=" + UnityWebRequest.EscapeURL(searchString);
- UserNames uNames = new UserNames();
- UnityWebRequest www = UnityWebRequest.Get(postUrl);
- www.SendWebRequest();
- if (www.isNetworkError || www.isHttpError) {
- Debug.Log(www.error);
- } else {
- while (!www.isDone) {
- }
- // Show result
- string jsonData = www.downloadHandler.text;
- jsonData = "{\"usernamesList\" : " + jsonData + " }";
- JsonUtility.FromJsonOverwrite(jsonData, uNames);
- }
- // TODO handle empty
- return uNames.usernamesList;
- }
- }
|