Snaparazzi/Assets/Scripts/RoomManager.cs

467 lines
15 KiB
C#
Raw Normal View History

2024-01-27 14:08:12 +00:00
using Firebase.Database;
2024-01-27 14:54:23 +00:00
using Firebase.Extensions;
2024-01-27 18:58:02 +00:00
using System;
using System.Collections.Generic;
2024-01-27 14:54:23 +00:00
using TMPro;
2024-01-27 09:19:32 +00:00
using UnityEngine;
2024-01-27 18:54:06 +00:00
using Newtonsoft.Json;
using System.Linq;
using System.Collections;
using UnityEditor.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.Localization;
using UnityEngine.Localization.Tables;
2024-01-27 09:19:32 +00:00
public class RoomManager : MonoBehaviour
{
public static RoomManager Instance;
2024-01-27 21:24:50 +00:00
[Header("Waiting For Players Page")]
public GameObject waitingForPlayersPage;
/// <summary>
/// TextMeshPro that show the value of the current rooom code
/// </summary>
public TextMeshProUGUI roomCodeLabel;
public AudioClip playerJoinSFX;
2024-01-31 21:04:51 +00:00
public List<PlayerSticker> playerStickers = new List<PlayerSticker>();
2024-01-27 09:19:32 +00:00
2024-01-27 22:07:41 +00:00
[Header("Explanation Page")]
public GameObject explanationPage;
2024-01-28 00:03:16 +00:00
public TextMeshProUGUI explanationCounter;
public float explanationTime;
2024-01-27 22:07:41 +00:00
private DateTime endOfExplanationDate = DateTime.MinValue;
2024-01-28 00:03:16 +00:00
public AudioClip counterSFX;
2024-01-27 22:07:41 +00:00
2024-01-27 21:24:50 +00:00
[Header("Waiting For Proposition Page")]
2024-01-29 18:32:07 +00:00
public WaitForPropositionsPage waitForPropositionsPage;
2024-01-27 21:24:50 +00:00
2024-01-28 12:18:40 +00:00
[Header("Waiting For Proposition Page")]
public VotingPage votingPage;
2024-01-29 22:49:48 +00:00
[Header("Scoring Page")]
public ScoringPage scoringPage;
2024-01-28 00:03:16 +00:00
[Header("Other")]
public PromptList promptList;
public StringTableCollection stringTableCollection;
/// <summary>
/// Contains all the translated string for the UI
/// </summary>
private StringTable stringTable;
public Room myRoom { get; private set; } = null;
2024-01-27 12:19:56 +00:00
2024-01-27 14:08:12 +00:00
DatabaseReference realtimeDB;
private void Awake()
{
Instance = this;
2024-01-27 14:08:12 +00:00
FirebaseInitializer.Instance.onFirebaseReady += Initialize;
stringTable = stringTableCollection.GetTable(LocalizationSettings.SelectedLocale.Identifier) as StringTable;
2024-01-27 14:08:12 +00:00
}
2024-01-27 12:19:56 +00:00
private void Start()
2024-02-04 12:57:13 +00:00
{
InitializeFirstPage();
}
private void InitializeFirstPage()
2024-01-27 12:19:56 +00:00
{
2024-01-27 23:06:23 +00:00
explanationPage.SetActive(false);
2024-01-29 18:32:07 +00:00
waitForPropositionsPage.gameObject.SetActive(false);
votingPage.gameObject.SetActive(false);
scoringPage.gameObject.SetActive(false);
2024-01-27 23:06:23 +00:00
waitingForPlayersPage.SetActive(true);
2024-01-27 22:07:41 +00:00
ResetAllPlayerLabels();
2024-01-27 18:54:06 +00:00
}
2024-01-27 22:07:41 +00:00
private void Update()
{
2024-01-27 22:47:31 +00:00
if (myRoom == null)
return;
//While Explanation State
2024-01-27 22:47:31 +00:00
if (myRoom.currentState == (int)GameState.Explanation && endOfExplanationDate != DateTime.MinValue)
2024-01-27 22:07:41 +00:00
{
TimeSpan duration = endOfExplanationDate - DateTime.Now;
2024-01-28 00:03:16 +00:00
explanationCounter.text = ((int)duration.TotalSeconds).ToString("D1");
2024-01-27 22:07:41 +00:00
if (duration.TotalMilliseconds <= 0)
{
2024-01-27 22:47:31 +00:00
SendRoomState(GameState.MakeProposition);
2024-01-27 22:07:41 +00:00
}
}
2024-01-28 00:03:16 +00:00
2024-01-27 22:07:41 +00:00
}
2024-01-27 22:47:31 +00:00
private void SendRoomState(GameState _newState)
{
//Debug.Log($"sending to RTDB that we are now in the {_newState} state", this);
2024-01-27 22:47:31 +00:00
realtimeDB.Child("rooms").Child(myRoom.code).Child("currentState").SetValueAsync((int)_newState);
}
2024-01-27 22:07:41 +00:00
private void ResetAllPlayerLabels()
2024-01-27 18:54:06 +00:00
{
string label = stringTable.GetEntry("ComputerView/Canvas/WaitingForPlayersPage/WaitingForP").LocalizedValue;
2024-01-31 21:04:51 +00:00
for (int i = 0; i < playerStickers.Count; i++)
2024-01-27 18:54:06 +00:00
{
playerStickers[i].Initialize($"{label}{i + 1}", i);
2024-01-27 18:54:06 +00:00
}
2024-01-27 14:08:12 +00:00
}
private bool deleteRoomFilesCompleted = false;
private bool deleteRealtimeDBCompleted = false;
2024-02-04 12:57:13 +00:00
private void OnApplicationQuit()
2024-01-27 14:08:12 +00:00
{
2024-02-04 12:57:13 +00:00
StartCoroutine(Coroutine_ClearCurrentRoom(() =>
2024-01-27 22:07:41 +00:00
{
2024-02-04 12:57:13 +00:00
Debug.Log("You can go. Bye bye...");
}));
2024-01-27 14:08:12 +00:00
}
private void Initialize()
{
FirebaseInitializer.Instance.onFirebaseReady -= Initialize;
realtimeDB = FirebaseDatabase.DefaultInstance.RootReference;
Debug.Log("Realtime DB initialized");
2024-02-04 12:57:13 +00:00
ClearOldAndCreateNewRoom();
}
private void ClearOldAndCreateNewRoom()
{
2024-01-28 16:34:12 +00:00
CleanOldRooms();
2024-02-04 12:57:13 +00:00
StartCoroutine(Coroutine_ClearCurrentRoom(() =>
{
CreateNewRoom();
}));
}
private IEnumerator Coroutine_ClearCurrentRoom(Action callback_OnRoomClear = null)
{
if(myRoom == null || string.IsNullOrEmpty(myRoom.code))
{
yield return null;
Debug.Log("There is no last room to clean", this);
2024-02-04 12:57:13 +00:00
callback_OnRoomClear?.Invoke();
}
else
{
realtimeDB.Child("rooms").Child(myRoom.code).ValueChanged -= OnRoomUpdate;
2024-02-04 12:57:13 +00:00
Debug.Log($"delete files of room {myRoom.code} from storage", this);
StorageManager.Instance.DeleteFileOfRoom(myRoom, () =>
{
Debug.Log($"cleaning photo files of room({myRoom.code})finish", this);
deleteRoomFilesCompleted = true;
});
Debug.Log($"delete realtimeDB room {myRoom.code}");
realtimeDB.Child("rooms").Child(myRoom.code).RemoveValueAsync().ContinueWithOnMainThread(task =>
{
Debug.Log($"room's({myRoom.code}) data has been deleted for database", this);
myRoom = null;
deleteRealtimeDBCompleted = true;
});
while (!deleteRoomFilesCompleted || !deleteRealtimeDBCompleted)
{
yield return null; // Yield until both tasks are completed
}
callback_OnRoomClear?.Invoke();
Debug.Log("Everything is clean.");
}
2024-01-27 14:54:23 +00:00
}
/// <summary>
/// Check all the rooms in the server and give back the number already taken
/// </summary>
private void WhichCodesAreAlreadyUsed(Action<List<int>> callback_OnCodesChecked)
{
2024-01-28 16:34:12 +00:00
QueryRoomsInDatabase(onlineRooms =>
2024-01-27 20:07:17 +00:00
{
2024-01-28 16:34:12 +00:00
List<int> alreadyUsedCodes = onlineRooms.Select(room => int.Parse(room.code)).ToList();
Debug.Log($"Codes {string.Join(", ", alreadyUsedCodes)} are already used by other parties", this);
callback_OnCodesChecked?.Invoke(alreadyUsedCodes);
});
2024-01-27 14:08:12 +00:00
}
/// <summary>
/// Automatically called at start of game
/// </summary>
[ContextMenu("Create New Room")]
public void CreateNewRoom()
{
2024-01-27 14:54:23 +00:00
WhichCodesAreAlreadyUsed(codes =>
{
Room newRoom = new Room(GenerateRandomAvailableCode(codes).ToString("D4"));
2024-01-27 18:54:06 +00:00
myRoom = newRoom;
2024-01-27 17:50:04 +00:00
try
2024-01-27 14:54:23 +00:00
{
2024-01-27 20:07:17 +00:00
string JSON = JsonConvert.SerializeObject(newRoom);
2024-01-27 18:54:06 +00:00
2024-01-27 17:50:04 +00:00
realtimeDB.Child("rooms").Child(newRoom.code).SetRawJsonValueAsync(JSON).ContinueWithOnMainThread(task =>
{
2024-01-27 18:54:06 +00:00
//then subscribe to it
realtimeDB.Child("rooms").Child(newRoom.code).ValueChanged += OnRoomUpdate;
roomCodeLabel.text = myRoom.code;
Debug.Log($"room {myRoom.code} has been created on the server");
2024-01-27 17:50:04 +00:00
});
2024-01-27 18:54:06 +00:00
}
2024-01-27 17:50:04 +00:00
catch (Exception e)
{
Debug.LogException(e);
}
2024-01-27 14:54:23 +00:00
});
}
/// <summary>
/// Generate a code between 0 and 1000 that is not in the list
/// </summary>
/// <param name="_impossibleCodes">the list of code you don"t want to get</param>
/// <returns></returns>
private int GenerateRandomAvailableCode(List<int> _impossibleCodes)
{
int random = UnityEngine.Random.Range(0, 1000);
while (_impossibleCodes.Contains(random))
{
Debug.Log($"{random} is already taken, choosing another room code", this);
random = UnityEngine.Random.Range(0, 1000);
}
return random;
}
2024-01-27 21:55:04 +00:00
public void GeneratePrompts()
2024-01-27 12:19:56 +00:00
{
2024-01-27 21:55:04 +00:00
System.Random rnd = new();
2024-01-28 11:54:57 +00:00
List<Prompt> prompts = promptList.prompts.OrderBy(x => rnd.Next()).Take(myRoom.players.Count()).ToList();
List<Player> players = myRoom.players.Values.ToList().OrderBy(x => rnd.Next()).ToList();
2024-01-28 14:42:32 +00:00
Dictionary<int, Question> questions = new();
2024-01-27 12:19:56 +00:00
2024-01-28 11:54:57 +00:00
for (int i = 0; i < players.Count(); i++)
2024-01-27 21:55:04 +00:00
{
2024-01-28 14:42:32 +00:00
Dictionary<int, Proposition> propositions = new();
2024-01-27 22:05:27 +00:00
2024-01-28 11:54:57 +00:00
for (int j = 0; j < 2; j++)
2024-01-27 22:05:27 +00:00
{
2024-01-29 20:30:09 +00:00
propositions.Add(j, new Proposition(players[i + j < players.Count() ? i + j : 0]));
2024-01-27 21:55:04 +00:00
}
2024-01-28 14:42:32 +00:00
questions.Add(i, new Question()
2024-01-27 21:55:04 +00:00
{
index = i,
2024-01-28 11:54:57 +00:00
promptId = prompts[i].id,
2024-01-27 21:55:04 +00:00
propositions = propositions,
creationDate = DateTime.Now.ToOADate(),
});
}
2024-01-28 12:25:17 +00:00
2024-01-27 21:55:04 +00:00
string JSON = JsonConvert.SerializeObject(questions);
realtimeDB.Child("rooms").Child(myRoom.code).Child("questions").SetRawJsonValueAsync(JSON);
2024-01-27 12:19:56 +00:00
}
/// <summary>
2024-01-27 18:54:06 +00:00
/// Automatically called when something change in your room
2024-01-27 12:19:56 +00:00
/// </summary>
2024-01-27 18:54:06 +00:00
private void OnRoomUpdate(object sender, ValueChangedEventArgs value)
2024-01-27 12:19:56 +00:00
{
2024-01-27 18:54:06 +00:00
if (value.DatabaseError != null)
2024-01-27 15:32:12 +00:00
{
2024-01-27 18:54:06 +00:00
Debug.LogError(value.DatabaseError.Message);
2024-01-27 15:32:12 +00:00
return;
}
if (value.Snapshot.Value == null)
{
Debug.Log("Trying to update room, but it's empty. Maybe you are exiting the app, so it's ok", this);
return;
}
2024-01-27 18:54:06 +00:00
string JSON = value.Snapshot.GetRawJsonValue();
2024-01-27 22:47:31 +00:00
Debug.Log($"your room has been updated :\n{JSON}");
GameState lastState = (GameState)myRoom.currentState;
2024-01-27 18:54:06 +00:00
try
{
myRoom = JsonConvert.DeserializeObject<Room>(JSON);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
//this is done only when entering a new state
if (lastState != (GameState)myRoom.currentState)
{
OnNewGameStateStarted();
}
else
{
//this is done each time something change
switch (myRoom.currentState)
{
case (int)GameState.WaitingForOtherPlayersToJoin:
UpdateConnectedPlayerList(myRoom.GetPlayerList());
break;
case (int)GameState.MakeProposition:
waitForPropositionsPage.OnRoomUpdate(myRoom);
break;
default:
break;
}
}
}
2024-01-27 12:19:56 +00:00
/// <summary>
/// Called when we enter in a new game state
/// </summary>
private void OnNewGameStateStarted()
{
2024-01-27 22:47:31 +00:00
switch (myRoom.currentState)
2024-01-27 18:54:06 +00:00
{
2024-02-04 12:57:13 +00:00
case (int)GameState.EnteringName: //if game has been reset by a player on mobile
ClearOldAndCreateNewRoom();
InitializeFirstPage();
2024-02-04 12:57:13 +00:00
break;
2024-01-27 22:47:31 +00:00
case (int)GameState.WaitingForOtherPlayersToJoin:
Debug.Log("New State : WaitingForOtherPlayersToJoin");
2024-01-27 18:54:06 +00:00
break;
2024-01-28 12:18:40 +00:00
2024-01-27 22:47:31 +00:00
case (int)GameState.Explanation:
Debug.Log("New State : Explanation");
2024-02-04 11:04:24 +00:00
scoringPage.gameObject.SetActive(false); //if we come back from a new game
2024-01-27 22:07:41 +00:00
waitingForPlayersPage.SetActive(false);
explanationPage.SetActive(true);
2024-01-28 00:03:16 +00:00
endOfExplanationDate = DateTime.Now.AddSeconds(explanationTime);
2024-01-28 14:42:54 +00:00
AudioManager.Instance.PlaySFX(counterSFX);
AudioManager.Instance.StopMusic();
//generate all the questions during the explanation
GeneratePrompts();
2024-01-27 22:07:41 +00:00
break;
2024-01-28 12:18:40 +00:00
2024-01-27 22:47:31 +00:00
case (int)GameState.MakeProposition:
Debug.Log("New State : MakeProposition");
2024-01-28 14:42:54 +00:00
AudioManager.Instance.ChangeMusic(MusicTitle.TakingPicture);
2024-01-29 18:32:07 +00:00
waitForPropositionsPage.Initialize(myRoom, () => SendRoomState(GameState.MakeVote));
2024-01-29 22:49:48 +00:00
explanationPage.SetActive(false);
2024-01-27 21:24:50 +00:00
break;
2024-01-28 12:18:40 +00:00
case (int)GameState.MakeVote:
2024-01-28 14:42:54 +00:00
AudioManager.Instance.ChangeMusic(MusicTitle.VotingSession);
2024-01-28 12:18:40 +00:00
votingPage.ShowVotingPage(
realtimeDB.Child("rooms").Child(myRoom.code)
, myRoom.players
, myRoom.questions
, () => SendRoomState(GameState.Score));
break;
case (int)GameState.Score:
2024-01-29 22:32:30 +00:00
Debug.Log("It's score time !");
2024-01-31 22:45:58 +00:00
scoringPage.Initialize(myRoom);
2024-01-28 12:18:40 +00:00
break;
2024-01-27 18:54:06 +00:00
default:
break;
}
}
2024-01-27 12:19:56 +00:00
2024-01-27 18:54:06 +00:00
/// <summary>
/// Update the player labels on the WaitingForPlayer page
/// </summary>
/// <param name="_players"></param>
private void UpdateConnectedPlayerList(List<Player> _players)
{
2024-01-28 14:42:54 +00:00
AudioManager.Instance.PlaySFX(playerJoinSFX);
2024-01-27 22:07:41 +00:00
ResetAllPlayerLabels();
//Debug.Log($"players count = {_players.Count}");
List<Player> orderedPlayers = _players.OrderBy(x => x.creationDate).ToList();
for (int i = 0; i < orderedPlayers.Count; i++)
2024-01-27 18:54:06 +00:00
{
Debug.Log($"player {i} = {orderedPlayers[i].name}");
2024-01-31 21:04:51 +00:00
playerStickers[i].Initialize(orderedPlayers[i].name, i);
2024-01-27 18:54:06 +00:00
}
2024-01-27 12:19:56 +00:00
}
2024-01-28 16:34:12 +00:00
private void QueryRoomsInDatabase(Action<List<Room>> callback)
{
//Debug.Log("Querying rooms from the database", this);
2024-01-28 16:34:12 +00:00
realtimeDB.Child("rooms").GetValueAsync().ContinueWithOnMainThread(task =>
{
if (task.IsFaulted)
{
Debug.LogException(task.Exception);
callback?.Invoke(new List<Room>());
return;
}
DataSnapshot snapshot = task.Result;
if (snapshot.Value != null)
{
string JSON = snapshot.GetRawJsonValue();
Debug.Log($"Found some rooms:\n{JSON}", this);
try
{
Dictionary<string, Room> onlineRooms = JsonConvert.DeserializeObject<Dictionary<string, Room>>(JSON);
callback?.Invoke(onlineRooms.Values.ToList());
}
catch (Exception e)
{
Debug.LogException(e);
2024-02-04 13:30:11 +00:00
Debug.Log($"Room {JSON} is broken, deleting it", this);
snapshot.Reference.RemoveValueAsync().ContinueWithOnMainThread(task =>
{
if (task.IsFaulted)
{
Debug.LogException(task.Exception);
return;
}
2024-02-04 13:30:11 +00:00
Debug.Log($"Broken room has been deleted. Checking again", this);
QueryRoomsInDatabase(callback);
});
}
2024-01-28 16:34:12 +00:00
}
else
{
Debug.Log("No rooms found in the database", this);
callback?.Invoke(new List<Room>());
}
});
}
private void CleanOldRooms()
{
QueryRoomsInDatabase(onlineRooms =>
{
DateTime oneHourLater = DateTime.Now.AddHours(1);
foreach (Room r in onlineRooms)
{
if (DateTime.FromOADate(r.creationDate) < oneHourLater)
{
Debug.Log($"Room {r.code} has been created at {DateTime.FromOADate(r.creationDate)} and it's more than one hour old.");
DeleteRoom(r.code);
2024-01-28 16:34:12 +00:00
}
}
});
}
private void DeleteRoom(string _roomCode)
{
realtimeDB.Child("rooms").Child(_roomCode).RemoveValueAsync().ContinueWithOnMainThread(task =>
{
if (task.IsFaulted)
{
Debug.LogException(task.Exception);
return;
}
Debug.Log($"Room {_roomCode} has been deleted");
});
}
2024-01-27 12:19:56 +00:00
}