Ошибка в питоне - не понимаю - PullRequest
2 голосов
/ 03 апреля 2010

Я создаю игру, и в целом я новичок в Python.

Я создал функцию descriptionGenerator (), которая генерирует описание для символов и объектов случайным образом или с использованием переданных ей переменных.

Казалось, что это работает, но время от времени это не будет работать правильно. Так что я поместил его в цикл, и кажется, что он никогда не сможет завершить цикл без одной из итераций, имеющих эту проблему.

Код выглядит следующим образом:

#+------------------------------------------+
#| Name: bitsandpieces.py       |
#| A module for the 'Europa I' game         |
#|  created for the Game Making Competition |
#|                                  |
#| Date Created/Modified:                   |
#|          3/4/10 | 3/4/10                 |
#+------------------------------------------+

# Import the required modules
    # Import system modules:
import time
import random
    # Import 3rd party modules:

    # Import game modules:
# Define the 'descriptionGenerator()' function
def descriptionGenerator(descriptionVariables):
    descriptionVariableSize = len(descriptionVariables)
    if descriptionVariables[0] == 'char':
        # If there is only one variable ('char'), create a random description
        if descriptionVariableSize == 1:
            # Define choices for descriptionVariables to be generated from
            gender_choices = ['male', 'female']
            hair_choices = ['black', 'red', 'blonde', 'grey', 'brown', 'blue']
            hair_choices2 = ['long', 'short', 'cropped', 'curly']
            size_choices = ['tubby', 'thin', 'fat', 'almost twig-like']
            demeanour_choices = ['glowering', 'bright', 'smiling', 'sombre', 'intelligent']
            impression_choices = ['likeable', 'unlikeable', 'dangerous', 'annoying', 'afraid']
            # Define description variables
            gender = random.choice(gender_choices)
            height = str(float('0.' + str(random.randint(1, 9))) + float(random.randint(1, 2)))
            if float(height) > 1.8:
                height_string = 'tall'
                if float(height) > 2:
                    height_string = 'very tall'
            elif float(height) < 1.8 and float(height) > 1.5:
                height_string = 'average'
            elif float(height) < 1.5:
                height_string = 'short'
                if float(height) < 1.3:
                    height_string = 'very short'
            hair = random.choice(hair_choices2) + ' ' + random.choice(hair_choices)
            size = random.choice(size_choices)
            demeanour = random.choice(demeanour_choices)
            impression = random.choice(impression_choices)
            # Collect description variables in list 'randomDescriptionVariables'
            randomDescriptionVariables = ['char', gender, height, height_string, hair, size, demeanour, impression]
            # Generate description using the 'descriptionGenerator' function
            descriptionGenerator(randomDescriptionVariables)
        # Generate the description of a character using the variables passed to the function
        elif descriptionVariableSize == 8:
            if descriptionVariables[1] == 'male':
                if descriptionVariables[7] != 'afraid':
                    print """A %s man, about %s m tall. He has %s hair and is %s. He is %s and you get the impression that he is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                elif descriptionVariables[7] == 'afraid':
                    print """A %s man, about %s m tall. He has %s hair and is %s. He is %s.\nYou feel that you should be %s of him.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
            elif descriptionVariables[1] == 'female':
                if descriptionVariables[7] != 'afraid':
                    print """A %s woman, about %s m tall. She has %s hair and is %s. She is %s and you get the impression that she is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                elif descriptionVariables[7] == 'afraid':
                    print """A %s woman, about %s m tall. She has %s hair and is %s. She is %s.\nYou feel that you should be %s of her.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
        else:
            pass
    elif descriptionVariables[0] == 'obj':
        # Insert code here 2 deal with object stuff
        pass

print
print
myDescriptionVariables = ['char']
i = 0
while i < 30:
    print
    print
    print
    descriptionGenerator(myDescriptionVariables)
    i = i + 1
time.sleep(10)

Когда он не работает должным образом, он говорит это:

Traceback (most recent call last):
  File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/Code/Code 2.0/bitsandpieces.py", line 79, in <module>
    descriptionGenerator(myDescriptionVariables)
  File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/Code/Code 2.0/bitsandpieces.py", line 50, in descriptionGenerator
    randomDescriptionVariables = ['char', gender, height, height_string, hair, size, demeanour, impression]
