如何让 python 乌龟根据文本文件移动

How to get python turtle to move according to a text file

import turtle as t
from turtle import *
from math import sin, pi, sqrt
setup(500, 500)
Screen()
title("Turtle Art")
showturtle()
screen = Screen()
yertle = Turtle()

turn = 90
speed = 10
moves = []

def k1():
    t.forward(speed)
    moves.append(1)

def k2():
    t.left(turn)
    moves.append(2)

def k3():
    t.right(turn)
    moves.append(3)

def k4():
    t.backward(speed)
    moves.append(4)

def k102():
    if input("Would you like to save this? (y/n) ") == "y":
        name = input("What would you like to call your masterpiece? ")
        my_file = open("./%s" % (name), "w")
        global moves
        moves = str(moves)
        my_file.write(moves)
        my_file.close()
        print("It has been saved as:", name)
    else:
        t.clear

t.onkey(k1, "Up") #move forwards
t.onkey(k2, "Left") #turn left
t.onkey(k3, "Right") #turn right
t.onkey(k4, "Down") # move backwards

t.onkey(k102, "p") #save page

listen()
mainloop()

这会将其作为列表保存在当前文件夹的文本文件中(看起来像这样:[1, 1, 2, 1, 3, 3, 1])。我想知道如何让乌龟根据 1、2、3 或 4 移动来重现这一点。有什么方法可以轻松地从文本文件中读取吗?

这个 python 的文件 IO 教程应该对您有所帮助:http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

您要特别注意分割线部分。您可能希望基于逗号而不是空格来拆分行。

如果只有一行,则可能没有必要使用循环遍历文本文件。如果你正确地分割线,它应该给你一个很好的数字数组,这些数字对应于乌龟应该做的动作。类似于:

file = open("movefile.txt","r")
moves = file.readline().split(",")

可能有用。这完全取决于如何设置包含预先存在的移动的文本文件。

编辑:

以不同的方式将移动写入文本文件可能会有所帮助。当你试图阅读它们时,它会让你省去一些头痛。与其说 my_file.write(moves),不如使用:

for i in moves:
     my_file.write(str(i)+",")

这应该使您的文本文件看起来像“1,1,1,2,3,3,1,”

使用这种格式,我输入的第一段代码应该可以将所有数字放入 "moves" 数组。我建议将该数组名称更改为 "moves_from_file" 之类的名称。一旦你拥有了...

for j in moves_from_file:
     if moves_from_file[j] == "1":
         k1()
     if moves_from_file[j] == "2":
         k2()
     if moves_from_file[j] == "3":
         k3()
     if moves_from_file[j] == "4":
         k4()

应该可以解决问题。

加载引起了几个问题,"Do you want to be able to load over an existing drawing to augment it?"、"Do you want to give the user the opportunity to save the current drawing before loading another?"、"Should you clear the drawing before loading?"。以下解决方案尝试允许所有这些可能性,让用户保存、清除 and/or 将一幅图加载到另一幅图之上,这可以保存为更复杂的图:

from turtle import Turtle, Screen

ANGLE = 90
DISTANCE = 10

def k1():
    yertle.forward(DISTANCE)
    moves.append(1)

def k2():
    yertle.left(ANGLE)
    moves.append(2)

def k3():
    yertle.right(ANGLE)
    moves.append(3)

def k4():
    yertle.backward(DISTANCE)
    moves.append(4)

COMMANDS = {1: k1, 2: k2, 3: k3, 4: k4}

def save():
    if moves and input('Would you like to save this drawing? (y/n) ').lower().startswith('y'):
        name = input('What would you like to call your drawing? ')

        with open(name, 'w') as my_file:
                    print(*moves, sep=', ', file=my_file)

        print('Drawing has been saved as:', name)

def clear():
    global moves

    save()

    if moves and input('Would you like to erase this drawing? (y/n) ').lower().startswith('y'):
        moves = []
        yertle.reset()

def load():
    clear()

    if input('Would you like to load a drawing? (y/n) ').lower().startswith('y'):
        name = input('What would drawing would you like to load? ')

        with open(name) as my_file:
            commands = [int(digit) for digit in my_file.readline().split(',')]

        for command in commands:
            if command in COMMANDS:
                COMMANDS[command]()

        print('Drawing has been loaded from:', name)


screen = Screen()
screen.setup(500, 500)
screen.title('Turtle Art')

moves = []

yertle = Turtle('turtle')

screen.onkey(k1, 'Up')  # move forwards
screen.onkey(k2, 'Left')  # turn left
screen.onkey(k3, 'Right')  # turn right
screen.onkey(k4, 'Down')  # move backwards

screen.onkey(clear, 'c')  # clear page
screen.onkey(save, 'p')  # save page
screen.onkey(load, 'l')  # load page

screen.listen()

screen.mainloop()