-
Notifications
You must be signed in to change notification settings - Fork 0
/
Room.cs
100 lines (82 loc) · 2.56 KB
/
Room.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
89
90
91
92
93
94
95
96
97
98
99
100
// <copyright file="Room.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
namespace Adventure
{
using System;
using System.Collections.Generic;
public abstract class Room
{
private readonly MessageBus bus;
private readonly Dictionary<string, Action<Word, Word>> verbs;
private IDisposable sub;
protected Room(MessageBus bus)
{
this.bus = bus;
this.verbs = new Dictionary<string, Action<Word, Word>>(StringComparer.OrdinalIgnoreCase);
}
protected abstract string Description { get; }
public void Enter()
{
if (this.sub != null)
{
throw new InvalidOperationException("Cannot Enter again.");
}
this.sub = this.bus.Subscribe<SentenceMessage>(m => this.Process(m));
this.EnterCore();
this.Look(new Word(string.Empty, string.Empty));
}
public void Leave()
{
if (this.sub == null)
{
throw new InvalidOperationException("Cannot Leave before Enter.");
}
this.verbs.Clear();
this.sub.Dispose();
this.sub = null;
}
protected virtual void EnterCore()
{
}
protected void Register(string verb, Action<Word, Word> handler)
{
if (this.verbs.ContainsKey(verb))
{
throw new InvalidOperationException($"The verb '{verb}' is already registered.");
}
this.verbs.Add(verb, handler);
}
protected void Output(string message)
{
this.bus.Send(new OutputMessage(message));
}
protected void Look(Word noun)
{
if (noun.Actual.Length == 0)
{
this.Output(this.Description);
}
else if (!this.LookAt(noun))
{
this.Output("You see nothing of interest.");
}
}
protected virtual bool LookAt(Word noun)
{
return false;
}
private void Process(SentenceMessage message)
{
if (!this.verbs.TryGetValue(message.Verb.Primary, out Action<Word, Word> handler))
{
handler = this.UnknownVerb;
}
handler(message.Verb, message.Noun);
}
private void UnknownVerb(Word verb, Word noun)
{
this.Output($"I don't know what '{verb}' means.");
}
}
}