From 446b1659de36158651ca628a42c3201248042330 Mon Sep 17 00:00:00 2001 From: Anton Vakhrushev Date: Thu, 3 Oct 2019 17:10:13 +0300 Subject: [PATCH] Add resource exception --- spec/world_spec.cr | 9 +++++++++ src/command.cr | 8 ++++++-- src/exception.cr | 2 ++ src/resources.cr | 12 +++++++++++- 4 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 src/exception.cr diff --git a/spec/world_spec.cr b/spec/world_spec.cr index 176a1bc..b3253dc 100644 --- a/spec/world_spec.cr +++ b/spec/world_spec.cr @@ -10,4 +10,13 @@ describe "World" do world.run(100) world.map.get(point).has_role(TileRole::CrystalHarvester) end + + it "should fail when not enought resources" do + world = World.new + point = Point.new(2, 3) + cmd = BuildCrystalRestorerCommand.new(point) + expect_raises(NotEnoughtResources) do + world.push(cmd) + end + end end diff --git a/src/command.cr b/src/command.cr index 6a80ba8..2867542 100644 --- a/src/command.cr +++ b/src/command.cr @@ -62,12 +62,14 @@ class HarvestCrystalCommand < Command end class BuildCrystalRestorerCommand < Command - BUILD_TIME = 50 + CRYSTALS_COST = 100 + BUILD_TIME = 50 def initialize(@point : Point) end def start(world : World) : Int32 + world.resources.dec(ResourceType::Crystal, CRYSTALS_COST) BUILD_TIME end @@ -112,12 +114,14 @@ class RestoreCrystalCommand < Command end class BuildTerraformerCommand < Command - BUILD_TIME = 120 + CRYSTALS_COST = 100 + BUILD_TIME = 120 def initialize(@point : Point) end def start(world : World) : Int32 + world.resources.dec(ResourceType::Crystal, CRYSTALS_COST) BUILD_TIME end diff --git a/src/exception.cr b/src/exception.cr new file mode 100644 index 0000000..9dcf0f3 --- /dev/null +++ b/src/exception.cr @@ -0,0 +1,2 @@ +class NotEnoughtResources < Exception +end diff --git a/src/resources.cr b/src/resources.cr index e9cdf14..6da26ec 100644 --- a/src/resources.cr +++ b/src/resources.cr @@ -1,3 +1,5 @@ +require "./exception" + enum ResourceType Crystal Terraformation @@ -16,6 +18,14 @@ class Resources end def inc(t : ResourceType, value : Int32) - @values[t] = @values[t] + value + new_value = @values[t] + value + if new_value < 0 + raise NotEnoughtResources.new + end + @values[t] = new_value + end + + def dec(t : ResourceType, value : Int32) + inc(t, -value) end end