Color Matching Game with Tkinter in Python

This article is about color matching game built using the Tkinter library in Python.

Overview of the game:

In this game, players have to enter the color of the text displayed not the actual text. For example, if the word  “red” is displayed in the color “blue” then the correct answer is “blue”. The player is given 30 seconds and the score increases on a correct answer and remains the same on a wrong answer.

Code implementation in Python:

Import required libraries:

import tkinter as tk
import random
from tkinter import messagebox

Initializing the game:

The __init__ method initializes the game by setting the score to 0 and the timer to 30 seconds. And sets the GUI elements.

def __init__(self):
    self.colors = ['Red', 'Blue', 'Green', 'Pink', 'Black', 'Yellow', 'Orange', 'White', 'Purple', 'Brown']
    self.score = 0
    self.time_remaining = 30
    self.color = random.choice(self.colors)
    self.text = random.choice(self.colors)
    
    self.root = tk.Tk()
    self.root.geometry("700x400")
    self.root.configure(bg='lightgrey')
    
    self.label_instruction = tk.Label(self.root, text="Enter the color that appears not the text color!", font=('Arial', 22), bg='lightgrey')
    self.label_instruction.pack(padx=10, pady=10)
    
    self.label_score = tk.Label(self.root, text="Score: " + str(self.score), font=('Arial', 20), bg='lightgrey')
    self.label_score.pack(padx=10, pady=10)
    
    self.label_timer = tk.Label(self.root, text="Time Remaining: " + str(self.time_remaining) + " Sec", font=('Arial', 18), bg='lightgrey')
    self.label_timer.pack(padx=10, pady=10)
    
    self.displaying_text = tk.Label(self.root, text=self.text, font=('Arial', 30), fg=self.color, bg='lightgrey')
    self.displaying_text.pack(padx=10, pady=10)
    
    self.textbox = tk.Entry(self.root, font=('Arial', 18), bg='white', fg='black', relief='solid', bd=2)
    self.textbox.pack(padx=10, pady=10)
    self.textbox.bind('<Return>', self.check_answer)
    
    self.replay_button = tk.Button(self.root, text="Play Again!", font=('Arial', 18), bg='white', fg='black', relief='solid', bd=2, command=self.replay_game)
    self.replay_button.pack(padx=10, pady=10)
    self.replay_button.pack_forget()
    
    self.update_timer()
    
    self.root.protocol('WM_DELETE_WINDOW', self.on_closing)
    self.root.mainloop()

Checking the answer:

This method is called whenever the player presses the enter key. It checks if the entered color matches the color of the displayed text. If it is correct then the score is updated else the score remains the same, in both cases new text with a new color is displayed.

def check_answer(self, event):
    answer = self.textbox.get().strip()
    if answer.lower() == self.color.lower():
        self.update_score()
    self.textbox.delete(0, tk.END)
    self.color = random.choice(self.colors)
    self.text = random.choice(self.colors)
    self.displaying_text.config(text=self.text, fg=self.color)

Updating the score:

This method updates the score and score label.

def update_score(self):
    self.score += 1
    self.label_score.config(text="Score: " + str(self.score))

Updating the timer:

This method decreases the remaining time by 1 second after each second. And if the timer reaches 0 it calls the end game method.

def update_timer(self):
    if self.time_remaining > 0:
        self.time_remaining -= 1
        self.label_timer.config(text="Time Remaining: " + str(self.time_remaining) + " Sec")
        self.root.after(1000, self.update_timer)
    else:
        self.end_game()

Ending the game:

This method disables the input, displays the final score, and displays the “Play Again!” button.

def end_game(self):
    self.label_instruction.config(text="Game Over! Your final score is: " + str(self.score))
    self.textbox.config(state='disabled')
    self.replay_button.pack()

Restarting the game:

If the player clicks the “Play Again!” button, the game restarts again by setting all the game variables to their initial values.

def replay_game(self):
    self.score = 0
    self.time_remaining = 30
    self.color = random.choice(self.colors)
    self.text = random.choice(self.colors)
    self.label_score.config(text="Score: " + str(self.score))
    self.label_timer.config(text="Time Remaining: " + str(self.time_remaining) + " Sec")
    self.displaying_text.config(text=self.text, fg=self.color)
    self.label_instruction.config(text="Enter the color that appears not the text color!")
    self.textbox.config(state='normal')
    self.replay_button.pack_forget()
    self.update_timer()

Closing the window:

After completion of the game when the user clicks on the close icon, this method displays a confirmation message box to close the window. If the user selects yes then the window will be closed.

def on_closing(self):
    if messagebox.askyesno(title="Quit?", message="Do you really want to quit?"):
        self.root.destroy()

Working demo of the game:

Leave a Reply

Your email address will not be published. Required fields are marked *