功能和列表索引超出范围

时间:2016-09-17 22:08:39

标签: python

我正在为一个简单的yahtzee风格的骰子游戏上班,但我一直在遇到问题。就是现在我遇到了列表问题。我一直在

  File "C:/Users/u1069284/Desktop/HW3_LandonShoaf.py", line 90, in scoring
    counts[value] = counts[value] + 1

IndexError: list index out of range

当我运行我的程序时。我不确定请帮忙吗?

    from math import *
    from random import *
    global PlayerScore
    PlayerScore = 100

def firstroll():

    global dice
    dice = [0,0,0,0,0]
    print(dice)

    for Index in range(5):
            dice[Index] = randint(1,6)
    print(dice)
    return(dice)
def reroll():
    rerollstring = input("Which die/dice do you want to reroll?: ")
    print(rerollstring)

    rerolllist = rerollstring.split()

    print(rerolllist)

    for i in rerolllist:
        dice[int(i) - 1] = randint(1,6)
    print(dice)
    return(dice)
def scoring():

    global dice
    counts = [] * 7
    for value in dice:
        counts[value] = counts[value] + 1

    if 5 in counts:
        message = "Five Of A Kind! +30 Points!"
        score = 30
    elif 4 in counts:
        message = "Four Of A Kind! +25 Points!"
        score = 25
    elif (3 in counts) and (2 in counts):
        message = "FULL HOUSE! +15 Points!"
        score = 15
    elif 3 in counts:
        message = "Three Of A Kind! +10 Points!"
        score = 10
    elif counts.count(2) == 2:
        message = "Two Pairs! +5 Points"
        score = 5
    elif  not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
        message = "Straight! +20 Points!"
        score = 20
    else:
        message = "NO POINTS!"
        score = 0
    return(score)  
    print(message)
def PlayerScoring():
    PlayerScore == PlayerScore - 10
    PlayerScore == PlayerScore + score
    return(PlayerScore)
    print(PlayerScore)
def want2play():
    play = input("Play the dice game? (y for yes): ")

    return play
def main():
    while True:
        if int(PlayerScore) > 0:
            playround = want2play()
            if playround == 'y':
                firstroll()
                reroll()
                scoring()
                PlayerScoring()
            else:
                print("Game Over")
                break
        else:
            print("Your Are Out Of Points!")
            print("GAME OVER")
main()

2 个答案:

答案 0 :(得分:0)

试试这个:

counts = [0]*7
for value in dice:
    counts[value] += 1

答案 1 :(得分:0)

此:

counts = [] * 7
for value in dice:
    counts[value] = counts[value] + 1

初始化0值列表不是一种有效的方法,正如您所期望的那样。只需在翻译处打印[] * 7,您就会发现您的假设不正确。它产生一个空列表。我不知道是什么导致您相信您的代码会生成0的列表。

相反,请将counts = [] * 7替换为counts = [0 for _ in range(6)],然后请记住它是零索引的。这允许您避免列表中的冗余第一个元素。

counts = [0 for _ in range(6)]
for value in dice:
    counts[value-1] += 1