Python字典Bingo游戏。需要帮助检查垂直获胜

时间:2019-09-28 20:17:10

标签: python

我正在写Bingo游戏作为上课的功课。到目前为止,我为此感到非常自豪,但是并没有取得任何胜利。

以下是生成卡的代码:

def generate_card():
    card = {
        "B": [],
        "I": [],
        "N": [],
        "G": [],
        "O": [],
    }
    min = 1
    max = 15
    for letter in card:
        card[letter] = random.sample(range(min, max), 5)
        min += 15
        max += 15
        if letter == "N":
            card[letter][2] = "X" # free space!
    return card

这是检查获胜的方法:

def check_win(card):
    win = False
    if card["B"][0] == "X" and card["I"][1] == "X" and card["N"][2] == "X" and card["G"][3] == "X" and card["O"][4] == "X":
        win = True
    elif card["O"][0] == "X" and card["G"][1] == "X" and card["N"][2] == "X" and card["I"][3] == "X" and card["B"][4] == "X":
        win = True
    elif card["B"][0] == "X" and card["O"][4] == "X" and card["B"][4] == "X" and card["O"][0] == "X":
        win = True
    for letter in card:
        if(len(set(card[letter]))==1):
            win = True
    for letter in card:
        for number in letter:
            i = 0
            if card[letter][i] == "X":
                i += 1
        if i == 5:
            win == True
            break
    return win

它首先检查对角线胜利,然后检查四角胜利,然后检查水平胜利,最后检查垂直胜利。我刚刚进行了测试,看来检查垂直获胜的代码无法正常工作。我不知道为什么,但是我确实知道很难让我的大脑为它编写代码。任何帮助表示赞赏!

如果还有其他问题,请告诉我!我发现这很难测试。

2 个答案:

答案 0 :(得分:1)

也许是这样:

for i in range(5):
    cnt = 0
    for letter in card:
        if letter[i] == "X":
            cnt += 1
    if cnt == 5:
        win == True
        break

答案 1 :(得分:0)

我的代码中没有逻辑错误,而我却是一个简单的语法错误。在检查i是否等于5的if语句中,我有一个条件win == True,我应该将win设置为true:win = True