Код Python не работает: не печатает победителя - PullRequest
0 голосов
/ 01 июня 2018

Мне было интересно, почему мой код продолжает печатать 'tan', я не могу заставить его напечатать фактического победителя.

import turtle
import random

turtles = []


def setup():
    global turtles
    startline = -610
    screen = turtle.Screen()
    screen.bgpic('pavement.gif')
    screen.setup(1290, 720)


    turtle_ycor = [-40, -20, 0, 20, 40]
    turtle_color = ['pink', 'skyblue', 'indigo', 'turquoise', 'tan']

    for i in range(0, len(turtle_ycor)):

        new_turtle = turtle.Turtle()
        new_turtle.shape('turtle')
        new_turtle.penup()
        new_turtle.setpos(startline, turtle_ycor[i])
        new_turtle.color(turtle_color[i])
        new_turtle.pendown()
        turtles.append(new_turtle)


def race():
    global turtles
    winner = False
    finishline = 550

    while not winner:
        for current_turtle in turtles:
            move = random.randint(0, 10)
            current_turtle.forward(move)

        xcor = current_turtle.xcor()
        if (xcor >= finishline):
            winner = True
            current_turtle.forward(0)
            turtle.forward(0)
            winner_color = current_turtle.color()
            print('The winner is', winner_color[1])


setup()
race()

turtle.mainloop()

Я пытался winner_color[0].

Ответы [ 2 ]

0 голосов
/ 07 июня 2018

Кажется, я мог найти ошибку в этом коде.

Я обнаружил, что с вашим кодом последнее строковое значение в списке turtle_color всегда побеждает.

Это из-за этой части вашего кода:

while not winner:
    for current_turtle in turtles:
        move = random.randint(0, 10)
        current_turtle.forward(move)

    xcor = current_turtle.xcor() #this should be indented, or itll only run this code
                                 #for the last color in the list, in this case, tan
    if (xcor >= finishline):     #and all of this code should be indented too
        winner = True            #so it checks all colors, not just tan
        current_turtle.forward(0)
        turtle.forward(0)
        winner_color = current_turtle.color()
        print('The winner is', winner_color[1])

Итак, правильный код (полностью):

import turtle
import random

turtles = []

def setup():
    global turtles
    startline = -610
    screen = turtle.Screen()
    screen.bgpic('pavement.gif')
    screen.setup(1290, 720)


    turtle_ycor = [-40, -20, 0, 20, 40]
    turtle_color = ['pink', 'skyblue', 'indigo', 'turquoise', 'tan']

    for i in range(0, len(turtle_ycor)):

        new_turtle = turtle.Turtle()
        new_turtle.shape('turtle')
        new_turtle.penup()
        new_turtle.setpos(startline, turtle_ycor[i])
        new_turtle.color(turtle_color[i])
        new_turtle.pendown()
        turtles.append(new_turtle)


def race():
    global turtles
    winner = False
    finishline = 550

    while not winner:
        for current_turtle in turtles:
            move = random.randint(0, 10)
            current_turtle.forward(move)
            xcor = current_turtle.xcor()
            if (xcor >= finishline):
                winner = True
                current_turtle.forward(0)
                turtle.forward(0)
                winner_color = current_turtle.color()
                print('The winner is', winner_color[1])


setup()
race()

Скажите, есть ли еще ошибки(и т.д.)!

0 голосов
/ 01 июня 2018

Вполне возможно, что победитель фактически «загорает» в конце каждой гонки.

Причиной этого может быть то, что random.seed еще не вызван.Следовательно, код будет инициализироваться одним и тем же начальным числом при каждом запуске, в результате чего одна и та же последовательность случайных чисел будет генерироваться каждый раз с одинаковым выигрышем в качестве результата.Вы можете увеличить рандомизацию, например, инициализируя начальное число перед каждым вызовом или только в верхней части кода.

Добавление этой строки:

random.seed()  # initializes seed using current system time

в любом месте кода должно рандомизировать результаты.

На заметку о зачитывании winner_color: Я предполагаю, что

winner_color = current_turtle.color()  # gets the color of the current turtle

теперь является строкой, содержащей цвет 'tan'.В этом случае индекс [0] будет работать со строкой, а не со списком.См., Например,

>>> a = 'tan'
>>> a[0]
't'
>>> a[1]
'a'
>>> a[2]
'n'
>>> a[:]
'tan'
>>> a[::-1]
'nat'

Кроме того, посмотрите, как представить ваш вопрос хорошим способом (текстовый редактор stackoverflow также показывает подсказки по стилю).Это повысит вероятность того, что на ваш вопрос ответят и изучат.

Добро пожаловать в stackoverflow, я надеялся, что это поможет вам заставить ваш код работать!

...