How to Build a Snake Water Gun Game Using Python Tkinter

How to Build a Snake Water Gun Game Using Python Tkinter Thumbnail

How to Build a Snake Water Gun Game Using Python Tkinter (Complete GUI Project)

Python is a great programming language for beginners because it allows us to turn simple programming concepts into practical applications. One interesting way to learn Python is by creating small games.

In this tutorial, we are going to build a Snake Water Gun Game using Python Tkinter. Instead of creating an ordinary command-line game, we will develop a desktop application with a modern gaming interface, interactive buttons, a live scoreboard, and animated computer selection.

The game will allow players to compete against the computer. You will select Snake, Water, or Gun, and the computer will automatically choose its option. Python will then compare both choices and display the result.

This project is suitable for beginners who want to understand Python GUI development while building something practical.

What We Will Build

Our final application will have a dark gaming interface with colorful selection cards, a scoreboard, and a battle section that displays both the player's and computer's choices.

  • Modern dark gaming interface.
  • Interactive Snake, Water, and Gun buttons.
  • Player versus computer gameplay.
  • Animated computer selection countdown.
  • Live player and computer scores.
  • Draw counter and round tracking.
  • Win, lose, and draw result messages.
  • New Game button to reset the scoreboard.
  • Hover effects on interactive buttons.

1. Understanding the Snake Water Gun Game

Before writing the code, let's understand the rules.

The game has three possible choices:

  • Snake: Snake defeats Water.
  • Water:Water defeats Gun.
  • Gun:Gun defeats Snake.

If the player and computer select the same option, the round ends in a draw.

Here is the complete winning logic:

Player ChoiceComputer ChoiceResult
SnakeWaterPlayer Wins
WaterGunPlayer Wins
GunSnakePlayer Wins
SnakeGunComputer Wins
WaterSnakeComputer Wins
GunWaterComputer Wins
Same ChoiceSame ChoiceDraw

2. Requirements for This Python Project

We will use Python and its built-in Tkinter library. Tkinter provides the widgets required to create desktop applications, including buttons, labels, frames, and windows.

Requirements:
  • Python 3 installed on your computer.
  • Visual Studio Code or another Python editor.
  • Tkinter library.
  • Basic understanding of Python variables and conditions.

We don't need any external Python packages for this project. Tkinter is included with many standard Python installations.

Check Python Installation

Open your terminal and execute:

python --version

To check whether Tkinter is available, run:

python -m tkinter

If a small Tkinter window opens, your installation is ready.

3. Create the Project File

Open Visual Studio Code and create a new Python file named:

snake_water_gun_pro.py

We will write the complete application in this single file. This makes the project easier to understand and run for beginners.

4. Complete Python Source Code

Copy the complete code below into snake_water_gun_pro.py.

The application uses Tkinter for the interface, the random module for the computer's choice, and the after() method to create a simple animated countdown without blocking the interface.

import tkinter as tk
import random


