package board import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "log" "math/rand" "net/http" "time" "battlecamp-go/flag" ) var setMask [4]byte = [4]byte{0xFC, 0xF3, 0xCF, 0x3F} var getMask [4]byte = [4]byte{0x03, 0x0C, 0x30, 0xC0} type Board struct { Width int `json:"cols"` Height int `json:"rows"` Finish Coordinate `json:"finish"` data []byte `json:"-"` } type response struct { boardTile io.ReadCloser x, y, width, height int } const ( maxIceWidth = 26 regionWidth = 1024 regionHeight = 1024 ) // Create a new randomly generated board. func New(width, height int) *Board { return NewRegion(0, 0, width, height, width, height) } func NewRegion(startX, startY, width, height, totalWidth, totalHeight int) *Board { r := rand.New(rand.NewSource(time.Now().UnixNano() + int64(startX*startY))) return newRegion(startX, startY, width, height, totalWidth, totalHeight, r) } func NewRemote(width, height int) *Board { log.Printf("Start creating board %v x %v", width, height) b := newBlank(width, height) xRegions := (width + (regionWidth - 1)) / regionWidth yRegions := (height + (regionHeight - 1)) / regionHeight returnChan := make(chan *response, 32) defer close(returnChan) go b.genRegions(xRegions, yRegions, returnChan) for answers := 0; xRegions*yRegions > answers; answers++ { result := <-returnChan log.Printf("Received partial: x=%v, y=%v, width=%v, height=%v\n", result.x, result.y, result.width, result.height) if result.boardTile == nil { continue } for ry := 0; ry < result.height; ry++ { i, _ := b.xyToIndex(result.x, result.y+ry) n, err := result.boardTile.Read(b.data[i : i+byteIndex(result.width)]) if !(err == nil || err == io.EOF) { log.Printf("ERROR after reading %v bytes: %v\n", n, err) } } result.boardTile.Close() } b.placeIglo() log.Printf("Finished creating board %v x %v\n", width, height) return b } func (b *Board) placeIglo() { b.Finish.X = b.Width - 2 b.Finish.Y = rand.Intn(b.Height-2) + 1 b.Set(b.Finish.X, b.Finish.Y, Iglo) b.Set(b.Finish.X, b.Finish.Y-1, Water) b.Set(b.Finish.X, b.Finish.Y+1, Water) b.Set(b.Finish.X-1, b.Finish.Y, Water) b.Set(b.Finish.X+1, b.Finish.Y, Water) } type work struct { x, y int width int height int } func (b *Board) genRegions(xRegions, yRegions int, responseChan chan *response) { const numWorkers = 32 workChan := make(chan *work, numWorkers) for i := 0; i < numWorkers; i++ { go worker(workChan, responseChan) } for i := 0; i < xRegions; i++ { for j := 0; j < yRegions; j++ { x := i * regionWidth y := j * regionHeight workChan <- &work{x, y, b.Width, b.Height} } } } func worker(workChan chan *work, responseChan chan *response) { for w, open := <-workChan; open; w, open = <-workChan { var partialWidth, partialHeight int if w.x+regionWidth > w.width { partialWidth = w.width - w.x } else { partialWidth = regionWidth } if w.y+regionHeight > w.height { partialHeight = w.height - w.y } else { partialHeight = regionHeight } 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) log.Printf("Requested generation of tile with url: %v\n", requestUrl) resp, err := http.Get(requestUrl) const maxRetries = 3 for retries := 1; err != nil && retries < maxRetries; retries++ { log.Printf("ERROR requesting region (try %v) : %v", retries, err) time.Sleep(50 * time.Millisecond) resp, err = http.Get(requestUrl) } var r io.ReadCloser if err == nil { r = resp.Body } else { log.Printf("ERROR requesting region, skipping (try %v) : %v", maxRetries, err) } responseChan <- &response{ x: w.x, y: w.y, width: partialWidth, //hier zat de bug dat het bord er gaar uit zag height: partialHeight, boardTile: r, } } } func (b *Board) Set(x, y int, t TileType) { i, p := b.xyToIndex(x, y) b.data[i] = (b.data[i] & setMask[p]) | byte(t)<<(p<<1) } func (b *Board) Get(x, y int) TileType { i, p := b.xyToIndex(x, y) return TileType((b.data[i] & getMask[p]) >> uint(p<<1)) } // Returns the index and offset inside the byte. func (b *Board) xyToIndex(x, y int) (int, uint) { width := byteIndex(b.Width) * 4 index := y*width + x i := index / 4 p := index % 4 return i, uint(p) } func byteIndex(x int) int { return (x + 3) / 4 } func (b *Board) WriteData(w io.Writer) { n, err := w.Write(b.data) if err != nil { log.Printf("Error writing board after %v bytes: %v", n, err) } } func (b *Board) WriteJSON(w io.Writer, startWidth, startHeight, width, height int) { // log.Printf("x:%v,y:%v,rows:%v,cols:%v", startWidth, startHeight, height, width) sc, sr, width, height := SanitizeViewPort(b, startWidth, startHeight, width, height) // log.Printf("x:%v,y:%v,rows:%v,cols:%v", sc, sr, height, width) fmt.Fprintf(w, "{\"x\":%v,\"y\":%v,\"rows\":%v,\"cols\":%v,\"tiles\":[", sc, sr, height, width) for y := startHeight; y < sr+height; y++ { for x := startWidth; x < sc+width; x++ { if !(x == startWidth && y == startHeight) { w.Write([]byte{','}) } t := &jsonTile{x, y, b.Get(x, y).Name(), ""} bs, _ := json.Marshal(t) w.Write(bs) } } fmt.Fprintf(w, "]}") } func ReadJSON(ofsetX, ofsetY int, reader io.Reader) *Board { b, _ := ioutil.ReadAll(reader) jsonBoard := new(boardJSON) json.Unmarshal(b, &jsonBoard) board := newBlank(jsonBoard.Width, jsonBoard.Height) for _, t := range jsonBoard.Tiles { board.Set(t.X-ofsetX, t.Y-ofsetY, FromName(t.Type)) } return board } type boardJSON struct { X int `json:"x"` Y int `json:"y"` Height int `json:"rows"` Width int `json:"cols"` Tiles []jsonTile `json:"tiles"` } func (b *Board) String() string { var buffer bytes.Buffer for y := 0; y < b.Height; y++ { for x := 0; x < b.Width; x++ { buffer.WriteString(b.Get(x, y).String()) } buffer.WriteString(fmt.Sprintln()) } return buffer.String() } func newBlank(width, height int) *Board { return &Board{ Width: width, Height: height, data: make([]byte, byteIndex(width)*height), } } func NewPreset(width, height int, data []byte) *Board { return &Board{ Width: width, Height: height, data: data, } } func newBoard(width, height int, r *rand.Rand) *Board { return newRegion(0, 0, width, height, width, height, r) } func newRegion(startX, startY, width, height, totalWidth, totalHeight int, r *rand.Rand) *Board { b := newBlank(width, height) leftLimit := (totalWidth-maxIceWidth)/2 - startX rightLimit := totalWidth/2 + maxIceWidth/2 - startX mid := totalWidth/2 - startX log.Printf("Creating new region width %v height %v", width, height) for y := 0; y < height; y++ { for x := 0; x < width; x++ { switch { case r.Intn(10) > 7: b.Set(x, y, Rock) case x > leftLimit && x < rightLimit && r.Intn(maxIceWidth) >= abs(mid-x): b.Set(x, y, Ice) default: b.Set(x, y, Water) } } } return b } func SanitizeViewPort(b *Board, startWidth, startHeight, width, height int) (int, int, int, int) { if startWidth > b.Width { startWidth = b.Width } if startWidth < 0 { // width += startWidth startWidth = 0 } if startHeight > b.Height { startHeight = b.Height } if startHeight < 0 { // height += startHeight startHeight = 0 } if startWidth+width > b.Width { width = b.Width - startWidth } if startHeight+height > b.Height { height = b.Height - startHeight } if width < 0 { width = 0 } if height < 0 { height = 0 } return startWidth, startHeight, width, height } func abs(a int) int { if a < 0 { return -a } return a }