Bingo! Implementation in Python

BINGO!

Bingo is one of the most popular games played by almost every kid in school. It is even liked by adults as it is played in many community gatherings, parties, and so on. There are many variants of this game, and each person has his preferences to play this game. It is one of the easiest board games ever.

With new performant online casinos being launched every summer, we can already confidently say the remote gambling industries is one of the most influent one at the moment. However, the success of an independent online casino is dependent on having a highly-performing platform that customers can navigate. Developers are the leading specialists that offer players the opportunity to explore many reliable online casinos, as experts ensure the good functioning of the websites customers access.

Do check out other easy games in Python.

How Do We Play Bingo?

So as mentioned above, each player gets a game card that contains numbers spread randomly across the rows and columns. Each player gets to draw a number and mark down the number on his card. If any player gets all the numbers marked down in a row, a column, or even a diagonal, he wins. Let us see the possible chances of winning in Bingo.

Winning Possibilities in Bingo
Winning Possibilities in Bingo

In the above game card, any of the rows, columns, and both left and right diagonals are allowed. We can even include a free space in the grid.

Let us learn how to play this game using Python!

But before we get to coding, we need to ensure our system has Python.

We are going to use a Tkinter – a popular GUI-based framework to make our game interesting.

Pre-requisites

To be able to run the code, we need to have a Python version of 3.7 or Higher. Generally, Tkinter comes bundled with Python when you install it. In case you have missed the step for Tkinter installation, you can install it with the pip command in the terminal using the following command.

pip install tk

The Tkinter Library

The Tkinter library is mainly used for creating GUI-friendly and interactive applications. It is the most simple GUI framework and beginner friendly. It provides us with different widgets like buttons, canvases, grids, etc., for building the GUIs in Python.

There are many other articles written on our site on how to use Tkinter for many cool projects. Do check them out!

Bingo Game Implementation in Python

When you search for this topic on the Internet, most websites give you the basic implementation of this game. Tkinter or any other interactive framework is rarely used for this implementation which makes it an interesting approach.

In this approach, we are going to implement the traditional bingo game where there are two players with their respective game cards, and a number is called out, which is then checked in each of the player’s cards. If any player completes a row or a column, or a diagonal check, they win. The numbers in the cards must be unique, and the number drawn earlier should not be drawn in the future.

There are two players in this game – Player and Computer. Both these players have their respective cards that contain randomly placed numbers between 1 through 25. To incorporate fair play, the cards contain almost the same numbers spread out in different positions of the grid.

When a number is drawn, the number is looked for in both the player’s card and is crossed(X) automatically. This can be called a game of luck, and the player who completes any check will win.

There are a few important methods in this game. Let us discuss them in detail.

Bingo Class : This is the main class of the code, and all the other functions reside in this class.

start_game: This method, as the name suggests, is used to start the game.

create_game_window: The game window where the cards are displayed, and all the activity occurs is created using this method.

generate_grids: This method is used to create two separate game cards for the players.

draw_number: The number is drawn using this function.

mark_number: Once the number is drawn and if the number is present in the cards of the players, it should be crossed.

check_winner: Lastly, we have a function to check the winner based on the crossed cells of each game card.

Here is the complete code.

import random
import tkinter as tk
from tkinter import messagebox

