3 ms·
I'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
by AYBABTME 13y ago
I'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/...