board.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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/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(startX*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: partialWidth, //hier zat de bug dat het bord er gaar uit zag
  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. i, p := b.xyToIndex(x, y)
  137. return TileType((b.data[i] & getMask[p]) >> uint(p<<1))
  138. }
  139. // Returns the index and offset inside the byte.
  140. func (b *Board) xyToIndex(x, y int) (int, uint) {
  141. width := byteIndex(b.Width) * 4
  142. index := y*width + x
  143. i := index / 4
  144. p := index % 4
  145. return i, uint(p)
  146. }
  147. func byteIndex(x int) int {
  148. return (x + 3) / 4
  149. }
  150. func (b *Board) WriteData(w io.Writer) {
  151. n, err := w.Write(b.data)
  152. if err != nil {
  153. log.Printf("Error writing board after %v bytes: %v", n, err)
  154. }
  155. }
  156. func (b *Board) WriteJSON(w io.Writer, startWidth, startHeight, width, height int) {
  157. // log.Printf("x:%v,y:%v,rows:%v,cols:%v", startWidth, startHeight, height, width)
  158. sc, sr, width, height := SanitizeViewPort(b, startWidth, startHeight, width, height)
  159. // log.Printf("x:%v,y:%v,rows:%v,cols:%v", sc, sr, height, width)
  160. fmt.Fprintf(w, "{\"x\":%v,\"y\":%v,\"rows\":%v,\"cols\":%v,\"tiles\":[", sc, sr, height, width)
  161. for y := startHeight; y < sr+height; y++ {
  162. for x := startWidth; x < sc+width; x++ {
  163. if !(x == startWidth && y == startHeight) {
  164. w.Write([]byte{','})
  165. }
  166. t := &jsonTile{x, y, b.Get(x, y).Name(), ""}
  167. bs, _ := json.Marshal(t)
  168. w.Write(bs)
  169. }
  170. }
  171. fmt.Fprintf(w, "]}")
  172. }
  173. func ReadJSON(ofsetX, ofsetY int, reader io.Reader) *Board {
  174. b, _ := ioutil.ReadAll(reader)
  175. jsonBoard := new(boardJSON)
  176. json.Unmarshal(b, &jsonBoard)
  177. board := newBlank(jsonBoard.Width, jsonBoard.Height)
  178. for _, t := range jsonBoard.Tiles {
  179. board.Set(t.X-ofsetX, t.Y-ofsetY, FromName(t.Type))
  180. }
  181. return board
  182. }
  183. type boardJSON struct {
  184. X int `json:"x"`
  185. Y int `json:"y"`
  186. Height int `json:"rows"`
  187. Width int `json:"cols"`
  188. Tiles []jsonTile `json:"tiles"`
  189. }
  190. func (b *Board) String() string {
  191. var buffer bytes.Buffer
  192. for y := 0; y < b.Height; y++ {
  193. for x := 0; x < b.Width; x++ {
  194. buffer.WriteString(b.Get(x, y).String())
  195. }
  196. buffer.WriteString(fmt.Sprintln())
  197. }
  198. return buffer.String()
  199. }
  200. func newBlank(width, height int) *Board {
  201. return &Board{
  202. Width: width,
  203. Height: height,
  204. data: make([]byte, byteIndex(width)*height),
  205. }
  206. }
  207. func NewPreset(width, height int, data []byte) *Board {
  208. return &Board{
  209. Width: width,
  210. Height: height,
  211. data: data,
  212. }
  213. }
  214. func newBoard(width, height int, r *rand.Rand) *Board {
  215. return newRegion(0, 0, width, height, width, height, r)
  216. }
  217. func newRegion(startX, startY, width, height, totalWidth, totalHeight int, r *rand.Rand) *Board {
  218. b := newBlank(width, height)
  219. leftLimit := (totalWidth-maxIceWidth)/2 - startX
  220. rightLimit := totalWidth/2 + maxIceWidth/2 - startX
  221. mid := totalWidth/2 - startX
  222. log.Printf("Creating new region width %v height %v", width, height)
  223. for y := 0; y < height; y++ {
  224. for x := 0; x < width; x++ {
  225. switch {
  226. case r.Intn(10) > 7:
  227. b.Set(x, y, Rock)
  228. case x > leftLimit && x < rightLimit && r.Intn(maxIceWidth) >= abs(mid-x):
  229. b.Set(x, y, Ice)
  230. default:
  231. b.Set(x, y, Water)
  232. }
  233. }
  234. }
  235. return b
  236. }
  237. func SanitizeViewPort(b *Board, startWidth, startHeight, width, height int) (int, int, int, int) {
  238. if startWidth > b.Width {
  239. startWidth = b.Width
  240. }
  241. if startWidth < 0 {
  242. // width += startWidth
  243. startWidth = 0
  244. }
  245. if startHeight > b.Height {
  246. startHeight = b.Height
  247. }
  248. if startHeight < 0 {
  249. // height += startHeight
  250. startHeight = 0
  251. }
  252. if startWidth+width > b.Width {
  253. width = b.Width - startWidth
  254. }
  255. if startHeight+height > b.Height {
  256. height = b.Height - startHeight
  257. }
  258. if width < 0 {
  259. width = 0
  260. }
  261. if height < 0 {
  262. height = 0
  263. }
  264. return startWidth, startHeight, width, height
  265. }
  266. func abs(a int) int {
  267. if a < 0 {
  268. return -a
  269. }
  270. return a
  271. }