UnboundLocalError: local variable 'height_string' referenced before assignment

Спасибо за любую помощь с этим

----- EDIT -----

Спасибо за помощь, исправил эту проблему, но теперь есть еще одна!

Я изменил этот сегмент кода 2, взял строки как переменные, затем «возвратил» их, а затем протестировал:

        elif descriptionVariableSize == 8:
            if descriptionVariables[1] == 'male':
                if descriptionVariables[7] != 'afraid':
                    descriptionOutput = """A %s man, about %s m tall. He has %s hair and is %s. He is %s and you get the impression that he is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                    return descriptionOutput
                elif descriptionVariables[7] == 'afraid':
                    descriptionOutput = """A %s man, about %s m tall. He has %s hair and is %s. He is %s.\nYou feel that you should be %s of him.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                    return descriptionOutput
            elif descriptionVariables[1] == 'female':
                if descriptionVariables[7] != 'afraid':
                    descriptionOutput = """A %s woman, about %s m tall. She has %s hair and is %s. She is %s and you get the impression that she is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                    return descriptionOutput
                elif descriptionVariables[7] == 'afraid':
                    descriptionOutput = """A %s woman, about %s m tall. She has %s hair and is %s. She is %s.\nYou feel that you should be %s of her.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7])
                    return descriptionOutput
        else:
            print 'Incorrect number of variables contained within \'descriptionVariables\''
    elif descriptionVariables[0] == 'obj':
        # Insert code here 2 deal with object stuff
        pass

myDescriptionVariables = ['char']
myOutput = descriptionGenerator(myDescriptionVariables)
print myOutput

Однако, когда я запускаю это, он выдает следующий вывод:

None

Что я делаю не так?

Ответы [ 2 ]

3 голосов
/ 03 апреля 2010

Вы определяете height_string внутри операторов if / else:

if float(height) > 1.8:
    height_string = 'tall'
    if float(height) > 2:
        height_string = 'very tall'
elif float(height) < 1.8 and float(height) > 1.5:
    height_string = 'average'
elif float(height) < 1.5:
    height_string = 'short'
    if float(height) < 1.3:
        height_string = 'very short'

Однако, если высота == 1,8 или высота == 1,5, все операторы if / elif являются ложными, и поэтому высота_строки никогда не определяется. Просто измените второе утверждение, чтобы вместо него были знаки <= и> =:

elif float(height) <= 1.8 and float(height) >= 1.5:

В ответ на ваши изменения:

Вы вызываете функцию с помощью

myOutput = descriptionGenerator(["char"])

Обратите внимание, что вы передаете список длины один. Следовательно, ваша функция видит descriptionVariableSize == 1 и создает случайное описание.

Пока все хорошо.

Но подождите! В конце этого оператора if у вас есть elif:

elif descriptionVariableSize == 8:

Теперь у вас есть descriptionVariableSize == 8. Однако вы использовали elif - поэтому вы просто потратили все это время на создание случайного набора описаний, но вам никогда не удастся его использовать, потому что первое утверждение было истинным, а это утверждение выполняется только в том случае, если первое утверждение было ложным.

Решение - просто измените это elif на if. Теперь, если вы передадите полный оператор или сгенерируете его в функции, вы все равно перейдете ко второму разделу.

Редактировать ... пятое?

Я не заметил, что вы снова вызываете функцию в конце случайного раздела. Обратите внимание, что вы не return этот вызов - так что все возвращенное теряется в пустоте. Просто измените его на

 return descriptionGenerator(randomDescriptionVariables)

Как добавленное примечание - ваша функция становится немного громоздкой. Проблема в том, что вы делаете две совершенно разные вещи в функции - один генерирует случайный список качеств, а другой генерирует описание из этих качеств. Может быть лучше переместить материал из первого блока if в его собственную функцию, generateRandomDescription() или что-то, что вызывается только в этом первом блоке if.

2 голосов
/ 03 апреля 2010

Пока вы проверяете, является ли height больше или меньше 1,5 или 1,8, у вас ничего нет, если оно равно одному из этих значений. Измените сравнения вокруг этих точек либо на >= и <, либо на > и <=.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...