class SnakeWaterGunPro:

    def __init__(self, root):

        self.root = root
        self.root.title("SNAKE WATER GUN | PRO")
        self.root.geometry("1000x760")
        self.root.minsize(850, 680)
        self.root.configure(bg="#090E1B")

        # Game data
        self.choices = ["Snake", "Water", "Gun"]

        self.icons = {
            "Snake": "🐍",
            "Water": "💧",
            "Gun": "🔫"
        }

        self.player_score = 0
        self.computer_score = 0
        self.draws = 0
        self.rounds = 0
        self.streak = 0
        self.best_streak = 0
        self.busy = False
        self.after_id = None

        # Colors
        self.bg = "#090E1B"
        self.panel = "#121B2E"
        self.card = "#19243A"
        self.cyan = "#42D9F5"
        self.purple = "#A78BFA"
        self.green = "#52E0A0"
        self.red = "#FF647C"
        self.white = "#F4F7FF"
        self.muted = "#8996AD"

        self.create_ui()
        self.update_scores()

    # UI HELPERS

    def make_label(self, parent, text, size=12,
                   color=None, weight="normal"):

        return tk.Label(
            parent,
            text=text,
            font=("Segoe UI", size, weight),
            bg=parent.cget("bg"),
            fg=color or self.white
        )

    def create_ui(self):

        main = tk.Frame(self.root, bg=self.bg)
        main.pack(fill="both", expand=True, padx=35, pady=22)

        # HEADER

        header = tk.Frame(main, bg=self.bg)
        header.pack(fill="x")

        tk.Label(
            header,
            text="⚡  ARCADE ARENA",
            font=("Segoe UI", 12, "bold"),
            bg=self.bg,
            fg=self.cyan
        ).pack(anchor="w")

        tk.Label(
            header,
            text="SNAKE WATER GUN",
            font=("Segoe UI", 29, "bold"),
            bg=self.bg,
            fg=self.white
        ).pack(anchor="w", pady=(5, 0))

        tk.Label(
            header,
            text="CHALLENGE THE COMPUTER • TEST YOUR STRATEGY",
            font=("Segoe UI", 9, "bold"),
            bg=self.bg,
            fg=self.muted
        ).pack(anchor="w", pady=(3, 18))

        # SCOREBOARD

        scoreboard = tk.Frame(main, bg=self.panel)
        scoreboard.pack(fill="x", pady=(0, 18))

        for column in range(3):
            scoreboard.grid_columnconfigure(column, weight=1)

        self.player_score_label = self.make_stat(
            scoreboard, "YOUR SCORE", "0", self.cyan, 0
        )

        self.computer_score_label = self.make_stat(
            scoreboard, "COMPUTER", "0", self.purple, 1
        )

        self.draw_label = self.make_stat(
            scoreboard, "DRAWS", "0", self.green, 2
        )

        # GAME PANEL

        game_panel = tk.Frame(
            main,
            bg=self.panel,
            padx=22,
            pady=20
        )
        game_panel.pack(fill="both", expand=True)

        self.make_label(
            game_panel,
            "CHOOSE YOUR WEAPON",
            15,
            self.white,
            "bold"
        ).pack(anchor="w")

        self.make_label(
            game_panel,
            "Select one option to start the battle",
            10,
            self.muted
        ).pack(anchor="w", pady=(4, 18))

        # CHOICE CARDS

        cards = tk.Frame(game_panel, bg=self.panel)
        cards.pack(fill="x")

        for column in range(3):
            cards.grid_columnconfigure(column, weight=1)

        self.choice_buttons = {}

        card_data = [
            ("Snake", "🐍", "BEATS WATER", self.green),
            ("Water", "💧", "BEATS GUN", self.cyan),
            ("Gun", "🔫", "BEATS SNAKE", self.purple)
        ]

        for index, (name, icon, description, color) in enumerate(card_data):

            card = tk.Frame(
                cards,
                bg=self.card,
                padx=8,
                pady=17,
                highlightthickness=1,
                highlightbackground="#293752"
            )

            card.grid(
                row=0,
                column=index,
                padx=7,
                sticky="nsew"
            )

            tk.Label(
                card,
                text=icon,
                font=("Segoe UI Emoji", 35),
                bg=self.card,
                fg=self.white
            ).pack(pady=(2, 8))

            tk.Label(
                card,
                text=name.upper(),
                font=("Segoe UI", 12, "bold"),
                bg=self.card,
                fg=self.white
            ).pack()

            tk.Label(
                card,
                text=description,
                font=("Segoe UI", 8, "bold"),
                bg=self.card,
                fg=color
            ).pack(pady=(5, 12))

            button = tk.Button(
                card,
                text="SELECT",
                font=("Segoe UI", 9, "bold"),
                bg=color,
                fg="#09101D",
                activebackground=self.white,
                activeforeground="#09101D",
                relief="flat",
                cursor="hand2",
                bd=0,
                pady=9,
                command=lambda choice=name: self.play(choice)
            )

            button.pack(fill="x", padx=4)

            self.choice_buttons[name] = button

            self.add_hover(button, color)

        # BATTLE AREA

        battle = tk.Frame(
            game_panel,
            bg="#0D1527",
            padx=15,
            pady=15
        )
        battle.pack(fill="x", pady=20)

        for column in range(3):
            battle.grid_columnconfigure(column, weight=1)

        self.make_label(
            battle, "YOU", 9, self.cyan, "bold"
        ).grid(row=0, column=0)

        self.make_label(
            battle, "VS", 12, self.purple, "bold"
        ).grid(row=0, column=1)

        self.make_label(
            battle, "COMPUTER", 9, self.purple, "bold"
        ).grid(row=0, column=2)

        self.player_choice_label = tk.Label(
            battle,
            text="❔",
            font=("Segoe UI Emoji", 34),
            bg="#0D1527",
            fg=self.white
        )
        self.player_choice_label.grid(row=1, column=0, pady=8)

        self.computer_choice_label = tk.Label(
            battle,
            text="❔",
            font=("Segoe UI Emoji", 34),
            bg="#0D1527",
            fg=self.white
        )
        self.computer_choice_label.grid(row=1, column=2, pady=8)

        self.make_label(
            battle, "VS", 16, self.muted, "bold"
        ).grid(row=1, column=1)

        self.player_name = self.make_label(
            battle, "Waiting...", 9, self.muted
        )
        self.player_name.grid(row=2, column=0)

        self.computer_name = self.make_label(
            battle, "Waiting...", 9, self.muted
        )
        self.computer_name.grid(row=2, column=2)

        # RESULT

        self.result_label = tk.Label(
            game_panel,
            text="READY FOR BATTLE?",
            font=("Segoe UI", 17, "bold"),
            bg=self.panel,
            fg=self.cyan
        )
        self.result_label.pack(pady=(0, 5))

        self.message_label = tk.Label(
            game_panel,
            text="Choose Snake, Water or Gun to begin.",
            font=("Segoe UI", 10),
            bg=self.panel,
            fg=self.muted
        )
        self.message_label.pack(pady=(0, 12))

        # ROUND INFORMATION

        info = tk.Frame(game_panel, bg=self.panel)
        info.pack(fill="x")

        self.round_label = self.make_label(
            info, "ROUND 0", 9, self.muted, "bold"
        )
        self.round_label.pack(side="left")

        self.streak_label = self.make_label(
            info, "WIN STREAK: 0", 9, self.green, "bold"
        )
        self.streak_label.pack(side="right")

        # FOOTER

        footer = tk.Frame(main, bg=self.bg)
        footer.pack(fill="x", pady=(16, 0))

        self.reset_button = tk.Button(
            footer,
            text="↻  NEW GAME",
            font=("Segoe UI", 10, "bold"),
            bg="#263550",
            fg=self.white,
            activebackground="#354866",
            activeforeground=self.white,
            relief="flat",
            cursor="hand2",
            bd=0,
            padx=20,
            pady=12,
            command=self.new_game
        )
        self.reset_button.pack(side="left")

        tk.Label(
            footer,
            text="PYTHON EDITION  •  v1.0",
            font=("Segoe UI", 8, "bold"),
            bg=self.bg,
            fg="#64738C"
        ).pack(side="right", pady=12)

    # SCOREBOARD

    def make_stat(self, parent, title, value, color, column):

        box = tk.Frame(
            parent,
            bg=self.panel,
            padx=8,
            pady=14
        )

        box.grid(row=0, column=column, sticky="nsew")

        tk.Label(
            box,
            text=title,
            font=("Segoe UI", 9, "bold"),
            bg=self.panel,
            fg=self.muted
        ).pack()

        label = tk.Label(
            box,
            text=value,
            font=("Segoe UI", 23, "bold"),
            bg=self.panel,
            fg=color
        )
        label.pack(pady=(3, 0))

        return label

    def update_scores(self):

        self.player_score_label.config(
            text=str(self.player_score)
        )

        self.computer_score_label.config(
            text=str(self.computer_score)
        )

        self.draw_label.config(
            text=str(self.draws)
        )

        self.round_label.config(
            text=f"ROUND {self.rounds}"
        )

        self.streak_label.config(
            text=f"WIN STREAK: {self.streak}  |  BEST: {self.best_streak}"
        )

    # BUTTON HOVER EFFECT

    def add_hover(self, button, color):

        button.bind(
            "<Enter>",
            lambda event: button.config(bg=self.white)
        )

        button.bind(
            "<Leave>",
            lambda event: button.config(bg=color)
        )

    # GAME LOGIC

    def play(self, player):

        if self.busy:
            return

        self.busy = True

        for button in self.choice_buttons.values():
            button.config(state="disabled")

        self.player_choice_label.config(
            text=self.icons[player]
        )

        self.computer_choice_label.config(text="❔")

        self.player_name.config(text=player.upper())

        self.computer_name.config(text="Choosing...")

        self.result_label.config(
            text="BATTLE STARTING...",
            fg=self.cyan
        )

        self.message_label.config(
            text="Computer is selecting its weapon...",
            fg=self.muted
        )

        self.countdown = 3
        self.pending_player = player
        self.countdown_step()

    def countdown_step(self):

        if self.countdown> 0:

            self.result_label.config(
                text=str(self.countdown),
                fg=self.cyan
            )

            self.countdown -= 1

            self.after_id = self.root.after(
                550, self.countdown_step
            )

        else:

            self.after_id = self.root.after(
                400,
                self.finish_round
            )

    def finish_round(self):

        self.after_id = None

        player = self.pending_player
        computer = random.choice(self.choices)

        self.computer_choice_label.config(
            text=self.icons[computer]
        )

        self.computer_name.config(
            text=computer.upper()
        )

        self.rounds += 1

        if player == computer:

            self.draws += 1
            self.streak = 0

            result = "IT'S A DRAW!"
            message = "Both selected the same weapon."
            color = self.cyan

        elif (
            (player == "Snake" and computer == "Water")
            or (player == "Water" and computer == "Gun")
            or (player == "Gun" and computer == "Snake")
        ):

            self.player_score += 1
            self.streak += 1

            self.best_streak = max(
                self.best_streak,
                self.streak
            )

            result = "VICTORY!"
            message = "Excellent move! You won this round."
            color = self.green

        else:

            self.computer_score += 1
            self.streak = 0

            result = "DEFEAT!"
            message = "Computer won this round. Try again!"
            color = self.red

        self.result_label.config(
            text=result,
            fg=color
        )

        self.message_label.config(
            text=message,
            fg=self.white
        )

        self.update_scores()

        self.busy = False

        for button in self.choice_buttons.values():
            button.config(state="normal")

    # RESET GAME

    def new_game(self):

        if self.after_id is not None:

            self.root.after_cancel(self.after_id)
            self.after_id = None

        self.player_score = 0
        self.computer_score = 0
        self.draws = 0
        self.rounds = 0
        self.streak = 0
        self.best_streak = 0
        self.busy = False

        for button in self.choice_buttons.values():
            button.config(state="normal")

        self.player_choice_label.config(text="❔")
        self.computer_choice_label.config(text="❔")

        self.player_name.config(text="Waiting...")
        self.computer_name.config(text="Waiting...")

        self.result_label.config(
            text="READY FOR BATTLE?",
            fg=self.cyan
        )

        self.message_label.config(
            text="Choose Snake, Water or Gun to begin.",
            fg=self.muted
        )

        self.update_scores()


