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.9KB

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