Skip to content

Commit

Permalink
Items - DoCustomActionForItem
Browse files Browse the repository at this point in the history
  • Loading branch information
bobbymcr committed Dec 12, 2018
1 parent d67b813 commit 07ca3a8
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
9 changes: 9 additions & 0 deletions core/src/Item.cs
Expand Up @@ -11,5 +11,14 @@ protected Item()
}

public abstract string ShortDescription { get; }

public void Do(MessageBus bus, Word verb, Word noun)
{
this.DoCore(bus, verb, noun);
}

protected virtual void DoCore(MessageBus bus, Word verb, Word noun)
{
}
}
}
12 changes: 12 additions & 0 deletions core/src/Items.cs
Expand Up @@ -13,12 +13,19 @@ public sealed class Items
private readonly MessageBus bus;
private readonly Dictionary<string, Item> items;

private IDisposable sub;

public Items(MessageBus bus)
{
this.bus = bus;
this.items = new Dictionary<string, Item>();
}

public void Activate()
{
this.sub = this.bus.Subscribe<SentenceMessage>(m => this.Do(m));
}

public void Look()
{
foreach (string item in this.items.Values.Select(i => i.ShortDescription))
Expand Down Expand Up @@ -47,5 +54,10 @@ private void Output(string text)
{
this.bus.Send(new OutputMessage(text));
}

private void Do(SentenceMessage sentence)
{
this.items[sentence.Noun.Primary].Do(this.bus, sentence.Verb, sentence.Noun);
}
}
}
24 changes: 24 additions & 0 deletions core/test/ItemsTest.cs
Expand Up @@ -5,6 +5,7 @@
namespace Adventure.Test
{
using System;
using System.Collections.Generic;
using FluentAssertions;
using Xunit;

Expand Down Expand Up @@ -93,9 +94,32 @@ public void DropItemAlreadyExists()
act.Should().Throw<InvalidOperationException>("Item 'key' already exists.");
}

[Fact]
public void DoCustomActionForItem()
{
MessageBus bus = new MessageBus();
List<string> messages = new List<string>();
bus.Subscribe<OutputMessage>(m => messages.Add(m.Text));
Items items = new Items(bus);
items.Drop("ball", new TestItem());

items.Activate();
bus.Send(new SentenceMessage(new Word("throw", "TOSS"), new Word("ball", "BASEBALL")));

messages.Should().ContainSingle().Which.Should().Be("You threw the BASEBALL!");
}

private sealed class TestItem : Item
{
public override string ShortDescription => "a test item";

protected override void DoCore(MessageBus bus, Word verb, Word noun)
{
if (verb.Primary == "throw")
{
bus.Send(new OutputMessage($"You threw the {noun}!"));
}
}
}
}
}

0 comments on commit 07ca3a8

Please sign in to comment.