diff --git a/spec/command_spec.cr b/spec/command_spec.cr index 634e916..378b22b 100644 --- a/spec/command_spec.cr +++ b/spec/command_spec.cr @@ -15,4 +15,22 @@ describe Game::Command do tile = world.map.get point tile.should be_a(Game::BuildingTile) end + + it "should restrict build if not enought resources" do + world = Game::World.new create_map_2x2 + point = Game::Point.new 1, 0 + building = Game::Building.new Game::Building::Type::StartPoint, "Dummy", **{ + construction: Game::Construction.new( + ts: 10, + cost: Game::Resources.new({ + Game::Resources::Type::Crystals => 100, + }), + requirements: [] of Game::Building::Type + ), + } + command = Game::BuildCommand.new point, building + expect_raises(Game::NotEnoughtResources) do + world.push(command) + end + end end diff --git a/src/game/building.cr b/src/game/building.cr index 35c1f32..dc6e40d 100644 --- a/src/game/building.cr +++ b/src/game/building.cr @@ -1,5 +1,5 @@ module Game - struct Production + class Production def initialize(@ts : TimeSpan, @input : Resources, @output : Resources) end @@ -8,7 +8,7 @@ module Game getter output end - struct Restoration + class Restoration def initialize(@ts : TimeSpan, @type : Resources::Type, @cap : Capacity) end @@ -17,7 +17,7 @@ module Game getter cap end - struct Construction + class Construction def initialize(@ts : TimeSpan, @cost : Resources, @requirements : Array(Building::Type)) end diff --git a/src/game/command.cr b/src/game/command.cr index 4804d0a..f7bcd9d 100644 --- a/src/game/command.cr +++ b/src/game/command.cr @@ -16,8 +16,13 @@ module Game end def start(world : World) : TimeSpan + construction = @building.construction + if !world.resources.has(construction.cost) + raise NotEnoughtResources.new + end + # @todo check requirements world.map.set(ConstructionSiteTile.new(@point)) - @building.construction.ts + construction.ts end def finish(world : World) diff --git a/src/game/resources.cr b/src/game/resources.cr index b3c97e6..b794dc1 100644 --- a/src/game/resources.cr +++ b/src/game/resources.cr @@ -6,10 +6,10 @@ class Game::Resources Terraformation end - alias Capacity = Int32 - alias ResourceBag = Hash(Type, Capacity) + @values : ResourceBag + def initialize(vals : ResourceBag | Nil = nil) @values = {} of Type => Capacity Type.each { |t, v| @values[t] = 0 } @@ -37,6 +37,10 @@ class Game::Resources end end + def has(vs : self) : Bool + has vs.to_hash + end + def inc(t : Type, value : Capacity) new_value = @values.fetch(t, 0) + value if new_value < 0 @@ -56,4 +60,8 @@ class Game::Resources def dec(t : Type, value : Capacity) inc(t, -value) end + + def to_hash : ResourceBag + @values.clone + end end