starfield.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "red-green/door"
  6. "strings"
  7. "time"
  8. "github.com/seehuhn/mt19937"
  9. )
  10. type StarPos struct {
  11. Y int
  12. X int
  13. Symbol int
  14. Color bool
  15. }
  16. type StarField struct {
  17. RNG *rand.Rand
  18. MX int
  19. MY int
  20. Sky map[StarPos]bool
  21. }
  22. func (s *StarField) make_pos() StarPos {
  23. for {
  24. pos := StarPos{X: s.RNG.Intn(s.MX), Y: s.RNG.Intn(s.MY)}
  25. _, found := (*s).Sky[pos]
  26. if !found {
  27. return pos
  28. }
  29. }
  30. }
  31. func (s *StarField) Regenerate() {
  32. s.MX = door.Width
  33. s.MY = door.Height
  34. s.Sky = make(map[StarPos]bool)
  35. s.RNG = rand.New(mt19937.New())
  36. s.RNG.Seed(time.Now().UnixNano())
  37. max_stars := ((s.MX * s.MY) / 40)
  38. for i := 0; i < max_stars; i++ {
  39. pos := s.make_pos()
  40. pos.Symbol = i % 2
  41. pos.Color = i%5 < 2
  42. s.Sky[pos] = true
  43. }
  44. }
  45. func (s *StarField) Display(d *door.Door) {
  46. white := door.ColorText("WHITE")
  47. dark := door.ColorText("BOLD BLACK")
  48. d.Write(door.Reset + door.Clrscr)
  49. var stars [2]string
  50. stars[0] = "."
  51. if door.Unicode {
  52. stars[1] = "\u2219"
  53. } else {
  54. stars[1] = "\xf9"
  55. }
  56. var i int = 0
  57. var last_pos StarPos
  58. // maps in go are not sorted
  59. for pos, _ := range s.Sky {
  60. use_goto := true
  61. if i != 0 {
  62. if pos.Y == last_pos.Y {
  63. dx := pos.X - last_pos.X
  64. // Sometimes pos.X < last_pos.X
  65. if dx == 0 {
  66. use_goto = false
  67. } else {
  68. if dx < 0 {
  69. // handle negative
  70. // fmt.Printf("from %#v to %#v\n", last_pos, pos)
  71. dx = -dx
  72. if dx < 5 {
  73. d.Write(strings.Repeat("\x08", dx))
  74. } else {
  75. d.Write(fmt.Sprintf("\x1b[%dD", dx))
  76. }
  77. use_goto = false
  78. } else {
  79. if dx < 5 {
  80. d.Write(strings.Repeat(" ", dx))
  81. } else {
  82. d.Write(fmt.Sprintf("\x1b[%dC", dx))
  83. }
  84. use_goto = false
  85. }
  86. }
  87. }
  88. }
  89. if use_goto {
  90. d.Write(door.Goto(pos.X, pos.Y))
  91. }
  92. if pos.Color {
  93. d.Write(dark)
  94. } else {
  95. d.Write(white)
  96. }
  97. d.Write(stars[pos.Symbol])
  98. last_pos = pos
  99. last_pos.X++
  100. i++
  101. }
  102. }