Simple queue realisation

This commit is contained in:
Anton Vakhrushev 2019-09-13 15:40:15 +03:00
parent 224748cb5a
commit db72b838d3
6 changed files with 92 additions and 7 deletions

5
.gitignore vendored
View File

@ -1,6 +1,7 @@
/.crystal/
/.shards/
/bin/
/build/
/docs/
/lib/
/bin/
/.shards/
*.dwarf

3
Dockerfile Normal file
View File

@ -0,0 +1,3 @@
FROM alpine:edge as builder
RUN apk add -u crystal shards libc-dev

View File

@ -1,3 +1,8 @@
.PHONY: build-docker
build-docker:
docker pull alpine:edge
docker build -t village-crystal .
.PHONY: format
format:
./cr tool format ./src ./spec
@ -5,3 +10,8 @@ format:
.PHONY: spec
spec:
./cr spec --warnings all --error-on-warnings
.PHONY: release
release:
mkdir -p build
./cr build ./src/village.cr --release --no-debug --static -o build/village

2
cr
View File

@ -6,4 +6,4 @@ docker run -it \
-u "$(id -u):$(id -g)" \
-v "$PWD:/app" \
-w "/app" \
crystallang/crystal:0.30.0 crystal "$@"
village-crystal crystal "$@"

2
shards
View File

@ -6,4 +6,4 @@ docker run -it \
-u "$(id -u):$(id -g)" \
-v "$PWD:/app" \
-w "/app" \
crystallang/crystal:0.30.0 shards "$@"
village-crystal shards "$@"

View File

@ -1,5 +1,76 @@
module Village
VERSION = "0.1.0"
class Resources
def initialize
@wood = 0
end
# TODO: Put your code here
def add_wood(x)
@wood += x
end
def wood
@wood
end
end
abstract class Command
def initialize(ts : Int32)
@ts = ts
end
def ts
@ts
end
abstract def run(queue : CommandQueue, res : Resources)
end
class BuildMillCommand < Command
def run(queue : CommandQueue, res : Resources)
puts "build mill"
c = GetWoodCommand.new(@ts + 5)
queue.push(c)
end
end
class GetWoodCommand < Command
def run(queue : CommandQueue, res : Resources)
res.add_wood(10)
puts "get wood"
c = GetWoodCommand.new(@ts + 5)
queue.push(c)
end
end
class CommandQueue
def initialize
@resources = Resources.new
@data = Array(Command).new
end
def push(command : Command)
printf "push command %d\n", command.ts
@data.push(command)
@data.sort! do |c|
-c.ts
end
end
def run(ts : Int32)
while @data.size != 0
c = @data.pop
printf "pop command %d\n", c.ts
if c.ts > ts
break
end
c.run(self, @resources)
end
printf "Wood: %d\n", @resources.wood
end
end
q = CommandQueue.new
q.push(BuildMillCommand.new(0))
q.push(BuildMillCommand.new(0))
q.push(BuildMillCommand.new(0))
q.push(BuildMillCommand.new(2))
q.run(10)