# RUN GAME

if __name__ == "__main__":

    root = tk.Tk()

    game = SnakeWaterGunPro(root)

    root.mainloop()
Snake Water Gun Game Using Python Tkinter Screenshot 1

Snake Water Gun Game Using Python Tkinter Screenshot 2


5. Understanding the Python Code

Now that we have the complete source code, let's understand the important parts. You don't need to memorize everything. Focus on understanding how each part contributes to the game.

Step 1: Import Required Modules

import tkinter as tk
import random

We import two Python modules.

  • tkinter:Used to create the desktop application and its graphical components.
  • random: Used to generate the computer's random choice.

The as tk part gives Tkinter a shorter name, allowing us to write tk.Label() instead of tkinter.Label().

Step 2: Create a Python Class

class SnakeWaterGunPro:

    def __init__(self, root):
        self.root = root

We use a class to organize the game's interface, data, and functions in one place.

The __init_ _() method runs automatically when we create an object of the class. It initializes the application and prepares the game data.

Step 3: Create Game Variables

self.player_score = 0
self.computer_score = 0
self.draws = 0
self.rounds = 0

These variables store the current game statistics.

Whenever the player wins, the player score increases. When the computer wins, its score increases. A draw increases the draw counter.

Step 4: Store the Available Choices

self.choices = ["Snake", "Water", "Gun"]

