| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- package games
- import (
- "battlecamp-go-server/board"
- "battlecamp-go-server/player"
- "math/rand"
- "sync"
- "time"
- )
- type Game struct {
- Id int64 `json:"id"`
- StartTime int64 `json:"startTime"`
- EndTime int64 `json:"endTime"`
- Board *board.Board `json:"board"`
- Players []*player.Player `json:"-"`
- mutex sync.Mutex
- Winner *player.Player `json:"winner,omitempty"`
- }
- func NewGame(cols, rows int) *Game {
- createTime := time.Now().Unix()
- game := &Game{
- StartTime: createTime,
- Board: board.New(cols, rows),
- Players: make([]*player.Player, 0),
- }
- return game
- }
- func (g *Game) Join(p *player.Player) {
- g.mutex.Lock()
- g.placePlayer(p)
- g.Players = append(g.Players, p)
- g.mutex.Unlock()
- }
- func (g *Game) placePlayer(p *player.Player) *board.Coordinate {
- xRange := g.Board.Cols / 5
- yRange := g.Board.Rows
- for {
- x := rand.Intn(xRange)
- y := rand.Intn(yRange)
-
- if g.isValidPlayerPos(x, y) {
- return &board.Coordinate{x, y}
- }
- }
- }
- func (g *Game) isValidPlayerPos(x, y int) bool {
- t := g.Board.Get(x, y)
- if t == board.Rock {
- return false;
- }
-
- return g.getPlayer(x, y) == nil
- }
- func (g *Game) getPlayer(x, y int) *player.Player {
-
- for _, p := range g.Players {
- if (p.Pos.X == x && p.Pos.Y == y) {
- return p
- }
- }
-
- return nil
- }
|