board.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 NewPartial(0, 0, width, height, width, height)
  33. }
  34. func NewPartial(startX, startY, width, height, totalWidth, totalHeight int) *Board {
  35. r := rand.New(rand.NewSource(time.Now().UnixNano() + int64(startY+startY)))
  36. return newPartial(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. for ry := 0; ry < result.height; ry++ {
  50. i, _ := b.xyToIndex(result.x, result.y+ry)
  51. _, err := result.boardTile.Read(b.data[i : i+byteIndex(result.width)])
  52. if !(err == nil || err == io.EOF) {
  53. log.Printf("ERROR: %v", err)
  54. }
  55. }
  56. result.boardTile.Close()
  57. }
  58. b.placeIglo()
  59. log.Printf("Finished creating board %v x %v\n", width, height)
  60. return b
  61. }
  62. func (b *Board) placeIglo() {
  63. b.Finish.X = b.Width - 2
  64. b.Finish.Y = rand.Intn(b.Height-2) + 1
  65. b.Set(b.Finish.X, b.Finish.Y, Iglo)
  66. b.Set(b.Finish.X, b.Finish.Y-1, Water)
  67. b.Set(b.Finish.X, b.Finish.Y+1, Water)
  68. b.Set(b.Finish.X-1, b.Finish.Y, Water)
  69. b.Set(b.Finish.X+1, b.Finish.Y, Water)
  70. }
  71. type work struct {
  72. x, y int
  73. width int
  74. height int
  75. }
  76. func (b *Board) genRegions(xRegions, yRegions int, responseChan chan response) {
  77. const numWorkers = 50
  78. workChan := make(chan work, numWorkers)
  79. for i := 0; i < numWorkers; i++ {
  80. go worker(workChan, responseChan)
  81. }
  82. for i := 0; i < xRegions; i++ {
  83. for j := 0; j < yRegions; j++ {
  84. x := i * regionWidth
  85. y := j * regionHeight
  86. workChan <- work{x, y, b.Width, b.Height}
  87. }
  88. }
  89. }
  90. func worker(workChan chan work, responseChan chan response) {
  91. for w, open := <-workChan; open; w, open = <-workChan {
  92. var partialWidth, partialHeight int
  93. if w.x+regionWidth > w.width {
  94. partialWidth = w.width - w.x
  95. } else {
  96. partialWidth = regionWidth
  97. }
  98. if w.y+regionHeight > w.height {
  99. partialHeight = w.height - w.y
  100. } else {
  101. partialHeight = regionHeight
  102. }
  103. 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)
  104. log.Printf("Requested generation of tile with url: %v\n", requestUrl)
  105. resp, err := http.Get(requestUrl)
  106. for err != nil {
  107. log.Printf("ERROR requesting region: %v", err)
  108. resp, err = http.Get(requestUrl)
  109. }
  110. result := response{
  111. x: w.x,
  112. y: w.y,
  113. width: partialHeight,
  114. height: partialHeight,
  115. boardTile: resp.Body,
  116. }
  117. responseChan <- result
  118. }
  119. }
  120. func (b *Board) Set(x, y int, t TileType) {
  121. i, p := b.xyToIndex(x, y)
  122. b.data[i] = (b.data[i] & setMask[p]) | byte(t)<<(p<<1)
  123. }
  124. func (b *Board) Get(x, y int) TileType {
  125. i, p := b.xyToIndex(x, y)
  126. return TileType((b.data[i] & getMask[p]) >> uint(p<<1))
  127. }
  128. // Returns the index and offset inside the byte.
  129. func (b *Board) xyToIndex(x, y int) (int, uint) {
  130. width := byteIndex(b.Width) * 4
  131. index := y*width + x
  132. i := index / 4
  133. p := index % 4
  134. return i, uint(p)
  135. }
  136. func byteIndex(x int) int {
  137. return (x + 3) / 4
  138. }
  139. func (b *Board) WriteData(w io.Writer) {
  140. n, err := w.Write(b.data)
  141. if err != nil {
  142. fmt.Errorf("Error writing board after %v bytes: %v", n, err)
  143. }
  144. }
  145. func (b *Board) WriteJSON(w io.Writer, startCol, startRow, cols, rows int) {
  146. sc, sr, cols, rows := sanitizeViewPort(b, startCol, startRow, cols, rows)
  147. fmt.Fprintf(w, "{\"x\":%v,\"y\":%v,\"rows\":%v,\"cols\":%v,\"tiles\":[", sc, sr, cols, rows)
  148. for y := startRow; y < sr+rows; y++ {
  149. for x := startCol; x < sc+cols; x++ {
  150. if !(x == startCol && y == startRow) {
  151. w.Write([]byte{','})
  152. }
  153. t := &jsonTile{x, y, b.Get(x, y).Name(), ""}
  154. bs, _ := json.Marshal(t)
  155. w.Write(bs)
  156. }
  157. }
  158. fmt.Fprintf(w, "]}")
  159. }
  160. func (b *Board) String() string {
  161. var buffer bytes.Buffer
  162. for y := 0; y < b.Height; y++ {
  163. for x := 0; x < b.Width; x++ {
  164. buffer.WriteString(b.Get(x, y).String())
  165. }
  166. buffer.WriteString(fmt.Sprintln())
  167. }
  168. return buffer.String()
  169. }
  170. func newBlank(width, height int) *Board {
  171. return &Board{
  172. Width: width,
  173. Height: height,
  174. data: make([]byte, byteIndex(width)*height),
  175. }
  176. }
  177. func new(width, height int, r *rand.Rand) *Board {
  178. return newPartial(0, 0, width, height, width, height, r)
  179. }
  180. func newPartial(startX, startY, width, height, totalWidth, totalHeight int, r *rand.Rand) *Board {
  181. b := newBlank(width, height)
  182. leftLimit := (totalWidth-maxIceWidth)/2 - startX
  183. rightLimit := totalWidth/2 + maxIceWidth/2 - startX
  184. mid := totalWidth/2 - startX
  185. for y := 0; y < height; y++ {
  186. for x := 0; x < width; x++ {
  187. switch {
  188. case r.Intn(10) > 7:
  189. b.Set(x, y, Rock)
  190. case x > leftLimit && x < rightLimit && r.Intn(maxIceWidth) >= abs(mid-x):
  191. b.Set(x, y, Ice)
  192. default:
  193. b.Set(x, y, Water)
  194. }
  195. }
  196. }
  197. return b
  198. }
  199. func sanitizeViewPort(b *Board, startCol, startRow, cols, rows int) (int, int, int, int) {
  200. if startCol > b.Width {
  201. startCol = b.Width
  202. }
  203. if startCol < 0 {
  204. cols += startCol
  205. startCol = 0
  206. }
  207. if startRow > b.Height {
  208. startRow = b.Height
  209. }
  210. if startRow < 0 {
  211. rows += startRow
  212. startRow = 0
  213. }
  214. if startCol+cols > b.Width {
  215. cols = b.Width - startCol
  216. }
  217. if startRow+rows > b.Height {
  218. rows = b.Height - startRow
  219. }
  220. if cols < 0 {
  221. cols = 0
  222. }
  223. if rows < 0 {
  224. rows = 0
  225. }
  226. return startCol, startRow, cols, rows
  227. }
  228. func abs(a int) int {
  229. if a < 0 {
  230. return -a
  231. }
  232. return a
  233. }