self.icons = {
    "Snake": "🐍",
    "Water": "💧",
    "Gun": "🔫"
}
We use a list to store the available choices and a dictionary to associate each choice with an emoji.

This makes it easier to display the selected option in the battle section.

Step 5: Design the Main Window

self.root.geometry("1000x760")
self.root.minsize(850, 680)
self.root.configure(bg="#090E1B")

The geometry() method sets the initial window dimensions to 1000 by 760 pixels.

The minsize() method prevents the user from shrinking the window below the specified dimensions.

We also use a dark background color to create a gaming-style appearance.

Step 6: Create Interface Components

Tkinter provides several widgets for building graphical applications.

WidgetPurpose
FrameGroups related interface components.
LabelDisplays text, icons, and scores.
ButtonAllows the player to interact with the game.
TkCreates the main application window.

For example:

tk.Button(
    card,
    text="SELECT",
    command=lambda choice=name: self.play(choice)
)

This creates a button. When the player clicks it, the selected option is passed to the play() method.

Step 7: Add Button Hover Effects

button.bind(
    "<Enter>",
    lambda event: button.config(bg=self.white)
)

button.bind(
    "<Leave>",
    lambda event: button.config(bg=color)
)

The bind() method connects mouse events to a button.

  • <Enter> runs when the mouse pointer enters the button.
  • <Leave> runs when the pointer moves away.

We change the button background color to provide a simple hover effect.

Step 8: Generate the Computer's Choice

computer = random.choice(self.choices)

