PuzzleGame/PuzzleGameProject/Assets/Scripts/UI/DungeonSelectMenuController.cs

113 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using DungeonSelection;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UIElements;
public class DungeonSelectMenuController : MonoBehaviour
{
private const int NUM_HIGH_SCORES = 10;
private Button _next;
private Button _previous;
private Button _start;
private Image _thumbnailImage;
private Label _dungeonName;
private VisualElement _dungeonThumbnail;
private ListView _highScores;
private DungeonDisplayData _currentlyShowingDungeon;
private List<string> _highScoreData = new List<string>();
private void OnEnable()
{
VisualElement root = GetComponent<UIDocument>().rootVisualElement;
Button rules = root.Q<Button>("Rules");
rules.clicked += RulesClicked;
_dungeonThumbnail = root.Q<VisualElement>("DungeonThumbnail");
_next = root.Q<Button>("Next");
_next.clicked += NextClicked;
_previous = root.Q<Button>("Previous");
_previous.clicked += PreviousClicked;
_start = root.Q<Button>("Start");
_start.clicked += StartClicked;
_dungeonName = root.Q<Label>("DungeonName");
_highScores = root.Q<ListView>("HighScoresListView");
_highScores.makeItem = () => new Label();
_highScores.bindItem = (element, index) => { (element as Label).text = _highScoreData[index]; };
_highScores.itemsSource = _highScoreData;
_highScores.makeNoneElement = () => new Label();
GameEvents.ShowingDungeon += ShowDungeon;
GameEvents.ShowingFirstDugeon += () => SetPreviousButtonEnabled(false);
GameEvents.ShowingLastDungeon += () => SetNextButtonEnabled(false);
}
private void Start()
{
UIEvents.GetScores?.Invoke();
}
private void ShowDungeon(DungeonDisplayData dungeon)
{
_currentlyShowingDungeon = dungeon;
_dungeonName.text = _currentlyShowingDungeon.DungeonData.Name;
if (_thumbnailImage == null)
{
_thumbnailImage = new Image();
_thumbnailImage.scaleMode = ScaleMode.ScaleAndCrop;
_dungeonThumbnail.Add(_thumbnailImage);
}
_thumbnailImage.image = _currentlyShowingDungeon.DungeonData.Thumbnail.texture;
_highScoreData.Clear();
int rank = 1;
foreach (ScoreDisplay score in dungeon.HighScores)
{
if (rank > NUM_HIGH_SCORES) break;
string formattedScore = $"{rank}. {score.PlayerName} {score.Score}";
_highScoreData.Add(formattedScore);
rank++;
}
_highScores.RefreshItems();
}
private void SetPreviousButtonEnabled(bool enabled)
{
_previous.SetEnabled(enabled);
}
private void SetNextButtonEnabled(bool enabled)
{
_next.SetEnabled(enabled);
}
private void NextClicked()
{
SetPreviousButtonEnabled(true);
SetNextButtonEnabled(true);
UIEvents.NextDungeonClicked?.Invoke();
}
private void PreviousClicked()
{
SetPreviousButtonEnabled(true);
SetNextButtonEnabled(true);
UIEvents.PreviousDungeonClicked?.Invoke();
}
private void StartClicked()
{
UIEvents.EnterDungeonClicked?.Invoke(_currentlyShowingDungeon.DungeonData);
}
private void RulesClicked()
{
UIEvents.ShowRules?.Invoke();
}
}