board.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package board
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "math/rand"
  8. )
  9. type Board struct {
  10. Cols int `json:"cols"`
  11. Rows int `json:"rows"`
  12. Tiles []Tile `json:"tiles"`
  13. }
  14. const maxIceWidth = 26
  15. // Create a new randomly generated board.
  16. func New(cols, rows int) Board {
  17. b := Board{cols, rows, make([]Tile, rows*cols)}
  18. for y := 0; y < rows; y++ {
  19. for x := 0; x < cols; x++ {
  20. b.randomizeTile(x, y)
  21. }
  22. }
  23. return b
  24. }
  25. // Set the tile in column x and row y to val.
  26. func (b Board) Set(x, y int, val Tile) {
  27. b.Tiles[y*b.Cols+x] = val
  28. }
  29. // Get the tile in column x and row y.
  30. func (b Board) Get(x, y int) Tile {
  31. return b.Tiles[y*b.Cols+x]
  32. }
  33. func (b Board) String() string {
  34. var buffer bytes.Buffer
  35. for y := 0; y < b.Rows; y++ {
  36. for x := 0; x < b.Cols; x++ {
  37. buffer.WriteString(b.Get(x, y).String())
  38. }
  39. buffer.WriteString(fmt.Sprintln())
  40. }
  41. return buffer.String()
  42. }
  43. type jsonTile struct {
  44. X int `json:"x"`
  45. Y int `json:"y"`
  46. Type string `json:"type"`
  47. Player string `json:"player,omitempty"`
  48. }
  49. func (b Board) WriteJSON(w io.Writer) {
  50. //fmt.Fpr
  51. fmt.Fprintf(w, "{rows=\"%v\",columns=\"%v\",tiles={", b.Rows, b.Cols)
  52. for y := 0; y < b.Rows; y++ {
  53. for x := 0; x < b.Cols; x++ {
  54. t := &jsonTile{x, y, b.Get(x, y).Name(), ""}
  55. bs, _ := json.Marshal(t)
  56. w.Write(bs)
  57. w.Write([]byte{','})
  58. }
  59. }
  60. fmt.Fprintf(w, "}}")
  61. }
  62. func (b Board) randomizeTile(x, y int) {
  63. switch {
  64. case b.isIglo(x, y):
  65. b.Set(x, y, Iglo)
  66. case b.isRock(x, y):
  67. b.Set(x, y, Rock)
  68. case b.isIce(x, y):
  69. b.Set(x, y, Ice)
  70. default:
  71. b.Set(x, y, Water)
  72. }
  73. }
  74. func (b Board) isIglo(x, y int) bool {
  75. return x == (b.Cols-1) && y == (b.Rows-1)/2
  76. }
  77. func (b Board) isRock(x, y int) bool {
  78. return rand.Intn(10) > 7
  79. }
  80. func (b Board) isIce(x, y int) bool {
  81. leftLimit := (b.Cols - maxIceWidth) / 2
  82. rightLimit := b.Cols/2 + maxIceWidth/2
  83. return x > leftLimit && x < rightLimit && rand.Intn(maxIceWidth) >= abs((b.Cols/2)-x)
  84. }
  85. func abs(a int) int {
  86. if a < 0 {
  87. return -a
  88. }
  89. return a
  90. }