Bingo using python

Viewed 1534

So I currently have a code to produce a bingo card but I'm trying to figure out the code to change the values in the card to X's based on user input. I know to set up an input() segment, but I just can't figure out the code to confirm if the input is equal to a number on the card, and then how to change it if it is equal. Thank you and I attached my code below.

import random

random_draw_list = random.sample(range(1, 76), 75)

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 print_card(card):

    for letter in card:
        print(letter, end="\t")
        for number in card[letter]:
            print(number, end="\t")
        print("\n")
    print("\n")

def main():
    print("Let's play bingo!")
    card = generate_card()

    print("\nHere is your card:\n")
    print_card(card)
main()
1 Answers

First of all, it'd be way better if you made your card 5x5 numpy.array. Dictionary that you have has no practical purpose other than being easy way to print card. To check you just iterate over rows and if digit matches variable change the digit from the card to 0 also its a good idea to have free space marked and its value as 0 for the sake of having everything as an integer.

Now. After five iterations you must start checking card for bingo. This is where numpy.array gets handy. Idea is that you're counting how many zeroes are in every row, column and diagonal. If you have 5 zeros, its BINGO.

def IsBingo(card):
    for i in range (5):
        row_zeros=np.count_nonzero(card[i:,])
        col_zeros=np.count_nonzero(card[:,i])
        if not row_zeros or not col_zeros: #check if we have 0 non-zeros
            return (True)
    diagonal_zeros=np.count_nonzero(np.diag(card))
    diagonal1_zeros=np.count_nonzero(np.diag(np.fliplr(card)))
    if not diagonal_zeros or not diagonal1_zeros:
        return(True)
    return(False)

probably you can do it better with some linear algebra and make a code more optimal but this will work as intended to assuming you provide card as a 5x5 np.array with zeroes as selected numbers and 0 as "free space" in the center.

Now to check for the numbers its actually pretty easy

card = np.where(card == number_that_we_check, 0, card) # this will replace number in our card with zero if it matches

Thats it. You can wrap around a loop around the code above and after five iterations start checking for bingo.

Related