board.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package board
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  8. "math/rand"
  9. "net/http"
  10. "time"
  11. "battlecamp-go-server/flag"
  12. )
  13. var setMask [4]byte = [4]byte{0xFC, 0xF3, 0xCF, 0x3F}
  14. var getMask [4]byte = [4]byte{0x03, 0x0C, 0x30, 0xC0}
  15. type Board struct {
  16. Width int `json:"cols"`
  17. Height int `json:"rows"`
  18. Finish Coordinate `json:"finish"`
  19. data []byte `json:"-"`
  20. }
  21. type response struct {
  22. boardTile io.ReadCloser
  23. x, y, width, height int
  24. }
  25. const (
  26. maxIceWidth = 26
  27. regionWidth = 1024
  28. regionHeight = 1024
  29. )
  30. // Create a new randomly generated board.
  31. func New(width, height int) *Board {
  32. return NewRegion(0, 0, width, height, width, height)
  33. }
  34. func NewRegion(startX, startY, width, height, totalWidth, totalHeight int) *Board {
  35. r := rand.New(rand.NewSource(time.Now().UnixNano() + int64(startY*startY)))
  36. return newRegion(startX, startY, width, height, totalWidth, totalHeight, r)
  37. }
  38. func NewRemote(width, height int) *Board {
  39. log.Printf("Start creating board %v x %v", width, height)
  40. b := newBlank(width, height)
  41. xRegions := (width + (regionWidth - 1)) / regionWidth
  42. yRegions := (height + (regionHeight - 1)) / regionHeight
  43. returnChan := make(chan *response, 32)
  44. defer close(returnChan)
  45. go b.genRegions(xRegions, yRegions, returnChan)
  46. for answers := 0; xRegions*yRegions > answers; answers++ {
  47. result := <-returnChan
  48. log.Printf("Received partial: x=%v, y=%v, width=%v, height=%v\n", result.x, result.y, result.width, result.height)
  49. if result.boardTile == nil {
  50. continue
  51. }
  52. for ry := 0; ry < result.height; ry++ {
  53. i, _ := b.xyToIndex(result.x, result.y+ry)
  54. n, err := result.boardTile.Read(b.data[i : i+byteIndex(result.width)])
  55. if !(err == nil || err == io.EOF) {
  56. log.Printf("ERROR after reading %v bytes: %v\n", n, err)
  57. }
  58. }
  59. result.boardTile.Close()
  60. }
  61. b.placeIglo()
  62. log.Printf("Finished creating board %v x %v\n", width, height)
  63. return b
  64. }
  65. func (b *Board) placeIglo() {
  66. b.Finish.X = b.Width - 2
  67. b.Finish.Y = rand.Intn(b.Height-2) + 1
  68. b.Set(b.Finish.X, b.Finish.Y, Iglo)
  69. b.Set(b.Finish.X, b.Finish.Y-1, Water)
  70. b.Set(b.Finish.X, b.Finish.Y+1, Water)
  71. b.Set(b.Finish.X-1, b.Finish.Y, Water)
  72. b.Set(b.Finish.X+1, b.Finish.Y, Water)
  73. }
  74. type work struct {
  75. x, y int
  76. width int
  77. height int
  78. }
  79. func (b *Board) genRegions(xRegions, yRegions int, responseChan chan *response) {
  80. const numWorkers = 32
  81. workChan := make(chan *work, numWorkers)
  82. for i := 0; i < numWorkers; i++ {
  83. go worker(workChan, responseChan)
  84. }
  85. for i := 0; i < xRegions; i++ {
  86. for j := 0; j < yRegions; j++ {
  87. x := i * regionWidth
  88. y := j * regionHeight
  89. workChan <- &work{x, y, b.Width, b.Height}
  90. }
  91. }
  92. }
  93. func worker(workChan chan *work, responseChan chan *response) {
  94. for w, open := <-workChan; open; w, open = <-workChan {
  95. var partialWidth, partialHeight int
  96. if w.x+regionWidth > w.width {
  97. partialWidth = w.width - w.x
  98. } else {
  99. partialWidth = regionWidth
  100. }
  101. if w.y+regionHeight > w.height {
  102. partialHeight = w.height - w.y
  103. } else {
  104. partialHeight = regionHeight
  105. }
  106. requestUrl := fmt.Sprintf("http://"+ *flag.BoardGenUrl + "/?totalWidth=%v&totalHeight=%v&width=%v&height=%v&x=%v&y=%v", w.width, w.height, partialWidth, partialHeight, w.x, w.y)
  107. log.Printf("Requested generation of tile with url: %v\n", requestUrl)
  108. resp, err := http.Get(requestUrl)
  109. const maxRetries = 3
  110. for retries := 1; err != nil && retries < maxRetries; retries++ {
  111. log.Printf("ERROR requesting region (try %v) : %v", retries, err)
  112. time.Sleep(50 * time.Millisecond)
  113. resp, err = http.Get(requestUrl)
  114. }
  115. var r io.ReadCloser
  116. if err == nil {
  117. r = resp.Body
  118. } else {
  119. log.Printf("ERROR requesting region, skipping (try %v) : %v", maxRetries, err)
  120. }
  121. responseChan <- &response{
  122. x: w.x,
  123. y: w.y,
  124. width: partialHeight,
  125. height: partialHeight,
  126. boardTile: r,
  127. }
  128. }
  129. }
  130. func (b *Board) Set(x, y int, t TileType) {
  131. i, p := b.xyToIndex(x, y)
  132. b.data[i] = (b.data[i] & setMask[p]) | byte(t)<<(p<<1)
  133. }
  134. func (b *Board) Get(x, y int) TileType {
  135. i, p := b.xyToIndex(x, y)
  136. return TileType((b.data[i] & getMask[p]) >> uint(p<<1))
  137. }
  138. // Returns the index and offset inside the byte.
  139. func (b *Board) xyToIndex(x, y int) (int, uint) {
  140. width := byteIndex(b.Width) * 4
  141. index := y*width + x
  142. i := index / 4
  143. p := index % 4
  144. return i, uint(p)
  145. }
  146. func byteIndex(x int) int {
  147. return (x + 3) / 4
  148. }
  149. func (b *Board) WriteData(w io.Writer) {
  150. n, err := w.Write(b.data)
  151. if err != nil {
  152. log.Printf("Error writing board after %v bytes: %v", n, err)
  153. }
  154. }
  155. func (b *Board) WriteJSON(w io.Writer, startCol, startRow, cols, rows int) {
  156. sc, sr, cols, rows := sanitizeViewPort(b, startCol, startRow, cols, rows)
  157. fmt.Fprintf(w, "{\"x\":%v,\"y\":%v,\"rows\":%v,\"cols\":%v,\"tiles\":[", sc, sr, cols, rows)
  158. for y := startRow; y < sr+rows; y++ {
  159. for x := startCol; x < sc+cols; x++ {
  160. if !(x == startCol && y == startRow) {
  161. w.Write([]byte{','})
  162. }
  163. t := &jsonTile{x, y, b.Get(x, y).Name(), ""}
  164. bs, _ := json.Marshal(t)
  165. w.Write(bs)
  166. }
  167. }
  168. fmt.Fprintf(w, "]}")
  169. }
  170. func (b *Board) String() string {
  171. var buffer bytes.Buffer
  172. for y := 0; y < b.Height; y++ {
  173. for x := 0; x < b.Width; x++ {
  174. buffer.WriteString(b.Get(x, y).String())
  175. }
  176. buffer.WriteString(fmt.Sprintln())
  177. }
  178. return buffer.String()
  179. }
  180. func newBlank(width, height int) *Board {
  181. return &Board{
  182. Width: width,
  183. Height: height,
  184. data: make([]byte, byteIndex(width)*height),
  185. }
  186. }
  187. func new(width, height int, r *rand.Rand) *Board {
  188. return newRegion(0, 0, width, height, width, height, r)
  189. }
  190. func newRegion(startX, startY, width, height, totalWidth, totalHeight int, r *rand.Rand) *Board {
  191. b := newBlank(width, height)
  192. leftLimit := (totalWidth-maxIceWidth)/2 - startX
  193. rightLimit := totalWidth/2 + maxIceWidth/2 - startX
  194. mid := totalWidth/2 - startX
  195. for y := 0; y < height; y++ {
  196. for x := 0; x < width; x++ {
  197. switch {
  198. case r.Intn(10) > 7:
  199. b.Set(x, y, Rock)
  200. case x > leftLimit && x < rightLimit && r.Intn(maxIceWidth) >= abs(mid-x):
  201. b.Set(x, y, Ice)
  202. default:
  203. b.Set(x, y, Water)
  204. }
  205. }
  206. }
  207. return b
  208. }
  209. func sanitizeViewPort(b *Board, startCol, startRow, cols, rows int) (int, int, int, int) {
  210. if startCol > b.Width {
  211. startCol = b.Width
  212. }
  213. if startCol < 0 {
  214. cols += startCol
  215. startCol = 0
  216. }
  217. if startRow > b.Height {
  218. startRow = b.Height
  219. }
  220. if startRow < 0 {
  221. rows += startRow
  222. startRow = 0
  223. }
  224. if startCol+cols > b.Width {
  225. cols = b.Width - startCol
  226. }
  227. if startRow+rows > b.Height {
  228. rows = b.Height - startRow
  229. }
  230. if cols < 0 {
  231. cols = 0
  232. }
  233. if rows < 0 {
  234. rows = 0
  235. }
  236. return startCol, startRow, cols, rows
  237. }
  238. func abs(a int) int {
  239. if a < 0 {
  240. return -a
  241. }
  242. return a
  243. }