-
Notifications
You must be signed in to change notification settings - Fork 0
/
HighScore.cs
77 lines (68 loc) · 1.95 KB
/
HighScore.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Wumpus.WinFormsApp
{
class Score : IComparable
{
public string Name;
public string CavePlayed;
public int HighScore;
public int NumberOfTurns;
public int NumberOfCoins;
public int NumberOfArrows;
public int CompareTo(object obj)
{
Score s = (Score)obj;
// Less than zero == this instance precedes other in the sort order.
return (s.HighScore - HighScore);
}
public void CalculateHighScore()
{
HighScore = 100 - NumberOfTurns + NumberOfCoins + (10 * NumberOfArrows);
}
}
class HighScore
{
List<Score> highScores;
public HighScore()
{
// always use an empty collection (never null)
highScores = new List<Score>();
LoadFile();
}
public List<Score> GetHighScores()
{
return highScores;
}
public void AddScore(Score score)
{
// add the score
highScores.Add(score);
// sort it
highScores.Sort();
}
private void LoadFile()
{
try
{
var json = File.ReadAllText("highScores.json");
highScores = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Score>>(json);
}
catch (System.IO.FileNotFoundException e)
{
// this is ok, we have no file and will just ignore and load nothing
// the first time we play a game and score will create a new file
}
}
private void SaveFile()
{
var json = JsonConvert.SerializeObject(highScores);
File.WriteAllText("highScores.json", json);
}
}
}