A3: nearly there

This commit is contained in:
Johannes Theiner 2020-05-21 20:04:50 +02:00
parent dbe8fcbf68
commit c90d077551
1 changed files with 60 additions and 12 deletions

View File

@ -31,6 +31,22 @@ var Colours = []Colour{
red, green, yellow,
}
func nextDirection(currentDirection CardinalDirection) CardinalDirection {
switch currentDirection {
case north:
return east
case south:
return west
case east:
return south
case west:
return north
default:
return north
}
}
func nextColour(currentColour Colour) Colour {
switch currentColour {
case red:
@ -52,10 +68,10 @@ func main() {
var eastColour = make(chan Colour, 2)
var westColour = make(chan Colour, 2)
var northDirection = make(chan string, 4)
var southDirection = make(chan string, 4)
var eastDirection = make(chan string, 4)
var westDirection = make(chan string, 4)
var northDirection = make(chan string, 2)
var southDirection = make(chan string, 2)
var eastDirection = make(chan string, 2)
var westDirection = make(chan string, 2)
go TrafficLight(north, northColour, southColour, northDirection, eastDirection, southDirection)
go TrafficLight(south, southColour, northColour, southDirection, westDirection, northDirection)
@ -65,25 +81,57 @@ func main() {
<-quitChannel
}
func TrafficLight(direction CardinalDirection, currentColour <-chan Colour, oppositeColour chan<- Colour, currentDirection <-chan string, nextDirection chan<- string, oppositeDirection chan<- string) {
func TrafficLight(direction CardinalDirection, currentColour <-chan Colour, oppositeColour chan<- Colour, currentDirection <-chan string, nextDirectionChan chan<- string, oppositeDirection chan<- string) {
var colour = red
if direction != north && direction != south {
nextDirection <- "go"
nextDirectionChan <- string(nextDirection(direction))
}
for {
show(direction, colour)
if colour == red {
syncLight(currentDirection, oppositeDirection)
changeDirection(direction, currentDirection, nextDirectionChan)
}
colour = changeLight(colour, currentColour, oppositeColour)
}
}
func syncLight(currentDirection <-chan string, oppositeDirection chan<- string) {
oppositeDirection <- "sync"
select {
case msg := <-currentDirection:
if msg == "sync" {
return
}
}
}
func changeDirection(direction CardinalDirection, currentDirection <-chan string, nextDirectionChan chan<- string) {
nextDirectionChan <- string(nextDirection(direction))
select {
case msg := <-currentDirection:
if msg == string(direction) {
return
}
}
}
func changeLight(colour Colour, currentColour <-chan Colour, oppositeColour chan<- Colour) Colour {
oppositeColour <- nextColour(colour)
select {
case msg := <-currentColour:
if msg == nextColour(colour) {
colour = msg
return nextColour(colour)
}
}
}
return colour
}
func show(direction CardinalDirection, colour Colour) {