Я создаю игру, и в целом я новичок в 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
Что я делаю не так?