将 turtle 命令分配给变量并在 python 上调用它们

Assigning turtle commands to variables and recalling them on python

我想这样分配 turtle 命令:

F = turt.forward(30)
+ = turt.left(90)
- = turt.right(90)

但是它不允许我将这些命令分配给 + 和 -,我不希望它执行命令。我也不知道如何执行它们。我想使用这些变量来纠正 "F+F-F++FF"

import turtle
f = turt.forward(30)
+ = turt.left(90)
- = turt.right(90)
F+F-F-FF+F

首先,您需要定义一些函数,我们将使用这些函数来定义您的 turtle 对象的操作:

def forward():
    turt.forward(30)

def left():
    turt.left(90)

def right():
    turt.right(90)

接下来,我们需要创建一个字典,将字符串键映射到我们刚刚定义的函数:

map = {'F': forward, '+': left, '-'; right} # F will cause the turtle to go forward by 30

最后,我们必须遍历字符串序列才能根据此映射调用函数:

for command in 'F+F-F++FF':
   map[command]()