Files
unity-application/Assets/SpellingBee/Scripts/GameController.cs
2023-03-26 18:01:51 +00:00

457 lines
12 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public partial class GameController : MonoBehaviour
{
/// <summary>
/// All of the words that can be used in this session
/// </summary>
//private string[] words;
private List<Learnable> words = new List<Learnable>();
/// <summary>
/// Where we currently are in the word
/// </summary>
private int letterIndex;
/// <summary>
/// Where we currently are in the word list
/// </summary>
private int wordIndex;
/// <summary>
/// The word that is currently being spelled
/// </summary>
private string currentWord;
/// <summary>
/// All of the available themes
/// </summary>
public ThemeList themeList;
/// <summary>
/// The theme we are currently using
/// </summary>
private Theme currentTheme;
/// <summary>
/// Current value of timer in seconds
/// </summary>
private float timerValue;
/// <summary>
/// Indicates if the game is still going
/// </summary>
private bool gameEnded;
/// <summary>
/// Amount of seconds user gets per letter of the current word
/// Set to 1 for testing; should be increased later
/// </summary>
private const int secondsPerLetter = 5;
/// <summary>
/// Counter that keeps track of how many letters have been spelled correctly
/// </summary>
private int correctLetters;
/// <summary>
/// Counter that keeps track of how many letters have been spelled incorrectly
/// </summary>
private int incorrectLetters;
/// <summary>
/// Counter that keeps track of how many words have been spelled correctly
/// </summary>
private int spelledWords;
/// <summary>
/// Timer that keeps track of when the game was started
/// </summary>
private DateTime startTime;
/// <summary>
/// Reference to the user list to access the current user
/// </summary>
public UserList userList;
/// <summary>
/// Reference to the current user
/// </summary>
private User user;
/// <summary>
/// Reference to the minigame ScriptableObject
/// </summary>
public Minigame minigame;
/// <summary>
/// We keep the minigamelist as well so that the minigame-index doesn't get reset
/// DO NOT REMOVE
/// </summary>
public MinigameList minigamelist;
/// <summary>
/// Letter prefab
/// </summary>
public GameObject letterPrefab;
/// <summary>
/// Reference to letter container
/// </summary>
public Transform letterContainer;
/// <summary>
/// The Image component for displaying the appropriate sprite
/// </summary>
public Image wordImage;
/// <summary>
/// Timer display
/// </summary>
public TMP_Text timerText;
/// <summary>
/// Bonus time display
/// </summary>
public GameObject bonusTimeText;
/// <summary>
/// Timer to display the bonus time
/// </summary>
private float bonusActiveRemaining = 0.0f;
/// <summary>
/// The GameObjects representing the letters
/// </summary>
private List<GameObject> letters = new List<GameObject>();
/// <summary>
/// Reference to the scoreboard
/// </summary>
public Transform Scoreboard;
/// <summary>
/// Accuracy feeback object
/// </summary>
public Feedback feedback;
/// <summary>
/// Reference to the gameEnded panel, so we can update its display
/// </summary>
public GameObject gameEndedPanel;
/// <summary>
/// Start is called before the first frame update
/// </summary>
public void Start()
{
correctLetters = 0;
incorrectLetters = 0;
words.Clear();
// We use -1 instead of 0 so SetNextWord can simply increment it each time
spelledWords = -1;
wordIndex = 0;
gameEnded = false;
timerValue = 30.0f;
bonusActiveRemaining = 0.0f;
startTime = DateTime.Now;
gameEndedPanel.SetActive(false);
bonusTimeText.SetActive(false);
// Create entry in current user for keeping track of progress
userList.Load();
user = userList.GetCurrentUser();
Progress progress = user.GetMinigameProgress(minigame.index);
if (progress == null)
{
progress = new Progress();
progress.AddOrUpdate<MinigameIndex>("minigameIndex", MinigameIndex.SPELLING_BEE);
progress.AddOrUpdate<List<Score>>("highestScores", new List<Score>());
progress.AddOrUpdate<List<Score>>("latestScores", new List<Score>());
user.minigames.Add(progress);
}
userList.Save();
currentTheme = minigame.themeList.themes[minigame.themeList.currentThemeIndex];
feedback.signPredictor.model = currentTheme.model;
words.AddRange(currentTheme.learnables);
ShuffleWords();
NextWord();
// Set calllbacks
feedback.getSignCallback = () =>
{
if (letterIndex < currentWord.Length)
{
return currentWord[letterIndex].ToString().ToUpper();
}
return null;
};
feedback.predictSignCallback = (sign) =>
{
bool successful = sign.ToUpper() == currentWord[letterIndex].ToString().ToUpper();
if (successful)
{
AddSeconds(secondsPerLetter);
}
NextLetter(successful);
};
}
/// <summary>
/// Update is called once per frame
/// </summary>
public void Update()
{
if (!gameEnded)
{
timerValue -= Time.deltaTime;
if (bonusActiveRemaining <= 0.0 && bonusTimeText.activeSelf)
{
bonusTimeText.SetActive(false);
}
else
{
bonusActiveRemaining -= Time.deltaTime;
}
if (timerValue <= 0.0f)
{
timerValue = 0.0f;
ActivateGameOver();
}
int minutes = Mathf.FloorToInt(timerValue / 60.0f);
int seconds = Mathf.FloorToInt(timerValue % 60.0f);
timerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}
}
/// <summary>
/// Randomly shuffle the list of words
/// </summary>
public void ShuffleWords()
{
for (int i = words.Count - 1; i > 0; i--)
{
// Generate a random index between 0 and i (inclusive)
int j = UnityEngine.Random.Range(0, i + 1);
// Swap the values at indices i and j
(words[j], words[i]) = (words[i], words[j]);
}
}
/// <summary>
/// Calculate the score
/// </summary>
/// <returns>The calculated score</returns>
public int CalculateScore()
{
return spelledWords * 5 + correctLetters;
}
/// <summary>
/// Displays the game over panel and score values
/// </summary>
public void ActivateGameOver()
{
gameEnded = true;
DeleteWord();
// Save the scores and show the scoreboard
SaveScores();
gameEndedPanel.GetComponent<GameEndedPanel>().GenerateContent(
startTime: startTime,
totalWords: spelledWords,
correctLetters: correctLetters,
incorrectLetters: incorrectLetters,
result: "VERLOREN",
score: CalculateScore()
);
gameEndedPanel.SetActive(true);
}
/// <summary>
/// Display win screen
/// </summary>
public void ActivateWin()
{
gameEnded = true;
DeleteWord();
// Save the scores and show the scoreboard
SaveScores();
gameEndedPanel.GetComponent<GameEndedPanel>().GenerateContent(
startTime: startTime,
totalWords: spelledWords,
correctLetters: correctLetters,
incorrectLetters: incorrectLetters,
result: "GEWONNEN",
score: CalculateScore()
);
gameEndedPanel.SetActive(true);
}
/// <summary>
/// Update and save the scores
/// </summary>
public void SaveScores()
{
// Calculate new score
int newScore = CalculateScore();
// Save the score as a tuple: < int score, string time ago>
Score score = new Score();
score.scoreValue = newScore;
score.time = DateTime.Now.ToString();
// Save the new score
user = userList.GetCurrentUser();
Progress progress = user.GetMinigameProgress(minigame.index);
// Get the current list of scores
List<Score> latestScores = progress.Get<List<Score>>("latestScores");
List<Score> highestScores = progress.Get<List<Score>>("highestScores");
// Add the new score
latestScores.Add(score);
highestScores.Add(score);
// Sort the scores
highestScores.Sort((a, b) => b.scoreValue.CompareTo(a.scoreValue));
// Only save the top 10 scores, so this list doesn't keep growing endlessly
progress.AddOrUpdate<List<Score>>("latestScores", latestScores.Take(10).ToList());
progress.AddOrUpdate<List<Score>>("highestScores", highestScores.Take(10).ToList());
userList.Save();
}
/// <summary>
/// Delete all letter objects
/// </summary>
public void DeleteWord()
{
for (int i = 0; i < letters.Count; i++)
{
Destroy(letters[i]);
}
letters.Clear();
}
/// <summary>
/// Adds seconds to timer
/// </summary>
/// <param name="seconds"></param>
public void AddSeconds(int seconds)
{
timerValue += (float)seconds;
bonusTimeText.SetActive(true);
bonusActiveRemaining = 2.0f;
}
/// <summary>
/// Display the next letter
/// </summary>
/// <param name="successful">true if the letter was correctly signed, false otherwise</param>
public void NextLetter(bool successful)
{
if (gameEnded) { return; }
// Change color of current letter (skip spaces)
if (successful)
{
correctLetters++;
letters[letterIndex].GetComponent<Image>().color = Color.green;
}
else
{
incorrectLetters++;
letters[letterIndex].GetComponent<Image>().color = new Color(0.5f, 0.0f, 0.0f);
}
do
{
letterIndex++;
} while (letterIndex < currentWord.Length && currentWord[letterIndex] == ' ');
// Change the color of the next letter or change to new word
if (letterIndex < currentWord.Length)
{
letters[letterIndex].GetComponent<Image>().color = Color.yellow;
}
else
{
StartCoroutine(Wait());
NextWord();
}
}
/// <summary>
/// Display next word in the series
/// </summary>
public void NextWord()
{
DeleteWord();
spelledWords++;
if (wordIndex < words.Count)
{
currentWord = words[wordIndex].name;
letterIndex = 0;
DisplayWord(currentWord);
wordIndex++;
}
else
{
ActivateWin();
}
}
/// <summary>
/// Displays the word that needs to be spelled
/// </summary>
/// <param name="word">The word to display</param>
public void DisplayWord(string word)
{
for (int i = 0; i < word.Length; i++)
{
// Create instance of prefab
GameObject instance = GameObject.Instantiate(letterPrefab, letterContainer);
letters.Add(instance);
// Dynamically load appearance
char c = Char.ToUpper(word[i]);
Image background = instance.GetComponent<Image>();
background.color = i == 0 ? Color.yellow : c != ' ' ? Color.red : Color.clear;
TMP_Text txt = instance.GetComponentInChildren<TMP_Text>();
txt.text = Char.ToString(c);
}
wordImage.sprite = words[wordIndex].image;
}
/// <summary>
/// wait for 2 seconds
/// </summary>
/// <returns></returns>
private IEnumerator Wait()
{
yield return new WaitForSecondsRealtime(2);
}
}