Python,用户输入生成海龟

时间:2016-12-05 14:05:40

标签: python turtle-graphics

我正在尝试设置一个程序,在该程序中,用户决定生成多少只龟,然后他们就会有一场比赛。我目前的解决方案是从用户那里获得一个int输入并执行下面的代码(代码不断重复更大的数字)。我已经尝试过循环,但是我遇到了麻烦,因为他们最终都需要预先形成随机动作。有帮助吗?

if turtNum >= 1:   
  turt1 = Turtle()
  turt1.color(turtColour[0])
  turt1.shape('turtle')

  turt1.penup()
  turt1.goto(0, -10)
  turt1.pendown()

  if turtNum >= 2:

    turt2Name = input('Enter a name for the second turtle: ')

    turt2 = Turtle()
    turt2.color(turtColour[1])
    turt2.shape('turtle')

    turt2.penup()
    turt2.goto(0, -25)
    turt2.pendown()

这是我尝试的代码,但是得到了这个错误“列表索引必须是整数或切片,而不是str”

turtName = []
maxLengthList = turtNum
while len(turtName) < maxLengthList:
    name = input('Enter the names for the turtles: ')
    turtName.append(name)

for i in turtName:
    turtName[i] = Turtle()
    turtName[i].color(turtColour[0])
    turtName[i].shape('turtle')

    turtName[i].penup()
    turtName[i].goto(0, -10)
    turtName[i].pendown()

1 个答案:

答案 0 :(得分:0)

你不能在不期待我们对看到它发生的事情感到兴奋的情况下抛弃海龟赛车的概念。下面是一个粗略的实现,解决了有关输入海龟数量,输入单个海龟信息,存储所有海龟信息以及随机运动的问题:

from turtle import Turtle, Screen
from itertools import cycle
from random import randrange

MAX_TURTLES = 20
LANE_WIDTH = 25
FONT_SIZE = 18
FONT = ("Arial", FONT_SIZE, "normal")
COLORS = cycle(['red', 'green', 'blue', 'cyan', 'black', 'yellow'])
FINISH_LINE = 350
START_LINE = -200
NAME_LINE = START_LINE - 150
DELAY = 100  # milliseconds
MAX_STEP = 10

turtles = dict()

def race():
    for name, turtle in turtles.items():  # should shuffle turtles
        turtle.forward(randrange(MAX_STEP + 1))

        if turtle.xcor() > FINISH_LINE:
            return  # the race is over

    screen.ontimer(race, DELAY)

magic_marker = Turtle(visible=False)
magic_marker.penup()

turtNum = 0

while not 1 <= turtNum <= MAX_TURTLES:
    turtNum = int(input('Enter the number of turtles: '))

for i in range(turtNum):

    name = input('Enter a name for the turtle #{}: '.format(i + 1))

    turtle = Turtle(shape="turtle")
    turtle.color(next(COLORS))

    y_offset = LANE_WIDTH * i - LANE_WIDTH * turtNum // 2

    magic_marker.color(turtle.pencolor())
    magic_marker.goto(NAME_LINE, y_offset - FONT_SIZE / 2)
    magic_marker.write(name, font=FONT)

    turtle.penup()
    turtle.goto(START_LINE, y_offset)
    turtle.pendown()

    turtles[name] = turtle

magic_marker.color('red')
magic_marker.goto(FINISH_LINE, -FINISH_LINE)
magic_marker.pendown()
magic_marker.goto(FINISH_LINE, FINISH_LINE)
magic_marker.penup()

screen = Screen()

screen.ontimer(race, DELAY)

screen.exitonclick()

enter image description here