I'm trying to write a function in Python that simulates a horse race. While there's no winner, it clears the screen, shows the list of horses (all have index starting at zero). Then, on the line I've marked, the code messes up. I get the index error list out of range. I'm trying to randomly pick a horse (randomly pick an index number) and add 1 to the value. But I can't seem to figure it out!!
我正在尝试用Python编写一个模拟赛马的函数。虽然没有赢家,但它会清除屏幕,显示马匹列表(所有马匹的索引都从零开始)。然后,在我标记的行上,代码混乱了。我得到索引错误列表超出范围。我试图随机选择一匹马(随机选择一个索引号)并将值加1。但我似乎无法搞清楚!
while (no_winner):
os.system("cls")
print(horses)
# randomly assign a horse to step forward
rando = random.randint(1, HORSE_NUM)
horses[rando] += 1 #######PROBLEM
# if the horse exceeds the finish line, he wins
if (steps > FINISH_LINE):
winner = horses[index]
no_winner = False
1 个解决方案
#1
1
random.randint() is inclusive, so if you get a random integer that is equal to HORSE_NUM it will be out of bounds. try
random.randint()是包含的,所以如果你得到一个等于HORSE_NUM的随机整数,它将超出范围。尝试
rando = random.randint(0, HORSE_NUM - 1)
#1
1
random.randint() is inclusive, so if you get a random integer that is equal to HORSE_NUM it will be out of bounds. try
random.randint()是包含的,所以如果你得到一个等于HORSE_NUM的随机整数,它将超出范围。尝试
rando = random.randint(0, HORSE_NUM - 1)