class Bingo(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Bingo")
        self.geometry("800x800")
        self.resizable(0, 0)

        self.back = tk.Frame(master=self, bg='black', highlightbackground="green", highlightcolor="green", highlightthickness=1, bd=0)
        self.back.pack_propagate(0)
        self.back.pack(fill=tk.BOTH, expand=1)

        self.banner_label = tk.Label(master=self.back, text="\n\nBINGO!\n", bg="black", fg="green")
        self.banner_label.pack()

        self.start_button = tk.Button(master=self.back, text="Start Game", command=self.start_game)
        self.start_button.pack()

        self.game_window = None
        self.player_grid = []
        self.computer_grid = []
        self.draw_button = None

    def start_game(self):
        self.destroy()  
        self.create_game_window()
        self.generate_grids()

    def create_game_window(self):
        self.game_window = tk.Tk()
        self.game_window.title("Bingo")
        self.game_window.geometry("800x800")
        self.game_window.resizable(0, 0)

        self.game_frame = tk.Frame(master=self.game_window)
        self.game_frame.pack(fill=tk.BOTH, expand=1)

        self.player_label = tk.Label(master=self.game_frame, text="Player's Card")
        self.player_label.pack()

        self.player_grid_frame = tk.Frame(master=self.game_frame)
        self.player_grid_frame.pack()

        self.computer_label = tk.Label(master=self.game_frame, text="Computer's Card")
        self.computer_label.pack()

        self.computer_grid_frame = tk.Frame(master=self.game_frame)
        self.computer_grid_frame.pack()

        self.draw_button = tk.Button(master=self.game_frame, text="Draw A Number", command=self.draw_number)
        self.draw_button.pack()

    def generate_grids(self):
        self.player_grid = [[0] * 5 for _ in range(5)]
        self.computer_grid = [[0] * 5 for _ in range(5)]

        player_numbers = random.sample(range(1, 26), 25)
        computer_numbers = random.sample(range(1, 26), 25)

        for i in range(5):
            for j in range(5):
                player_number = player_numbers[i * 5 + j]
                computer_number = computer_numbers[i * 5 + j]

                self.player_grid[i][j] = player_number
                player_label = tk.Label(master=self.player_grid_frame, text=player_number, width=4, height=2, relief=tk.RAISED, bg="white")
                player_label.grid(row=i, column=j, padx=5, pady=5)

                self.computer_grid[i][j] = computer_number
                computer_label = tk.Label(master=self.computer_grid_frame, text=computer_number, width=4, height=2, relief=tk.RAISED, bg="white")
                computer_label.grid(row=i, column=j, padx=5, pady=5)

    def draw_number(self):
        available_numbers = [number for row in self.player_grid for number in row if number != "X"]
        if available_numbers:
            drawn_number = random.choice(available_numbers)
            messagebox.showinfo("Drawn Number", f"The drawn number is: {drawn_number}")
            self.mark_number(drawn_number)
            self.check_winner()
            self.computer_mark_number(drawn_number)
            self.check_winner()
        else:
            messagebox.showinfo("No Numbers", "No numbers left to draw.")

    def mark_number(self, number):
        for i in range(5):
            for j in range(5):
                if self.player_grid[i][j] == number:
                    self.player_grid[i][j] = "X"
                    player_label = tk.Label(master=self.player_grid_frame, text="X", width=4, height=2, relief=tk.RAISED, bg="white")
                    player_label.grid(row=i, column=j, padx=5, pady=5)
                    return

    def computer_mark_number(self, number):
        for i in range(5):
            for j in range(5):
                if self.computer_grid[i][j] == number:
                    self.computer_grid[i][j] = "X"
                    computer_label = tk.Label(master=self.computer_grid_frame, text="X", width=4, height=2, relief=tk.RAISED, bg="white")
                    computer_label.grid(row=i, column=j, padx=5, pady=5)
                    return

    def check_winner(self):
        for i in range(5):
            if all(self.player_grid[i][j] == "X" for j in range(5)):
                self.show_winner_message("Player")
                self.reset_game()
                return
        for j in range(5):
            if all(self.player_grid[i][j] == "X" for i in range(5)):
                self.show_winner_message("Player")
                self.reset_game()
                return
        if all(self.player_grid[i][i] == "X" for i in range(5)) or all(self.player_grid[i][4 - i] == "X" for i in range(5)):
            self.show_winner_message("Player")
            self.reset_game()
            return
        for i in range(5):
            if all(self.computer_grid[i][j] == "X" for j in range(5)):
                self.show_winner_message("Computer")
                self.reset_game()
                return

        for j in range(5):
            if all(self.computer_grid[i][j] == "X" for i in range(5)):
                self.show_winner_message("Computer")
                self.reset_game()
                return

        if all(self.computer_grid[i][i] == "X" for i in range(5)) or all(self.computer_grid[i][4 - i] == "X" for i in range(5)):
            self.show_winner_message("Computer")
            self.reset_game()
            return

    def show_winner_message(self, winner):
        messagebox.showinfo("Bingo", f"Congratulations! {winner} wins!")

    def reset_game(self):
        self.player_grid_frame.destroy()
        self.computer_grid_frame.destroy()
        self.draw_button.destroy()
        self.generate_grids()

if __name__ == "__main__":
    game = Bingo()
    game.mainloop()

Let us have a breakdown of the code. Firstly, we import the random module to draw random numbers and populate our game cards randomly. The Tkinter library is imported to create an interactive window. The messagebox component of the Tkinter library is used to display messages.

Lines 6-25 : In these lines, we create an instance of the Tkinter to generate a window, specify its size, set the title of the window, and also create a trigger. In line 19, we have a button called Start Game. When the user clicks on this button, another window pops up that contains the game cards.

The self keyword is used to access the methods and variables of the parent class.

To know more about this keyword, refer to this article.

Lines 26-30: Here, we are initializing the game and populating the game window.

Lines 32-54: In this section, we are displaying the game cards( 5×5 grids) for the players, naming them, and also enabling the Draw A Number button to draw a number randomly. All these elements are packed to keep them from dispositioning every time we run the code.

Lines 56-74: This code snippet is used to generate the game cards which have 25 random numbers in the range 1 to 26 spread out randomly. The extra number 26 is used to eliminate any out of index errors. We are defining the size of the grid, the size of the cells, and the color of the cells.

Lines 76-86: The draw_number method is used to draw random unique numbers for which we check the grids for any ‘x’ elements and eliminate them from the available_numbers list as they have been drawn already. We also check after each number generation for any winning condition. If we draw all the numbers and no winner is declared, a warning message is displayed.

Lines 88-104: In this snippet, we are marking the drawn number in the grid. We have separate functions for the player and the computer to mark the numbers automatically with an X.

Lines 106-136: This is the largest method in the code. We check for the winner in this snippet. As we know, there are three possibilities to win: A row, a column, or a diagonal completion of the grid. If any five numbers across these positions are crossed, the respective player is declared a winner. The same thing is done twice for both the Player and the Computer.

Lines 138-140: The winner declared in the earlier method has a congratulatory message displayed in the message box.

Lines 141-146: After the game is finished- if one player wins or if all the numbers are drawn, all the grids, buttons, and windows are destroyed.

Lines 147-149: This whole process resides under the main Game class which is under a loop.

How to Play?

It is a very simple game. All you have to do is run the code, click on the Start Game , and a window with the game cards opens. Just below the Computer’s card, you will find the Draw A Number button. Click on this button, and a little message box opens with a number. Click on Ok. As soon as you do this, notice the players’ grids. If the number is present in the cards, it is crossed. Repeat this process until one of the player wins.

Here is a demo of the game.

Bingo Game Demo

Note: The results of this game are not the same. That means, the Computer doesn’t always win! Also, there is no condition to check tie between the two players. If you are intrested to expand this game, you can add the tie condition, a few rewards and customize it according to you to make it more intresting.

Conclusion

We have come to the end of this game! To briefly discuss what we did, we discussed the Bingo game in general and the rules associated with it.

We have learned about the tool we are going to use, which is the Tkinter library. Tkinter is used to create GUI- friendly applications and games and comes bonded with Python. Following that, we discussed the game strategy, which involves creating two separate game cards for the players containing unique random numbers in a 5×5 grid. The numbers to call out are generated by a random number generator.

Then we took a look at the important building blocks of the code and discussed their purpose. We proceeded to understand the code in detail and also had a quick glimpse of how the game works.

Hope you had fun coding this game!

References

You can find more about the Tkinter library here.