4 ms·
Note the use of receive-only channels: func merge(cs ...<-chan int) <-chan int { Inside the function you cannot send to a member of cs - it will give you
by Jabbles 13y ago
Note the use of receive-only channels:
func merge(cs ...<-chan int) <-chan int {
Inside the function you cannot send to a member of cs - it will give you a compile-error.
Outside the function you cannot send to its return value.
An example to play with: http://play.golang.org/p/6AJLpZkLBe http://play.golang.org/p/6AJLpZkLBe
- AYBABTME 13y agoI've cleanly used that in a lil' game I'm working on. Players send their move to the game on a channel they expose through Move(). They receive regular updates of the game state on a channel they expose through Update(). type Player interface { Name() string Move() <-chan Move Update() chan<- State } > https://github.com/aybabtme/bomberman/blob/master/player/player.go#L30-L34 https://github.com/aybabtme/bomberman/blob/master/player/pla... The game reads the player moves, if moves are available[1]: for pState, player := range g.Players { if pState.Alive { select { case m := <-player.Move(): movePlayer(g, board, pState, m) default: } } } > https://github.com/aybabtme/bomberman/blob/master/bomberman.go#L250-L251 https://github.com/aybabtme/bomberman/blob/master/bomberman.... The game sends each turn's update to players that are ready to listen for it: for pState, player := range game.Players { pState.Board = board.Clone() pState.Turn = game.Turn() select { case player.Update() <- *pState: default: } } > https://github.com/aybabtme/bomberman/blob/master/bomberman.go#L262-L269 https://github.com/aybabtme/bomberman/blob/master/bomberman.... This leans to surprisingly clean implementations: * A websocket player [2] * A keyboard player [3] * A random AI player [4] Note that the rest of the game (`bomberman.go`) is a hairy ball that needs refactoring. [1]: this, to prevent an unresponsive player from hanging the game, or an AI player from unfairly computing longer than it's opponent [2]: https://github.com/aybabtme/bomberweb/blob/master/player/player.go https://github.com/aybabtme/bomberweb/blob/master/player/pla... [3]: https://github.com/aybabtme/bomberman/blob/master/player/input/input.go https://github.com/aybabtme/bomberman/blob/master/player/inp... [4]: https://github.com/aybabtme/bomberman/blob/master/player/ai/random.go https://github.com/aybabtme/bomberman/blob/master/player/ai/...