banner
biuaxia

biuaxia

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

Experiment: turtle.go

title: Experiment: 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:
  • Print
  • Reflection
  • Random
  • Coordinates
  • Methods
  • Pointers
  • Functions
  • Receivers
  • Movement
  • Position

Please write a program that allows a turtle to move up, down, left, and right.

The turtle in the program needs to store a position (x, y), where positive coordinates represent down or right, and use methods to implement movement by incrementing and decrementing the corresponding variables.

Please use the main function to test these methods and print the final position of the turtle.

Hint: To modify the x and y values of the turtle, you need to set the receiver of the method to a pointer.


Sample Solution:

image

Here is the code combining reflection and the random package:

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) // Capitalize method name
	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()
	}
}

Output:

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)
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.