| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- package board
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "math/rand"
- "time"
- )
- type Board struct {
- Cols int `json:"cols"`
- Rows int `json:"rows"`
- Tiles []Tile `json:"tiles"`
- }
- var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
- const maxIceWidth = 26
- // Create a new randomly generated board.
- func New(cols, rows int) Board {
- b := Board{cols, rows, make([]Tile, rows*cols)}
- for y := 0; y < rows; y++ {
- for x := 0; x < cols; x++ {
- b.randomizeTile(x, y)
- }
- }
- return b
- }
- // Set the tile in column x and row y to val.
- func (b Board) Set(x, y int, val Tile) {
- b.Tiles[y*b.Cols+x] = val
- }
- // Get the tile in column x and row y.
- func (b Board) Get(x, y int) Tile {
- return b.Tiles[y*b.Cols+x]
- }
- func (b Board) String() string {
- var buffer bytes.Buffer
- for y := 0; y < b.Rows; y++ {
- for x := 0; x < b.Cols; x++ {
- buffer.WriteString(b.Get(x, y).String())
- }
- buffer.WriteString(fmt.Sprintln())
- }
- return buffer.String()
- }
- type jsonTile struct {
- X int `json:"x"`
- Y int `json:"y"`
- Type string`json:"type"`
- Player string `json:"player,omitempty"`
- }
- func (b Board) WriteJSON(w io.Writer) {
- //fmt.Fpr
- fmt.Fprintf(w, "{rows=\"%v\",columns=\"%v\",tiles={", b.Rows, b.Cols)
- for y := 0; y < b.Rows; y++ {
- for x := 0; x < b.Cols; x++ {
- t := &jsonTile{x, y, b.Get(x, y).Name(), ""}
- bs, _ := json.Marshal(t)
- w.Write(bs)
- w.Write([]byte{','})
- }
- }
- fmt.Fprintf(w, "}}")
- }
- func (b Board) randomizeTile(x, y int) {
- switch {
- case b.isIglo(x, y):
- b.Set(x, y, Iglo)
- case b.isRock(x, y):
- b.Set(x, y, Rock)
- case b.isIce(x, y):
- b.Set(x, y, Ice)
- default:
- b.Set(x, y, Water)
- }
- }
- func (b Board) isIglo(x, y int) bool {
- return x == (b.Cols-1) && y == (b.Rows-1)/2
- }
- func (b Board) isRock(x, y int) bool {
- return rnd.Intn(10) > 7
- }
- func (b Board) isIce(x, y int) bool {
- leftLimit := (b.Cols - maxIceWidth) / 2
- rightLimit := b.Cols/2 + maxIceWidth/2
- return x > leftLimit && x < rightLimit && rnd.Intn(maxIceWidth) >= abs((b.Cols/2)-x)
- }
- func abs(a int) int {
- if a < 0 {
- return -a
- }
- return a
- }
|