Add resource exception

This commit is contained in:
Anton Vakhrushev 2019-10-03 17:10:13 +03:00
parent 6404a6e519
commit 446b1659de
4 changed files with 28 additions and 3 deletions

View File

@ -10,4 +10,13 @@ describe "World" do
world.run(100) world.run(100)
world.map.get(point).has_role(TileRole::CrystalHarvester) world.map.get(point).has_role(TileRole::CrystalHarvester)
end 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 end

View File

@ -62,12 +62,14 @@ class HarvestCrystalCommand < Command
end end
class BuildCrystalRestorerCommand < Command class BuildCrystalRestorerCommand < Command
BUILD_TIME = 50 CRYSTALS_COST = 100
BUILD_TIME = 50
def initialize(@point : Point) def initialize(@point : Point)
end end
def start(world : World) : Int32 def start(world : World) : Int32
world.resources.dec(ResourceType::Crystal, CRYSTALS_COST)
BUILD_TIME BUILD_TIME
end end
@ -112,12 +114,14 @@ class RestoreCrystalCommand < Command
end end
class BuildTerraformerCommand < Command class BuildTerraformerCommand < Command
BUILD_TIME = 120 CRYSTALS_COST = 100
BUILD_TIME = 120
def initialize(@point : Point) def initialize(@point : Point)
end end
def start(world : World) : Int32 def start(world : World) : Int32
world.resources.dec(ResourceType::Crystal, CRYSTALS_COST)
BUILD_TIME BUILD_TIME
end end

2
src/exception.cr Normal file
View File

@ -0,0 +1,2 @@
class NotEnoughtResources < Exception
end

View File

@ -1,3 +1,5 @@
require "./exception"
enum ResourceType enum ResourceType
Crystal Crystal
Terraformation Terraformation
@ -16,6 +18,14 @@ class Resources
end end
def inc(t : ResourceType, value : Int32) 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
end end