The random.choice() function selects one item from the choices list.

For example, the computer might select Snake, Water, or Gun. Every valid choice has an equal chance of being selected.

Step 9: Determine the Winner

if player == computer:
    print("Draw")

elif (
    (player == "Snake" and computer == "Water")
    or (player == "Water" and computer == "Gun")
    or (player == "Gun" and computer == "Snake")
):
    print("Player Wins")

else:
    print("Computer Wins")

This is the main game logic.

First, Python checks whether both players selected the same option. If not, it checks the three winning combinations. If none of those conditions is true, the computer wins.

Step 10: Create an Animated Countdown

self.after_id = self.root.after(
    550, self.countdown_step
)

Tkinter's after() method schedules a function to run after a specified number of milliseconds.

We use this method to display a countdown before revealing the computer's choice. Unlike time.sleep(), this approach does not freeze the interface while waiting.

Step 11: Update the Scoreboard

self.player_score += 1
self.update_scores()

When the player wins, the score increases by one. The update_scores() method then refreshes the scoreboard labels.

The same method updates the computer score, draw count, round number, and winning streak.

Step 12: Reset the Game

def new_game(self):

    self.player_score = 0
    self.computer_score = 0
    self.draws = 0
    self.rounds = 0

The New Game button resets the game statistics and restores the initial interface.

6. How to Run the Game

After saving the file, follow these steps:

  1. Open Visual Studio Code.
  2. Open the folder containing your Python project.
  3. Open snake_water_gun_pro.py.
  4. Open the integrated terminal.
  5. Execute the following command.
python snake_water_gun_pro.py

Your desktop game window should open. Select any of the three choices to start playing against the computer.

7. Understanding the Game Controls

ControlAction
SnakeSelect Snake.
WaterSelect Water.
GunSelect Gun.
New GameReset all current game statistics.
Window Close\Exit the application.

8. Common Errors and Solutions

Error 1: No module named tkinter

This error means Tkinter is not available in your Python installation.

On Ubuntu or Debian-based Linux distributions, you can install it using:

sudo apt install python3-tk

On Windows, check that your Python installation includes the Tcl Tk support component. You may need to modify or reinstall Python with that component enabled.

Error 2: Emoji icons are not displaying correctly

Emoji appearance depends on the operating system and installed fonts. If an emoji is missing, replace it with a simple text label or use custom image assets.

Error 3: The game window is too small

The application has a minimum window size of 850 by 680 pixels. If your screen is smaller, you may need to reduce the window dimensions and adjust the padding and font sizes.

9. Practice Exercises

Now it's time to improve the project. Try completing these challenges yourself.

  1. Add a player name field.
  2. Create Easy, Medium, and Hard difficulty settings.
  3. Add a sound toggle button.
  4. Save the best score using a JSON file.
  5. Add a First to 5 tournament mode.
  6. Create a separate game history panel.
  7. Replace emojis with custom graphical illustrations.

These exercises will help you understand Python classes, functions, event handling, file operations, and GUI development.

10. What Can We Improve Next?

This is the first version of our Snake Water Gun desktop game. Although it already includes an interactive interface and scoreboard, there are many ways to improve it further.

For example, we can use Tkinter Canvas to draw custom game graphics, add particle effects, create animated backgrounds, and introduce sound effects.

We can also use JSON or SQLite to save player statistics between sessions.

Conclusion

In this tutorial, we built a Snake Water Gun game using Python and Tkinter. We started with the basic game rules and then created a desktop interface with interactive buttons, a scoreboard, computer selection, and result messages.

The most useful part of this project is that it combines several Python concepts in one practical application. Instead of learning individual concepts without context, you can see how variables, conditions, functions, classes, and event handling work together.

If you are learning Python, try modifying the game and adding your own features. Small projects like this are an excellent way to improve your programming skills.

Frequently Asked Questions

Can beginners build a Snake Water Gun game in Python?

Yes. Beginners can build this game after learning basic Python concepts such as variables, lists, conditions, functions, and loops.

Does this project require external libraries?

No. The project uses Python's built-in Tkinter and random modules. No third-party package is required.

Can I run this game in Visual Studio Code?

Yes. You can write and execute the Python file in Visual Studio Code as long as Python and Tkinter are installed correctly.

Can I convert this Python game into an EXE file?

Yes. You can use PyInstaller to package the application as a Windows executable. This is an additional step and is not required to run the source code.

What should I learn after completing this project?

Try building a Hangman game, a Tic Tac Toe game, a calculator, or a graphical quiz application using Tkinter.

Previous Post Next Post