board.go 7.2 KB

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