game.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package games
  2. import (
  3. "battlecamp-go-server/board"
  4. "battlecamp-go-server/player"
  5. "math/rand"
  6. "sync"
  7. "time"
  8. )
  9. type Game struct {
  10. Id int64 `json:"id"`
  11. StartTime int64 `json:"startTime"`
  12. EndTime int64 `json:"endTime"`
  13. Board *board.Board `json:"board"`
  14. Players []*player.Player `json:"-"`
  15. mutex sync.Mutex
  16. Winner *player.Player `json:"winner,omitempty"`
  17. }
  18. func NewGame(cols, rows int) *Game {
  19. createTime := time.Now().Unix()
  20. game := &Game{
  21. StartTime: createTime,
  22. Board: board.New(cols, rows),
  23. Players: make([]*player.Player, 0),
  24. }
  25. return game
  26. }
  27. func (g *Game) Join(p *player.Player) {
  28. g.mutex.Lock()
  29. g.placePlayer(p)
  30. g.Players = append(g.Players, p)
  31. g.mutex.Unlock()
  32. }
  33. func (g *Game) placePlayer(p *player.Player) *board.Coordinate {
  34. xRange := g.Board.Cols / 5
  35. yRange := g.Board.Rows
  36. for {
  37. x := rand.Intn(xRange)
  38. y := rand.Intn(yRange)
  39. if g.isValidPlayerPos(x, y) {
  40. return &board.Coordinate{x, y}
  41. }
  42. }
  43. }
  44. func (g *Game) isValidPlayerPos(x, y int) bool {
  45. t := g.Board.Get(x, y)
  46. if t == board.Rock {
  47. return false;
  48. }
  49. return g.getPlayer(x, y) == nil
  50. }
  51. func (g *Game) getPlayer(x, y int) *player.Player {
  52. for _, p := range g.Players {
  53. if (p.Pos.X == x && p.Pos.Y == y) {
  54. return p
  55. }
  56. }
  57. return nil
  58. }