0

Pythonシェルを介してタートルモジュールを制御できる関数を作成しました。その一部を次に示します。

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()下で使えitertoolsば十分です。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

非常に簡単な解決策があります - gettr関数を使用します。一連のスペース/行末コマンドがある場合:

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 に答える