609 lines
18 KiB
C#
609 lines
18 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
/// <summary>
|
|
/// Contains all game logic for the JustSign game
|
|
/// </summary>
|
|
public class JustSignController : MonoBehaviour
|
|
{
|
|
/// <summary>
|
|
/// All of the words that can be used in this session
|
|
/// </summary>
|
|
private List<Learnable> words = new List<Learnable>();
|
|
|
|
/// <summary>
|
|
/// The canvas containing all components
|
|
/// </summary>
|
|
public Canvas canvas;
|
|
|
|
/// <summary>
|
|
/// The input field where the user can type his or her answer
|
|
/// </summary>
|
|
public TMP_InputField answerField;
|
|
|
|
/// <summary>
|
|
/// The feedback on the timing
|
|
/// </summary>
|
|
public TMP_Text feedBack;
|
|
|
|
/// <summary>
|
|
/// The current score
|
|
/// </summary>
|
|
public TMP_Text scoreDisplay;
|
|
|
|
/// <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>
|
|
/// Reference to the list of available songs
|
|
/// </summary>
|
|
public SongList songList;
|
|
|
|
/// <summary>
|
|
/// Reference to the currently used song
|
|
/// </summary>
|
|
private Song currentSong;
|
|
|
|
|
|
/// <summary>
|
|
/// The zone that the player should be hitting with his or her inputs
|
|
/// </summary>
|
|
public GameObject hitZone;
|
|
|
|
/// <summary>
|
|
/// Symbol prefab
|
|
/// </summary>
|
|
public GameObject symbolPrefab;
|
|
|
|
/// <summary>
|
|
/// Reference to symbol prefab
|
|
/// </summary>
|
|
public Transform symbolContainer;
|
|
|
|
/// <summary>
|
|
/// The theme we are currently using
|
|
/// </summary>
|
|
private Theme currentTheme;
|
|
|
|
/// <summary>
|
|
/// List of strings representing all words on the track
|
|
/// </summary>
|
|
private List<string> activeWords = new List<string>();
|
|
|
|
/// <summary>
|
|
/// List of objects representing all symbols on the track
|
|
/// </summary>
|
|
private List<GameObject> activeSymbols = new List<GameObject>();
|
|
|
|
/// <summary>
|
|
/// The current score
|
|
/// </summary>
|
|
private int score;
|
|
|
|
/// <summary>
|
|
/// Have the symbols started spawning or not
|
|
/// </summary>
|
|
private bool gameIsActive = false;
|
|
|
|
/// <summary>
|
|
/// Width and height of the symbols
|
|
/// </summary>
|
|
private int symbolSize = 280;
|
|
|
|
/// <summary>
|
|
/// Controls movement speed of symbols (higher -> faster)
|
|
/// </summary>
|
|
private int moveSpeed = 200;
|
|
|
|
/// <summary>
|
|
/// Starting X-coordinate of a symbol = (-1920 - symbolsize) / 2
|
|
/// </summary>
|
|
private int trackX = -1100;
|
|
|
|
/// <summary>
|
|
/// Starting Y-coordinate of a symbol
|
|
/// </summary>
|
|
private int trackY = -200;
|
|
|
|
/// <summary>
|
|
/// Max distance from hit zone to get perfect score
|
|
/// </summary>
|
|
private int perfectBoundary = 10;
|
|
|
|
/// <summary>
|
|
/// Score obtained when getting a perfect hit
|
|
/// </summary>
|
|
private int perfectScore = 5;
|
|
|
|
/// <summary>
|
|
/// Max distance from hit zone to get good score
|
|
/// </summary>
|
|
private int goodBoundary = 120;
|
|
|
|
/// <summary>
|
|
/// Score obtained when getting a good hit
|
|
/// </summary>
|
|
private int goodScore = 3;
|
|
|
|
/// <summary>
|
|
/// Max distance from hit zone to get meh score
|
|
/// </summary>
|
|
private int mehBoundary = 200;
|
|
|
|
/// <summary>
|
|
/// Score obtained when getting a meh hit
|
|
/// </summary>
|
|
private int mehScore = 1;
|
|
|
|
/// <summary>
|
|
/// Score obtained when getting a terrible hit
|
|
/// </summary>
|
|
private int terribleScore = -3;
|
|
|
|
/// <summary>
|
|
/// Score obtained when symbol goes offscreen
|
|
/// </summary>
|
|
private int offscreenScore = -5;
|
|
|
|
/// <summary>
|
|
/// Time at which the last symbol was spawned
|
|
/// </summary>
|
|
private float lastSpawn;
|
|
|
|
/// <summary>
|
|
/// Time at which the game started, needed to know when to stop
|
|
/// </summary>
|
|
private float beginTime;
|
|
|
|
/// <summary>
|
|
/// Time at which the last symbol should spawn
|
|
/// </summary>
|
|
private float lastSymbolTime;
|
|
|
|
/// <summary>
|
|
/// Counter that keeps track of how many signs get you score "perfect"
|
|
/// </summary>
|
|
private int perfectSigns;
|
|
|
|
/// <summary>
|
|
/// Counter that keeps track of how many signs get you score "good"
|
|
/// </summary>
|
|
private int goodSigns;
|
|
|
|
/// <summary>
|
|
/// Counter that keeps track of how many signs get you score "meh"
|
|
/// </summary>
|
|
private int mehSigns;
|
|
|
|
/// <summary>
|
|
/// Counter that keeps track of how many signs get you score "perfect"
|
|
/// </summary>
|
|
private int terribleSigns;
|
|
|
|
/// <summary>
|
|
/// Counter that keeps track of how many signs done incorrectly
|
|
/// </summary>
|
|
private int incorrectSigns;
|
|
|
|
/// <summary>
|
|
/// Reference to the scoreboard entries container
|
|
/// </summary>
|
|
public Transform scoreboardEntriesContainer;
|
|
|
|
/// <summary>
|
|
/// The GameObjects representing the letters
|
|
/// </summary>
|
|
private List<GameObject> scoreboardEntries = new List<GameObject>();
|
|
|
|
/// <summary>
|
|
/// Reference to the ScoreboardEntry prefab
|
|
/// </summary>
|
|
public GameObject scoreboardEntry;
|
|
|
|
/// <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>
|
|
/// LPM
|
|
/// </summary>
|
|
public TMP_Text lpmText;
|
|
|
|
/// <summary>
|
|
/// Perfect Signs Score
|
|
/// </summary>
|
|
public TMP_Text perfectSignsText;
|
|
|
|
/// <summary>
|
|
/// Good Signs Score
|
|
/// </summary>
|
|
public TMP_Text goodSignsText;
|
|
|
|
/// <summary>
|
|
/// Meh Signs Score
|
|
/// </summary>
|
|
public TMP_Text mehSignsText;
|
|
|
|
/// <summary>
|
|
/// Perfect Signs Score
|
|
/// </summary>
|
|
public TMP_Text terribleSignsText;
|
|
|
|
/// <summary>
|
|
/// Signs that were not found
|
|
/// </summary>
|
|
public TMP_Text notFoundSignsText;
|
|
|
|
/// <summary>
|
|
/// Score
|
|
/// </summary>
|
|
public TMP_Text scoreText;
|
|
|
|
/// <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()
|
|
{
|
|
perfectSigns = 0;
|
|
goodSigns = 0;
|
|
mehSigns = 0;
|
|
terribleSigns = 0;
|
|
incorrectSigns = 0;
|
|
score = 0;
|
|
gameEndedPanel.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", minigame.index);
|
|
progress.AddOrUpdate<List<Score>>("highestScores", new List<Score>());
|
|
progress.AddOrUpdate<List<Score>>("latestScores", new List<Score>());
|
|
user.minigames.Add(progress);
|
|
}
|
|
userList.Save();
|
|
|
|
scoreDisplay.text = "Score: " + score.ToString();
|
|
currentTheme = minigame.themeList.themes[minigame.themeList.currentThemeIndex];
|
|
words.AddRange(currentTheme.learnables);
|
|
currentSong = songList.songs[songList.currentSongIndex];
|
|
AudioSource.PlayClipAtPoint(currentSong.song, Vector3.zero, 1.0f);
|
|
beginTime = Time.time;
|
|
lastSymbolTime = beginTime + currentSong.duration - 1920.0f / moveSpeed;
|
|
|
|
StartCoroutine(WaitThenStart(currentSong.firstSymbolTime));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Wait for a given amount of time (specified in song) before spawning symbols
|
|
/// </summary>
|
|
IEnumerator WaitThenStart(float nrOfSeconds)
|
|
{
|
|
//yield on a new YieldInstruction that waits for nrOfSeconds seconds
|
|
yield return new WaitForSeconds(nrOfSeconds);
|
|
gameIsActive = true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Update is called once per frame
|
|
/// </summary>
|
|
void Update()
|
|
{
|
|
if (gameIsActive) {
|
|
int matchedSymbolIndex = -1;
|
|
for (int i = 0; i < activeWords.Count; i++) {
|
|
if (activeWords[i].ToLower() == answerField.text.ToLower()) {
|
|
matchedSymbolIndex = i;
|
|
}
|
|
}
|
|
|
|
// Destroy the oldest symbol if the current input matches it
|
|
if (matchedSymbolIndex >= 0) {
|
|
int difference = Math.Abs((int) (activeSymbols[matchedSymbolIndex].transform.position.x - hitZone.transform.position.x));
|
|
if (difference < perfectBoundary) {
|
|
feedBack.text = "Perfect!";
|
|
perfectSigns++;
|
|
score += perfectScore;
|
|
} else if (difference < goodBoundary) {
|
|
feedBack.text = "Good!";
|
|
goodSigns++;
|
|
score += goodScore;
|
|
} else if (difference < mehBoundary) {
|
|
feedBack.text = "Meh...";
|
|
mehSigns++;
|
|
score += mehScore;
|
|
} else {
|
|
feedBack.text = "Terrible!";
|
|
terribleSigns++;
|
|
score += terribleScore;
|
|
}
|
|
|
|
DestroySymbolAt(matchedSymbolIndex);
|
|
answerField.text = "";
|
|
}
|
|
|
|
// Destroy the oldest symbol if it leaves the screen
|
|
if (activeSymbols.Count > 0) {
|
|
if (activeSymbols[0].GetComponent<RectTransform>().localPosition.x > -trackX) {
|
|
DestroySymbolAt(0);
|
|
incorrectSigns++;
|
|
feedBack.text = "Te laat!";
|
|
score += offscreenScore;
|
|
}
|
|
}
|
|
|
|
// Spawn new symbol every spawn period
|
|
float currentTime = Time.time;
|
|
if (currentTime - lastSpawn > currentSong.spawnPeriod && lastSymbolTime > currentTime) {
|
|
lastSpawn = currentTime;
|
|
SpawnNewSymbol();
|
|
}
|
|
|
|
// Check if the song has ended and activate scorescreen if it has
|
|
if (currentTime - beginTime > currentSong.duration) {
|
|
ActivateEnd();
|
|
}
|
|
|
|
// Move all active symbols to the right
|
|
foreach (GameObject symbol in activeSymbols) {
|
|
RectTransform rectTransform = symbol.GetComponent<RectTransform>();
|
|
rectTransform.localPosition = new Vector3(rectTransform.localPosition.x + Time.deltaTime * moveSpeed, trackY, 0);
|
|
}
|
|
|
|
scoreDisplay.text = "Score: " + score.ToString();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Display Scoreboard + Metrics
|
|
/// </summary>
|
|
public void ActivateEnd()
|
|
{
|
|
gameIsActive = false;
|
|
while (activeSymbols.Count > 0)
|
|
{
|
|
DestroySymbolAt(0);
|
|
}
|
|
// TODO: Scoreboard
|
|
SaveScores();
|
|
SetScoreMetrics();
|
|
SetScoreBoard();
|
|
gameEndedPanel.SetActive(true);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Destroy the symbol at the given index
|
|
/// </summary>
|
|
/// <param name="index">The index of the symbol to destroy</param>
|
|
void DestroySymbolAt(int index) {
|
|
activeWords.RemoveAt(index);
|
|
GameObject symbol = activeSymbols[index];
|
|
activeSymbols.RemoveAt(index);
|
|
Destroy(symbol);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create a new symbol at the start of the track
|
|
/// </summary>
|
|
void SpawnNewSymbol() {
|
|
// Pick a word that isn't in use yet
|
|
List<int> unusedWordIndices = new List<int>();
|
|
|
|
for (int i = 0; i < words.Count; i++) {
|
|
if (!activeWords.Contains(words[i].name)) {
|
|
unusedWordIndices.Add(i);
|
|
}
|
|
}
|
|
|
|
Learnable newLearnable = words[unusedWordIndices[UnityEngine.Random.Range(0, unusedWordIndices.Count)]];
|
|
string nextSymbol = newLearnable.name;
|
|
|
|
GameObject newSymbolObject = GameObject.Instantiate(symbolPrefab, symbolContainer);
|
|
|
|
// Dynamically load appearance
|
|
Image image = newSymbolObject.GetComponent<Image>();
|
|
image.sprite = newLearnable.image;
|
|
image.rectTransform.sizeDelta = new Vector2(symbolSize, symbolSize);
|
|
|
|
// Place the word that the symbol represents under the image
|
|
TMP_Text text = newSymbolObject.GetComponentInChildren<TMP_Text>();
|
|
text.text = nextSymbol;
|
|
text.color = Color.black;
|
|
text.rectTransform.localPosition = new Vector3(0, -160, 0);
|
|
|
|
activeWords.Add(nextSymbol);
|
|
activeSymbols.Add(newSymbolObject);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Update and save the scores
|
|
/// </summary>
|
|
public void SaveScores()
|
|
{
|
|
// Calculate new score
|
|
int newScore = this.score;
|
|
|
|
// 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>
|
|
/// Set score metrics
|
|
/// </summary>
|
|
private void SetScoreMetrics()
|
|
{
|
|
// In de zone
|
|
perfectSignsText.text = perfectSigns.ToString();
|
|
|
|
// Aanvaardbaar
|
|
goodSignsText.text = goodSigns.ToString();
|
|
|
|
// Nipt
|
|
mehSignsText.text = mehSigns.ToString();
|
|
|
|
// Slechte timing
|
|
terribleSignsText.text = terribleSigns.ToString();
|
|
|
|
// Niet Geraden
|
|
notFoundSignsText.text = incorrectSigns.ToString();
|
|
|
|
// LPM
|
|
int duration = songList.songs[songList.currentSongIndex].duration;
|
|
int correctSigns = goodSigns + perfectSigns + mehSigns + terribleSigns;
|
|
lpmText.text = (60f * correctSigns / duration).ToString("#") + " GPM";
|
|
|
|
// Score
|
|
scoreText.text = "Score: " + score.ToString();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the scoreboard
|
|
/// </summary>
|
|
private void SetScoreBoard()
|
|
{
|
|
// Clean the previous scoreboard entries
|
|
for (int i = 0; i < scoreboardEntries.Count; i++)
|
|
{
|
|
Destroy(scoreboardEntries[i]);
|
|
}
|
|
scoreboardEntries.Clear();
|
|
|
|
// Instantiate new entries
|
|
// Get all scores from all users
|
|
List<Tuple<string, Score>> allScores = new List<Tuple<string, Score>>();
|
|
foreach (User user in userList.GetUsers())
|
|
{
|
|
// Get user's progress for this minigame
|
|
Progress progress = user.GetMinigameProgress(minigame.index);
|
|
if (progress != null)
|
|
{
|
|
// Add scores to dictionary
|
|
List<Score> scores = progress.Get<List<Score>>("highestScores");
|
|
foreach (Score score in scores)
|
|
{
|
|
allScores.Add(new Tuple<string, Score>(user.username, score));
|
|
}
|
|
}
|
|
}
|
|
|
|
// Sort allScores based on Score.scoreValue
|
|
allScores.Sort((a, b) => b.Item2.scoreValue.CompareTo(a.Item2.scoreValue));
|
|
|
|
// Instantiate scoreboard entries
|
|
int rank = 1;
|
|
foreach (Tuple<string, Score> tup in allScores.Take(10))
|
|
{
|
|
string username = tup.Item1;
|
|
Score score = tup.Item2;
|
|
|
|
GameObject entry = Instantiate(scoreboardEntry, scoreboardEntriesContainer);
|
|
scoreboardEntries.Add(entry);
|
|
|
|
// Set the player icon
|
|
entry.transform.Find("Image").GetComponent<Image>().sprite = userList.GetUserByUsername(username).avatar;
|
|
|
|
// Set the player name
|
|
entry.transform.Find("PlayerName").GetComponent<TMP_Text>().text = username;
|
|
|
|
// Set the score
|
|
entry.transform.Find("Score").GetComponent<TMP_Text>().text = score.scoreValue.ToString();
|
|
|
|
// Set the rank
|
|
entry.transform.Find("Rank").GetComponent<TMP_Text>().text = rank.ToString();
|
|
|
|
// Set the ago
|
|
// Convert the score.time to Datetime
|
|
DateTime time = DateTime.Parse(score.time);
|
|
DateTime currentTime = DateTime.Now;
|
|
TimeSpan diff = currentTime.Subtract(time);
|
|
|
|
string formatted;
|
|
if (diff.Days > 0)
|
|
{
|
|
formatted = $"{diff.Days}d ";
|
|
}
|
|
else if (diff.Hours > 0)
|
|
{
|
|
formatted = $"{diff.Hours}h ";
|
|
}
|
|
else if (diff.Minutes > 0)
|
|
{
|
|
formatted = $"{diff.Minutes}m ";
|
|
}
|
|
else
|
|
{
|
|
formatted = "now";
|
|
}
|
|
|
|
entry.transform.Find("Ago").GetComponent<TMP_Text>().text = formatted;
|
|
|
|
|
|
// Alternating colors looks nice
|
|
if (rank % 2 == 0)
|
|
{
|
|
Image image = entry.transform.GetComponent<Image>();
|
|
image.color = new Color(image.color.r, image.color.g, image.color.b, 0f);
|
|
}
|
|
|
|
// Make new score stand out
|
|
if (diff.TotalSeconds < 1)
|
|
{
|
|
Image image = entry.transform.GetComponent<Image>();
|
|
image.color = new Color(0, 229, 255, 233);
|
|
}
|
|
|
|
rank++;
|
|
}
|
|
}
|
|
|
|
}
|