Python Project: Playing Snake-Water-Gun Game with Python.

Introduction:


This Snake-Water-Gun game project helped me practice logical thinking, conditional statements, and randomization in Python. In this article, I’ll share how I built the game, the challenges I faced, and their solutions.

These are the steps I took to grasp the concepts:


  1. The first step is to understand the rules as follows:

    • Snake (S) drinks Water (W): Snake wins.

    • Water (W) spoils Gun (G): Water wins.

    • Gun (G) shoots Snake (S): Gun wins.

    • If both players choose the same, it’s a draw.

  2. The Logic behind this Python Game:

    • The first step is to use the Python function random.choice() to let the computer randomly choose between snake, water, and gun.

    • To simplify input and output, create dictionaries to map characters ('s', 'w', 'g') to numerical values (1, -1, 0) and vice versa.

    • Using conditional statements (if, elif,else), We can compare the player's and computer's choices to determine the result.

  3. Below is the main code snippet I used to implement the game:

These are the problems that I encountered:


  1. Case Sensitivity of User Input.

  2. Invalid Input Handling.

  3. Handling Ties.

This is how I solved those problems:


1. Case Sensitivity of User Input:

Problem: Users might enter the characters in uppercase or mixed case (e.g., 'S' or 'G' instead of 's' or 'g').

Solution: Use you_string.lower() to convert user input to lowercase.

you = you_dict[you_string.lower()

2. Invalid Input Handling:

Problem: If the user enters anything other than 's', 'w', or 'g', the program will crash.

Solution: Add validation to ensure only valid inputs are accepted.

if you_string.lower() not in you_dict:
    print("Invalid input. Please enter 's', 'w', or 'g'.")
    exit()

3. Handling Ties:

Problem: The game might not handle ties correctly, leading to confusion or errors.

Solution: Ties are handled properly by displaying a clear message when both players choose the same option.

if computer == you:
    print("It's a Draw!")

Output when running in the terminal:


Enter the char: g  
Computer Chose: s  
You Chose: g  
You Win!

Resources:


My GitHub repository with the project code: GitHub Link

0
Subscribe to my newsletter

Read articles from Sheikh Abdul Wahid directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sheikh Abdul Wahid
Sheikh Abdul Wahid