banner
biuaxia

biuaxia

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

実験:turtle.go

title: 実験:turtle.go
date: 2022-06-19 20:21:00
toc: false
index_img: http://api.btstu.cn/sjbz/?lx=m_dongman&cid=5
category:

  • Go
    tags:
  • プリント
  • 反射
  • ランダム
  • 座標
  • メソッド
  • ポインタ
  • 関数
  • レシーバ
  • 移動
  • 位置

海亀が上下左右に移動できるプログラムを作成してください。

プログラム内の海亀は位置 (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)
読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。