-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hanoi.cs
88 lines (80 loc) · 2.31 KB
/
Hanoi.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
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tower_Of_Hanoi
{
public class HanoiGame
{
public Tower[] towers = new Tower[3];
public int blockCount;
public delegate void MoveEvent(MoveInfo info);
public MoveEvent BlockMoved;
public event Action GameFinished;
public List<MoveInfo> moves = new List<MoveInfo>();
public MoveInfo originTowers;
public class MoveInfo
{
public Tower[] towers;
public MoveInfo(Tower[] towers)
{
this.towers = towers;
}
}
public HanoiGame(int blockCount)
{
this.blockCount = blockCount;
SetupTowers();
Tower[] curTowers = new Tower[3];
for (int i = 0; i < 3; i++)
{
curTowers[i] = new Tower(blockCount);
curTowers[i].SetBlocks(towers[i].GetBlocks());
}
originTowers = new MoveInfo(curTowers);
moves.Add(originTowers);
}
void SetupTowers()
{
for (int i = 0; i < towers.Length; i++)
{
towers[i] = new Tower(blockCount);
}
for (int i = blockCount ; i > 0; i--)
{
towers[0].AddBlockToTop(new Block(i));
}
}
public void MoveBlock(Tower from, Tower to)
{
Block block = from.TopBlock;
if(block == null || !to.AddBlockToTop(block))
{
return;
}
from.TopBlock = null;
Tower[] curTowers = new Tower[3];
for (int i = 0; i < 3; i++)
{
curTowers[i] = new Tower(blockCount);
curTowers[i].SetBlocks(towers[i].GetBlocks());
}
MoveInfo moveInfo = new MoveInfo(curTowers);
moves.Add(moveInfo);
BlockMoved?.Invoke(moveInfo);
CheckGame();
}
void CheckGame()
{
for (int i= 0; i < blockCount; i++)
{
if (towers[2][i] == null)
{
return;
}
}
GameFinished?.Invoke();
}
}
}