第五部分习题 - 图1

    第五部分习题 - 图2

    1. package main
    2. import (
    3. "fmt"
    4. "math/rand"
    5. "time"
    6. )
    7. type honeyBee struct {
    8. name string
    9. }
    10. func (hb honeyBee) String() string {
    11. return hb.name
    12. }
    13. func (hb honeyBee) move() string {
    14. switch rand.Intn(2) {
    15. case 0:
    16. return "buzzes about"
    17. default:
    18. return "flies to infinity and beyond"
    19. }
    20. }
    21. func (hb honeyBee) eat() string {
    22. switch rand.Intn(2) {
    23. case 0:
    24. return "pollen"
    25. default:
    26. return "nectar"
    27. }
    28. }
    29. type gopher struct {
    30. name string
    31. }
    32. func (g gopher) String() string {
    33. return g.name
    34. }
    35. func (g gopher) move() string {
    36. switch rand.Intn(2) {
    37. case 0:
    38. return "scurries along the ground"
    39. default:
    40. return "burrows in the sand"
    41. }
    42. }
    43. func (g gopher) eat() string {
    44. switch rand.Intn(5) {
    45. case 0:
    46. return "carrot"
    47. case 1:
    48. return "lettuce"
    49. case 2:
    50. return "radish"
    51. case 3:
    52. return "corn"
    53. default:
    54. return "root"
    55. }
    56. }
    57. type animal interface {
    58. move() string
    59. eat() string
    60. }
    61. func step(a animal) {
    62. switch rand.Intn(2) {
    63. case 0:
    64. fmt.Printf("%v %v.\n", a, a.move())
    65. default:
    66. fmt.Printf("%v eats the %v.\n", a, a.eat())
    67. }
    68. }
    69. const sunrise, sunset = 8, 18
    70. func main() {
    71. rand.Seed(time.Now().UnixNano())
    72. animals := []animal{
    73. honeyBee{name: "Bzzz Lightyear"},
    74. gopher{name: "Go gopher"},
    75. }
    76. var sol, hour int
    77. for {
    78. fmt.Printf("%2d:00 ", hour)
    79. if hour < sunrise || hour >= sunset {
    80. fmt.Println("The animals are sleeping.")
    81. } else {
    82. i := rand.Intn(len(animals))
    83. step(animals[i])
    84. }
    85. time.Sleep(500 * time.Millisecond)
    86. hour++
    87. if hour >= 24 {
    88. hour = 0
    89. sol++
    90. if sol >= 3 {
    91. break
    92. }
    93. }
    94. }
    95. }