game.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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().UnixNano() / 1000
  20. game := &Game{
  21. StartTime: createTime,
  22. Board: board.New(cols, rows),
  23. }
  24. return game
  25. }
  26. func (g *Game) Join(p *player.Player) {
  27. g.mutex.Lock()
  28. g.placePlayer(p)
  29. g.Players = append(g.Players, p)
  30. g.mutex.Unlock()
  31. }
  32. func (g *Game) placePlayer(p *player.Player) *board.Coordinate {
  33. xRange := g.Board.Cols / 5
  34. yRange := g.Board.Rows
  35. for {
  36. x := rand.Intn(xRange)
  37. y := rand.Intn(yRange)
  38. if g.isValidPlayerPos(x, y) {
  39. return &board.Coordinate{x, y}
  40. }
  41. }
  42. }
  43. func (g *Game) isValidPlayerPos(x, y int) bool {
  44. t := g.Board.Get(x, y)
  45. if t == board.Rock {
  46. return false;
  47. }
  48. return g.getPlayer(x, y) == nil
  49. }
  50. func (g *Game) getPlayer(x, y int) *player.Player {
  51. for _, p := range g.Players {
  52. if (p.Pos.X == x && p.Pos.Y == y) {
  53. return p
  54. }
  55. }
  56. return nil
  57. }