No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

game.go 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package server
  2. // delete me
  3. import (
  4. "log"
  5. "sort"
  6. "sync"
  7. "time"
  8. "mcquay.me/bandwidth"
  9. )
  10. const maxPlayer = 128
  11. // BotHealth is sent to all players so they know how other robots are
  12. // doing.
  13. type BotHealth struct {
  14. RobotId string `json:"robot_id"`
  15. Health int `json:"health"`
  16. }
  17. // Scanner contains a Robot/Projectile hash and is sent to the user to
  18. // let them know which things they know about.
  19. type Scanner struct {
  20. Id string `json:"id"`
  21. Type string `json:"type"`
  22. }
  23. // BotStats is stats for a single Player's Robot.
  24. type BotStats struct {
  25. Kills int
  26. Deaths int
  27. Suicides int
  28. Shots int
  29. DirectHits int
  30. Hits int
  31. Wins int
  32. }
  33. // PlayerStats is what you want many of. Contains a map of BotStats and total
  34. // wins.
  35. type PlayerStats struct {
  36. BotStats map[string]*BotStats
  37. Wins int
  38. }
  39. // GameStats is a collection of PlayerStats for all players involved.
  40. type GameStats struct {
  41. PlayerStats map[string]*PlayerStats
  42. sync.RWMutex
  43. }
  44. // Game is the main point of interest in this application. Embodies all info
  45. // required to keep track of players, robots, stats, projectils, etc.
  46. // Currently Controllers have a map of these.
  47. type Game struct {
  48. id string
  49. players map[*Player]bool
  50. projectiles map[*Projectile]bool
  51. splosions map[*Splosion]bool
  52. defaultObstacles []Obstacle
  53. obstacles []Obstacle
  54. obstacleCount int
  55. register chan *Player
  56. unregister chan *Player
  57. turn int
  58. players_remaining int
  59. width, height float64
  60. maxPoints int
  61. spectators map[*Spectator]bool
  62. sregister chan *Spectator
  63. sunregister chan *Spectator
  64. kill chan bool
  65. repair_hp int
  66. repair_rate float64
  67. tick_duration int
  68. stats GameStats
  69. mode GameMode
  70. bw *bandwidth.Bandwidth
  71. }
  72. // This is the interface that different gametypes should implement.
  73. type GameMode interface {
  74. setup(g *Game)
  75. tick(gg *Game, payload *Boardstate)
  76. gameOver(gg *Game) (bool, *GameOver)
  77. }
  78. // NewGame Poplulates a Game struct and starts the bandwidth calculator.
  79. func NewGame(id string, width, height float64, tick, maxPoints int, mode string) (*Game, error) {
  80. bw, err := bandwidth.NewBandwidth(
  81. []int{1, 10, 60},
  82. 1*time.Second,
  83. )
  84. if err != nil {
  85. return nil, err
  86. }
  87. go bw.Run()
  88. g := &Game{
  89. id: id,
  90. register: make(chan *Player, maxPlayer),
  91. unregister: make(chan *Player, maxPlayer),
  92. projectiles: make(map[*Projectile]bool),
  93. splosions: make(map[*Splosion]bool),
  94. players: make(map[*Player]bool),
  95. turn: 0,
  96. width: width,
  97. height: height,
  98. maxPoints: maxPoints,
  99. spectators: make(map[*Spectator]bool),
  100. sregister: make(chan *Spectator),
  101. sunregister: make(chan *Spectator),
  102. kill: make(chan bool),
  103. repair_hp: 5,
  104. repair_rate: 3.0,
  105. tick_duration: tick,
  106. players_remaining: 2,
  107. stats: GameStats{PlayerStats: make(map[string]*PlayerStats)},
  108. bw: bw,
  109. }
  110. if mode == "melee" {
  111. g.mode = &melee{respawn: make(map[*Robot]float64)}
  112. } else {
  113. g.mode = &deathmatch{}
  114. }
  115. g.mode.setup(g)
  116. return g, nil
  117. }
  118. // tick is the method called every TICK ms.
  119. func (g *Game) tick(payload *Boardstate) {
  120. g.players_remaining = 0
  121. // Update Players
  122. for p := range g.players {
  123. living_robots := 0
  124. for _, r := range p.Robots {
  125. if r.Health > 0 {
  126. living_robots++
  127. r.Tick(g)
  128. }
  129. if len(r.Message) > 0 {
  130. if len(r.Message) > 100 {
  131. r.Message = r.Message[0:99]
  132. }
  133. payload.Messages = append(payload.Messages, r.Message)
  134. }
  135. payload.OtherRobots = append(
  136. payload.OtherRobots,
  137. r.GetTruncatedDetails())
  138. payload.AllBots = append(
  139. payload.AllBots,
  140. BotHealth{RobotId: r.Id, Health: r.Health})
  141. }
  142. if living_robots > 0 {
  143. g.players_remaining++
  144. }
  145. }
  146. // Update Projectiles
  147. for pr := range g.projectiles {
  148. pr.Tick(g)
  149. }
  150. // We do this here, because the tick calls can alter g.projectiles
  151. for pr := range g.projectiles {
  152. payload.Projectiles = append(payload.Projectiles, *pr)
  153. }
  154. // Update Splosions
  155. for s := range g.splosions {
  156. s.Tick()
  157. if !s.Alive() {
  158. delete(g.splosions, s)
  159. }
  160. payload.Splosions = append(payload.Splosions, *s)
  161. }
  162. }
  163. // sendUpdate is what we use to determine what data goes out to each client;
  164. // performs filtering and sorting of the data.
  165. func (g *Game) sendUpdate(payload *Boardstate) {
  166. // Ensure that the robots are always sent in a consistent order
  167. sort.Sort(RobotSorter{Robots: payload.OtherRobots})
  168. sort.Sort(AllRobotSorter{Robots: payload.AllBots})
  169. for p := range g.players {
  170. // Copy the payload but only add the robots in scanner range
  171. player_payload := NewBoardstate()
  172. player_payload.Messages = payload.Messages
  173. player_payload.AllBots = payload.AllBots
  174. player_payload.Turn = payload.Turn
  175. for _, r := range p.Robots {
  176. player_payload.MyRobots = append(player_payload.MyRobots, *r)
  177. }
  178. player_payload.Obstacles = []Obstacle{}
  179. player_payload.Splosions = []Splosion{}
  180. player_payload.Projectiles = []Projectile{}
  181. living_robots := 0
  182. for _, r := range p.Robots {
  183. if r.Health > 0 {
  184. living_robots++
  185. // Filter robots by scanner
  186. for player := range g.players {
  187. for _, scan_entry := range r.Scanners {
  188. for _, r := range player.Robots {
  189. if r.Id == scan_entry.Id {
  190. player_payload.OtherRobots = append(
  191. player_payload.OtherRobots,
  192. r.GetTruncatedDetails())
  193. }
  194. }
  195. }
  196. }
  197. // Filter projectiles
  198. for proj := range g.projectiles {
  199. if proj.Owner == r {
  200. player_payload.Projectiles = append(
  201. player_payload.Projectiles,
  202. *proj)
  203. }
  204. for _, scan_entry := range r.Scanners {
  205. if proj.Id == scan_entry.Id {
  206. player_payload.Projectiles = append(
  207. player_payload.Projectiles,
  208. *proj)
  209. }
  210. }
  211. }
  212. // Filter splosions
  213. for splo := range g.splosions {
  214. for _, scan_entry := range r.Scanners {
  215. if splo.Id == scan_entry.Id {
  216. player_payload.Splosions = append(
  217. player_payload.Splosions,
  218. *splo)
  219. }
  220. }
  221. }
  222. // Filter objects
  223. for _, ob := range g.obstacles {
  224. if ob.distance_from_point(r.Position) < float64(r.Stats.ScannerRadius)+r.ScanCounter {
  225. player_payload.Obstacles = append(
  226. player_payload.Obstacles, ob)
  227. }
  228. }
  229. }
  230. }
  231. p.send <- player_payload
  232. }
  233. for s := range g.spectators {
  234. payload.Obstacles = g.obstacles
  235. s.send <- payload
  236. }
  237. }
  238. // run is the method that contians the main game loop.
  239. func (g *Game) run() {
  240. ticker := time.NewTicker(time.Duration(g.tick_duration) * time.Millisecond)
  241. for {
  242. select {
  243. case <-g.kill:
  244. log.Printf("game %s: received kill signal, dying gracefully", g.id)
  245. g.bw.Quit <- true
  246. for player := range g.players {
  247. close(player.send)
  248. }
  249. return
  250. case p := <-g.register:
  251. log.Println("registering player:", p.Id)
  252. g.players[p] = true
  253. g.stats.PlayerStats[p.Id] = &PlayerStats{
  254. BotStats: make(map[string]*BotStats),
  255. }
  256. for _, r := range p.Robots {
  257. g.stats.PlayerStats[p.Id].BotStats[r.Name] = &BotStats{}
  258. r.gameStats = g.stats.PlayerStats[p.Id].BotStats[r.Name]
  259. }
  260. case p := <-g.unregister:
  261. log.Println("unregistering player:", p.Id)
  262. delete(g.players, p)
  263. close(p.send)
  264. case s := <-g.sregister:
  265. log.Println("registering spectator:", s.Id)
  266. g.spectators[s] = true
  267. case s := <-g.sunregister:
  268. log.Println("unregistering spectator:", s.Id)
  269. delete(g.spectators, s)
  270. close(s.send)
  271. case <-ticker.C:
  272. payload := NewBoardstate()
  273. g.turn++
  274. payload.Turn = g.turn
  275. // UPDATE GAME STATE
  276. if end, data := g.mode.gameOver(g); end {
  277. g.sendGameOver(data)
  278. }
  279. g.tick(payload)
  280. g.mode.tick(g, payload)
  281. // SEND THE UPDATE TO EACH PLAYER
  282. g.sendUpdate(payload)
  283. }
  284. }
  285. }
  286. // sendGameOver is a special method that sends a GameOver object to the clients
  287. // instead of a normal Boardstate message.
  288. func (g *Game) sendGameOver(eg *GameOver) {
  289. log.Printf("sending out game over message: %+v", eg)
  290. for p := range g.players {
  291. p.send <- eg
  292. }
  293. for s := range g.spectators {
  294. s.send <- eg
  295. }
  296. }
  297. // returns a GameParam object popuplated by info from the game. This is
  298. // used during client/server initial negociation.
  299. func (g *Game) gameParam() *GameParam {
  300. return &GameParam{
  301. BoardSize: BoardSize{
  302. Width: g.width,
  303. Height: g.height,
  304. },
  305. MaxPoints: g.maxPoints,
  306. Type: "gameparam",
  307. }
  308. }