0

我写了一个函数,它允许你通过 python shell 控制turtle模块,这里是它的一部分:

import turtle
turtle.showturtle()
def turtle_commands():
    instructions = input().split()
    i = instructions[0]
    if len(instructions) == 2:
        if i == 'forward' :
            n = int(instructions[1])
            turtle.forward(n)

例如当你输入

forward 100

乌龟向前移动 100 像素。我对大多数海龟命令都做了同样的事情——向后、向左、向右、向上、向下、颜色等等。

我的问题是,有没有办法从文本文件中加载这些命令?我在想类似的事情

instructions = input().split()
i = instructions[0]
if i == 'load' :
    n = str(instructions[1])
    l = open(n, 'r')
    while True:
        line = l.readline()
        turtle_commands(line) #i don't really know what i did here, but hopefully you get the point
        if not line:
            break

程序必须接受来自文件和外壳的命令。谢谢您的回答。

4

4 回答 4

3

假设所有命令的格式为<command> <pixels>

# Create a dictionary of possible commands, with the values being pointers
# to the actual function - so that we can call the commands like so:
# commands[command](argument)
commands = {
    'forward': turtle.forward,
    'backwards': turtle.backward,
    'left': turtle.left,
    'right': turtle.right
    # etc., etc.
}

# Use the `with` statement for some snazzy, automatic
# file setting-up and tearing-down
with open('instructions_file', 'r') as instructions:
    for instruction in instructions:  # for line in intructions_file
        # split the line into command, pixels
        instruction, pixels = instruction.split()

        # If the parsed instruction is in `commands`, then run it.
        if instruction in commands:
            commands[instruction](pixels)
        else:
        # If it's not, then raise an error.
            raise()
于 2012-12-07T06:36:50.097 回答
1

应该很简单——只需更改您的turtle_commands()函数以从参数而不是函数获取其输入input(),如下所示:

def turtle_commands(command):
    instructions = command.split()
    i = instructions[0]
    if len(instructions) == 2:
        if i == 'forward' :
            n = int(instructions[1])
            turtle.forward(n)

然后,使用您从文件中读取的输入命令调用您的函数,就像您在建议的代码中使用turtle_commands(line).

于 2012-12-07T06:37:35.883 回答
0

使用map()underitertools就足够了。l.readlines()将文件中的所有行作为列表返回,map内置函数将遍历列表中的所有元素并将它们作为参数提供给函数 turtle_commands

map(turtle_commands, [ int(_) for _ in l.readlines() ] )

map()将为函数提供参数列表。

map(function, params_list)

>>> map(lambda x: x + 1, [1, 2, 3, 4, 5, 6])
[2, 3, 4, 5, 6, 7]
于 2012-12-07T06:34:40.177 回答
0

有一个非常简单的解决方案 - 使用getattr函数。如果您有一系列空格/行尾命令:

instructions = data.split()
commands = instructions[::2]
params   = instructions[1::2]
for command, param in zip(commands,params):
    try:
        getattr(turtle, command)(int(param))
    except AttributeError:
        print('Bad command name:{}'.format(command))
于 2012-12-07T07:26:46.997 回答