board.go 5.8 KB

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