board.go 6.2 KB

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