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:
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.
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.
Below is the main code snippet I used to implement the game:
These are the problems that I encountered:
Case Sensitivity of User Input.
Invalid Input Handling.
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
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