Repository navigation
Expand file tree
/
Copy pathGame.cs
More file actions
78 lines (62 loc) · 1.92 KB
/
Copy pathGame.cs
File metadata and controls
78 lines (62 loc) · 1.92 KB
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
78
using System;
using Tower.Models;
using Tower.Resources;
using Tower.UI;
namespace Tower
{
internal class Game
{
private readonly Towers _towers;
private readonly TowerDisplay _display;
private readonly int _optimalMoveCount;
private int _moveCount;
public Game(int diskCount)
{
_towers = new Towers(diskCount);
_display = new TowerDisplay(_towers);
_optimalMoveCount = (1 << diskCount) - 1;
}
public bool Play()
{
Console.Write(Strings.Instructions);
Console.Write(_display);
while (true)
{
if (!Input.TryReadNumber(Prompt.Disk, out int disk)) { return false; }
if (!_towers.TryFindDisk(disk, out var from, out var message))
{
Console.WriteLine(message);
continue;
}
if (!Input.TryReadNumber(Prompt.Needle, out var to)) { return false; }
if (!_towers.TryMoveDisk(from, to))
{
Console.Write(Strings.IllegalMove);
continue;
}
Console.Write(_display);
var result = CheckProgress();
if (result.HasValue) { return result.Value; }
}
}
private bool? CheckProgress()
{
_moveCount++;
if (_moveCount == 128)
{
Console.Write(Strings.TooManyMoves);
return false;
}
if (_towers.Finished)
{
if (_moveCount == _optimalMoveCount)
{
Console.Write(Strings.Congratulations);
}
Console.WriteLine(Strings.TaskFinished, _moveCount);
return true;
}
return default;
}
}
}