banner
biuaxia

biuaxia

"万物皆有裂痕,那是光进来的地方。"
github
bilibili
tg_channel

實驗:turtle.go

標題:實驗:turtle.go
日期:2022-06-19 20:21:00
toc:false
index_img:http://api.btstu.cn/sjbz/?lx=m_dongman&cid=5
類別:

  • Go
    標籤:
  • 打印
  • 反射
  • 隨機
  • 坐標
  • 方法
  • 指針
  • 函數
  • 接收者
  • 移動
  • 位置

請編寫一個可以讓海龜上下左右移動的程式。

程式中的海龜需要存儲一個位置 (x, y),正數坐標表示向下或向右,並通過使用方法對相應的變數實施自增和自減來實現移動。

請使用 main 函數測試這些方法並打印出海龜的最終位置。

提示:為了修改海龜的 x 值和 y 值,你需要將方法的接收者設置為指針。


標準答案:

image

結合反射和隨機包的程式碼如下:

package main

import (
	"fmt"
	"math/rand"
	"reflect"
	"time"
)

type seaTurtle struct {
	x, y int
}

func (s *seaTurtle) Up() {
	s.y++
}

func (s *seaTurtle) Down() {
	s.y--
}

func (s *seaTurtle) Left() {
	s.x--
}

func (s *seaTurtle) Right() {
	s.x++
}

var positions = []string{
	"Up",
	"Down",
	"Left",
	"Right",
}

func (s *seaTurtle) randMove() {
	rand.Seed(time.Now().UnixMilli())
	time.Sleep(time.Millisecond * 5)
	randNum := rand.Intn(4)
	positionStr := positions[randNum]
	valueOf := reflect.ValueOf(s)
	method := valueOf.MethodByName(positionStr) // 方法名大寫
	method.Call(nil)
	fmt.Printf("seaTurtle %s, now position: (%d, %d)\n", positionStr, s.x, s.y)
}

func main() {
	turtle := &seaTurtle{-5, 10}
	for i := 0; i < 5; i++ {
		turtle.randMove()
	}
}

執行結果:

seaTurtle Up, now position: (-5, 11)
seaTurtle Left, now position: (-6, 11)
seaTurtle Left, now position: (-7, 11)
seaTurtle Up, now position: (-7, 12)
seaTurtle Down, now position: (-7, 11)
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。