Add project files.
This commit is contained in:
62
FreedomFighter/HighScores.cs
Normal file
62
FreedomFighter/HighScores.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace FreedomFighter;
|
||||
|
||||
public record HighScoreEntry(string Name, int Score);
|
||||
|
||||
/// <summary>High score table; JSON replaces the original Highscore.dat record file.</summary>
|
||||
public class HighScores
|
||||
{
|
||||
const string FileName = "highscore.json";
|
||||
public HighScoreEntry[] List = new HighScoreEntry[10];
|
||||
|
||||
public void Load()
|
||||
{
|
||||
if (File.Exists(FileName))
|
||||
{
|
||||
try
|
||||
{
|
||||
var loaded = JsonSerializer.Deserialize<HighScoreEntry[]>(File.ReadAllText(FileName));
|
||||
if (loaded is { Length: 10 }) { List = loaded; return; }
|
||||
}
|
||||
catch { /* fall through to defaults */ }
|
||||
}
|
||||
for (int i = 0; i < 10; i++)
|
||||
List[i] = new HighScoreEntry("Nameless", 0);
|
||||
Save();
|
||||
}
|
||||
|
||||
public void Save() => File.WriteAllText(FileName, JsonSerializer.Serialize(List));
|
||||
|
||||
public bool Qualifies(int score) => score > List[9].Score;
|
||||
|
||||
public void Add(int num, string name, int score)
|
||||
{
|
||||
for (int i = 9; i >= num + 1; i--)
|
||||
List[i] = List[i - 1];
|
||||
List[num] = new HighScoreEntry(name, score);
|
||||
}
|
||||
|
||||
/// <summary>Port of EnterHighScoreList: insert from the bottom up.</summary>
|
||||
public void Enter(string name, int score)
|
||||
{
|
||||
for (int i = 8; i >= 0; i--)
|
||||
{
|
||||
if (score <= List[i].Score)
|
||||
{
|
||||
Add(i + 1, name, score);
|
||||
break;
|
||||
}
|
||||
if (i == 0)
|
||||
{
|
||||
Add(i, name, score);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Save();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user