def ensure_data_directory():
"""Ensure the data directory exists."""
if not os.path.exists('data'):
os.makedirs('data')
def load_user_data():
"""Load user data from a file."""
if not os.path.exists(USER_DATA_FILE):
return {}
code
with open(USER_DATA_FILE, 'r') as file:
user_data = {}
for line in file:
username = line.strip()
user_data[username] = True # Using a dictionary to track registered users
return user_data
def register_user(username):
"""Register a new user."""
with open(USER_DATA_FILE, 'a') as file:
file.write(username + '\n')
def user_login():
"""Handle user login or registration."""
user_data = load_user_data()
code
while True:
try:
print("Login (l) or Register (r): ", end='', flush=True)
choice = sys.stdin.readline().strip().lower() # Using sys.stdin.readline()
print("Enter your username: ", end='', flush=True)
username = sys.stdin.readline().strip() # Using sys.stdin.readline()
if choice == 'l':
if username in user_data:
print(f"Welcome back, {username}!")
return username
else:
print("Username does not exist. Please register.")
elif choice == 'r':
if username not in user_data:
register_user(username)
print(f"User {username} registered successfully!")
return username
else:
print("Username already exists. Please choose a different one.")
else:
print("Invalid choice. Please enter 'l' for Login or 'r' for Register.")
except EOFError:
print("\nInput error: Please ensure you're running this in an interactive console.")
break
except KeyboardInterrupt:
print("\nInput interrupted. Exiting user login.")
break
except Exception as e:
print(f"An error occurred: {e}")
break
def load_high_scores():
"""Load high scores from a file."""
if not os.path.exists(HIGH_SCORES_FILE):
return {}
code
with open(HIGH_SCORES_FILE, 'r') as file:
high_scores = {}
for line in file:
difficulty, name, score = line.strip().split(',')
high_scores[difficulty] = (name, int(score))
return high_scores
def save_high_score(name, score, difficulty):
"""Save player's name and score to a file."""
ensure_data_directory() # Ensure data directory exists
with open(HIGH_SCORES_FILE, 'a') as file:
file.write(f"{difficulty},{name},{score}\n")
def get_word(difficulty):
"""Select a random word from a given difficulty level."""
return random.choice(DIFFICULTY_WORDS[difficulty])
def display_progress(selected_word, guessed_letters):
"""Display the current state of the guessed word."""
display_word = ''
for letter in selected_word:
if letter in guessed_letters:
display_word += letter + ' '
else:
display_word += '_ '
print("\nCurrent word:", display_word.strip())
def guess_the_word(username):
"""Guess the word game."""
while True: # Loop for playing the game until user decides to exit
print("Welcome to 'Guess the Word'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty] # Set tries based on selected difficulty
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1 # Deduct one attempt for incorrect guess
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!") # Show word on win
break
if remaining_tries <= 0:
print(f"Game over! The correct word was '{selected_word}'.") # Show correct word on loss
score = 0 # Zero score if they fail to guess
save_high_score(username, score, difficulty)
# Asking the player if they want to play again
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break # Exit the loop to stop the game
def display_shark(shark):
"""Display the shark's position."""
print("Shark's position:", shark)
def beat_the_shark(username):
"""A simple race game where player guesses letters and compares to a shark opponent."""
while True: # Loop for playing the game until user decides to exit
print("\nWelcome to 'Beat the Shark'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty] # Set tries based on selected difficulty
# Initialize shark string based on difficulty
if difficulty == 'easy':
shark = "﹏﹏﹏𓂁" # 3 underscores for easy
elif difficulty == 'medium':
shark = "﹏﹏﹏﹏﹏𓂁" # 5 underscores for medium
else:
shark = "﹏﹏﹏﹏﹏﹏﹏﹏𓂁" # 7 underscores for hard
# Display initial shark position
display_shark(shark)
while remaining_tries > 0: # The loop continues as long as there are remaining tries
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess! The shark is still behind!")
else:
remaining_tries -= 1 # Deduct one attempt for incorrect guess
score -= 10
print("Wrong guess! -10 points. The shark moves forward!")
# Remove one '﹏' from the shark to show it moving closer
shark = shark[:-1] # Slice off the last character
if len(shark) <= 1: # If we only have the shark emoji left
shark = '𓂁' # Replace with only the shark emoji
# Display updated shark position
display_shark(shark)
# If the player successfully guesses all letters in the word, they win
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! The shark couldn't catch you!") # Show word on win
break
# If player runs out of tries, the shark catches them
if remaining_tries <= 0:
print(f"The shark caught you! Game over! The correct word was '{selected_word}'.") # Show correct word on loss
score = 0 # Score is zero if caught
save_high_score(username, score, difficulty)
# Asking the player if they want to play again
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break # Exit the loop to stop the game
def timed_guess_the_word(username):
"""Timed Guess the Word game."""
while True: # Loop for playing the game until user decides to exit
print("Welcome to 'Timed Guess the Word'!")
print("You have infinite guesses but must guess the word within the time limit.")
code
# Select time limit
while True:
print("Choose a time limit:")
print("1. 30 seconds")
print("2. 1 minute (60 seconds)")
print("3. 1 minute and 30 seconds (90 seconds)")
time_choice = input("Select a time limit (1, 2, 3): ").strip()
if time_choice == '1':
timer_duration = 30
break
elif time_choice == '2':
timer_duration = 60
break
elif time_choice == '3':
timer_duration = 90
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
start_time = time.time() # Start the timer
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
elapsed_time = time.time() - start_time # Calculate elapsed time
remaining_time = max(0, timer_duration - elapsed_time) # Calculate remaining time (cannot be negative)
print(f"Time remaining: {int(remaining_time)} seconds")
if remaining_time <= 0:
print(f"Time's up! The correct word was '{selected_word}'.") # Show correct word on loss
score = 0
break
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!") # Show word on win
break
save_high_score(username, score, 'timed') # Save high score for timed game
# Asking the player if they want to play again
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break # Exit the loop to stop the game
def display_high_scores(high_scores):
"""Display the high scores."""
print("\nHigh Scores:")
for difficulty in DIFFICULTY_WORDS.keys():
if difficulty in high_scores:
name, score = high_scores[difficulty]
print(f"High Score [Difficulty: {difficulty}]: {name} with {score} points")
else:
print(f"High Score [Difficulty: {difficulty}]: No scores yet")
def start_menu():
"""Display the start menu and handle user choices."""
while True: # Loop for displaying the main menu
print("Pick a game mode!")
print("1. Guess the Word: Earn points by guessing the correct letters.")
print("2. Beat the Shark: Race against a shark by guessing the word correctly.")
print("3. Timed Guess the Word: Infinite guesses but beat the timer!")
try:
choice = input("Select a game (1, 2, or 3), or 'q' to quit: ")
code
if choice == '1':
guess_the_word(username)
elif choice == '2':
beat_the_shark(username)
elif choice == '3':
timed_guess_the_word(username)
elif choice.lower() == 'q':
print("Thank you for playing! Goodbye!")
break
else:
print("Invalid choice. Please try again.")
except KeyboardInterrupt:
print("\nInput interrupted. Exiting the game.")
break
Load high scores at the start
high_scores = load_high_scores()
Display high scores if available
display_high_scores(high_scores)
Load users and handle login/registration
username = user_login()
Start the game
if name == "main":
start_menu() make it so in the log in page make a section that says highscores and in this highscores section save every gamemodes highscores
Assistant
Certainly! To add a High Scores section inside the login page, we can modify the user_login() function to include an option to view the high scores before logging in or registering.
What I'll do:
Modify user_login() to show a menu allowing:
Login (l)
Register (r)
View High Scores (h)
Quit (q)
When the user selects h, show the high scores for all game modes.
Make sure the high scores display function formats all game modes' scores, including the timed game mode.
Here's the updated full code for the user_login() function and minor modifications to support this behavior:
Updated user_login() with High Scores section:
python
User
import random
import os
import sys
import time # Import time for the timer functionality
Set number of tries based on difficulty
TRIES = {
'easy': 5,
'medium': 7,
'hard': 10
}
def ensure_data_directory():
"""Ensure the data directory exists."""
if not os.path.exists('data'):
os.makedirs('data')
def load_user_data():
"""Load user data from a file."""
if not os.path.exists(USER_DATA_FILE):
return {}
with open(USER_DATA_FILE, 'r') as file:
user_data = {}
for line in file:
username = line.strip()
user_data[username] = True # Using a dictionary to track registered users
return user_data
def register_user(username):
"""Register a new user."""
with open(USER_DATA_FILE, 'a') as file:
file.write(username + '\n')
def user_login():
"""Handle user login or registration."""
user_data = load_user_data()
while True:
try:
print("Login (l) or Register (r): ", end='', flush=True)
choice = sys.stdin.readline().strip().lower() # Using sys.stdin.readline()
print("Enter your username: ", end='', flush=True)
username = sys.stdin.readline().strip() # Using sys.stdin.readline()
code
Assistant
Certainly! I've integrated a High Scores section directly into the login menu per your request. Also fixed some formatting and indentation issues in your posted code. The main improvements are:
The user_login() function offers a menu: Login (l), Register (r), View High Scores (h), Quit (q)
Choosing h will display the high scores of all game modes before login/register.
Added 'timed' mode to display the timed mode high score as well.
Cleaned and fixed some indentation and syntax issues.
Corrected the if __name__ == "__main__": guard at the end.
Here is your updated full script with the requested features:
python
User
import random
import os
import sys
import time # Import time for the timer functionality
def ensure_data_directory():
"""Ensure the data directory exists."""
if not os.path.exists('data'):
os.makedirs('data')
def load_user_data():
"""Load user data from a file."""
if not os.path.exists(USER_DATA_FILE):
return {}
code
user_data = {}
with open(USER_DATA_FILE, 'r') as file:
for line in file:
username = line.strip()
user_data[username] = True # Using a dictionary to track registered users
return user_data
def register_user(username):
"""Register a new user."""
ensure_data_directory()
with open(USER_DATA_FILE, 'a') as file:
file.write(username + '\n')
def load_high_scores():
"""Load high scores from a file."""
if not os.path.exists(HIGH_SCORES_FILE):
return {}
code
high_scores = {}
with open(HIGH_SCORES_FILE, 'r') as file:
for line in file:
parts = line.strip().split(',')
if len(parts) == 3:
difficulty, name, score_str = parts
try:
score = int(score_str)
# Only keep the highest score per difficulty
if difficulty not in high_scores or score > high_scores[difficulty][1]:
high_scores[difficulty] = (name, score)
except ValueError:
continue
return high_scores
Assistant
To make the program quit immediately once the user answers no to the "Do you wish to play again?" prompt in any game mode, you should replace the break in each game replay loop with a sys.exit() call.
This will exit the entire program instead of just exiting the current game's loop.
What to do:
In these three functions:
guess_the_word(username)
beat_the_shark(username)
timed_guess_the_word(username)
Replace the lines like this:
python
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break # currently only breaks the game loop
with:
python
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
print("Thank you for playing! Exiting game.")
sys.exit(0) # Exit entire program immediately
Example: modified snippet for guess_the_word():
python
def guess_the_word(username):
"""Guess the word game."""
while True:
# game logic here ...
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
print("Thank you for playing! Exiting game.")
sys.exit(0)
Repeat this for beat_the_shark and timed_guess_the_word similarly:
python
# Inside beat_the_shark:
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
print("Thank you for playing! Exiting game.")
sys.exit(0)
# Inside timed_guess_the_word:
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
print("Thank you for playing! Exiting game.")
sys.exit(0)
Summary:
sys.exit(0) terminates the entire program.
break would only exit the current loop, and you would still return to the main menu.
Using sys.exit(0) provides immediate exit upon "no".
If you want, I can provide the full functions with these changes applied!
User
import random
import os
import sys
import time # Import time for the timer functionality
def ensure_data_directory():
"""Ensure the data directory exists."""
if not os.path.exists('data'):
os.makedirs('data')
def load_user_data():
"""Load user data from a file."""
if not os.path.exists(USER_DATA_FILE):
return {}
code
user_data = {}
with open(USER_DATA_FILE, 'r') as file:
for line in file:
username = line.strip()
user_data[username] = True # Using a dictionary to track registered users
return user_data
def register_user(username):
"""Register a new user."""
ensure_data_directory()
with open(USER_DATA_FILE, 'a') as file:
file.write(username + '\n')
def load_high_scores():
"""Load high scores from a file."""
if not os.path.exists(HIGH_SCORES_FILE):
return {}
code
high_scores = {}
with open(HIGH_SCORES_FILE, 'r') as file:
for line in file:
parts = line.strip().split(',')
if len(parts) == 3:
difficulty, name, score_str = parts
try:
score = int(score_str)
# Only keep the highest score per difficulty
if difficulty not in high_scores or score > high_scores[difficulty][1]:
high_scores[difficulty] = (name, score)
except ValueError:
continue
return high_scores
Assistant
Got it! You want the following behavior added to each game mode (guess_the_word, beat_the_shark, timed_guess_the_word):
After a game finishes, when asked "Do you wish to play again? (yes/no):"
If user answers yes, restart the same game mode.
If user answers no, ask "Return to main menu? (yes/no)"
If yes, return to the main menu (start menu)
If no, exit the game (quit the whole program)
Here's how to implement it:
Modify each game loop to run one game session inside an inner loop.
After that, prompt for "play again" (restart same game) or "main menu" (return to menu or quit).
Adjust loops accordingly.
I will show updates for guess_the_word() with comments, then you can apply a similar pattern to the other two games.
Updated guess_the_word() Function:
python
User
import random
import os
import sys
import time # Import time for the timer functionality
def ensure_data_directory():
"""Ensure the data directory exists."""
if not os.path.exists('data'):
os.makedirs('data')
def load_user_data():
"""Load user data from a file."""
if not os.path.exists(USER_DATA_FILE):
return {}
code
user_data = {}
with open(USER_DATA_FILE, 'r') as file:
for line in file:
username = line.strip()
user_data[username] = True # Using a dictionary to track registered users
return user_data
def register_user(username):
"""Register a new user."""
ensure_data_directory()
with open(USER_DATA_FILE, 'a') as file:
file.write(username + '\n')
def load_high_scores():
"""Load high scores from a file."""
if not os.path.exists(HIGH_SCORES_FILE):
return {}
code
high_scores = {}
with open(HIGH_SCORES_FILE, 'r') as file:
for line in file:
parts = line.strip().split(',')
if len(parts) == 3:
difficulty, name, score_str = parts
try:
score = int(score_str)
# Only keep the highest score per difficulty
if difficulty not in high_scores or score > high_scores[difficulty][1]:
high_scores[difficulty] = (name, score)
except ValueError:
continue
return high_scores
Assistant
You want to add at the "Do you wish to play again? (yes/no)" prompt an additional option "mainmenu (m)" — so players can choose to return to the main menu immediately instead of replaying or quitting.
Here’s what we'll do:
Change the prompt from "Do you wish to play again? (yes/no): "
to something like: "Do you wish to play again? (yes/no/m for main menu): "
Accept 'm' as the input to return immediately to the main menu.
So the logic for this prompt will be:
If input is 'yes': replay same game mode.
If input is 'm': return to main menu (exit the game loop and return).
Otherwise (no or anything else): exit the program.
I'll update the three game functions accordingly:
Updated snippet example (for guess_the_word()):
python
User
import random
import os
import sys
import time # Import time for the timer functionality
Set number of tries based on difficulty
TRIES = {
'easy': 5,
'medium': 7,
'hard': 10
}
def ensure_data_directory():
"""Ensure the data directory exists."""
if not os.path.exists('data'):
os.makedirs('data')
def load_user_data():
"""Load user data from a file."""
if not os.path.exists(USER_DATA_FILE):
return {}
user_data = {}
with open(USER_DATA_FILE, 'r') as file:
for line in file:
username = line.strip()
user_data[username] = True # Using a dictionary to track registered users
return user_data
def register_user(username):
"""Register a new user."""
ensure_data_directory()
with open(USER_DATA_FILE, 'a') as file:
file.write(username + '\n')
def load_high_scores():
"""Load high scores from a file."""
if not os.path.exists(HIGH_SCORES_FILE):
return {}
high_scores = {}
with open(HIGH_SCORES_FILE, 'r') as file:
for line in file:
parts = line.strip().split(',')
if len(parts) == 3:
difficulty, name, score_str = parts
try:
score = int(score_str)
# Only keep the highest score per difficulty
if difficulty not in high_scores or score > high_scores[difficulty][1]:
high_scores[difficulty] = (name, score)
except ValueError:
continue
return high_scores
def save_high_score(name, score, difficulty):
"""Save player's name and score to a file."""
ensure_data_directory() # Ensure data directory exists
with open(HIGH_SCORES_FILE, 'a') as file:
file.write(f"{difficulty},{name},{score}\n")
def get_word(difficulty):
"""Select a random word from a given difficulty level."""
return random.choice(DIFFICULTY_WORDS[difficulty])
def display_progress(selected_word, guessed_letters):
"""Display the current state of the guessed word."""
display_word = ''
for letter in selected_word:
if letter in guessed_letters:
display_word += letter + ' '
else:
display_word += '_ '
print("\nCurrent word:", display_word.strip())
def user_login():
"""Handle user login, registration, or viewing high scores."""
user_data = load_user_data()
high_scores = load_high_scores() # Load high scores here to show on demand
Assistant
Certainly! I've fixed your code issues, improved the formatting and indentation, and incorporated the "main menu (m)" option at the "Do you wish to play again?" prompts in all game modes (guess_the_word, beat_the_shark, and timed_guess_the_word).
Here is the complete updated code with your request applied and ready to run:
def user_login():
"""Handle user login, registration, or viewing high scores."""
user_data = load_user_data()
high_scores = load_high_scores() # Load high scores here to show on demand
while True:
try:
print("\nWelcome! Please choose an option:")
print("Login (l)")
print("Register (r)")
print("View High Scores (h)")
print("Quit (q)")
print("Enter your choice: ", end='', flush=True)
choice = sys.stdin.readline().strip().lower()
if choice == 'l':
print("Enter your username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username in user_data:
print(f"Welcome back, {username}!")
return username
else:
print("Username does not exist. Please register first.")
elif choice == 'r':
print("Enter your desired username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username not in user_data:
register_user(username)
print(f"User {username} registered successfully!")
return username
else:
print("Username already exists. Please choose a different one.")
elif choice == 'h':
print("\n--- High Scores ---")
# Include timed game mode and the existing difficulties
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
if mode in high_scores:
name, score = high_scores[mode]
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: {name} with {score} points")
else:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: No scores yet")
print("-------------------\n")
elif choice == 'q':
print("Exiting. Goodbye!")
sys.exit(0)
else:
print("Invalid choice. Please enter 'l', 'r', 'h', or 'q'.")
except EOFError:
print("\nInput error: Please ensure you're running this in an interactive console.")
break
except KeyboardInterrupt:
print("\nInput interrupted. Exiting user login.")
break
except Exception as e:
print(f"An error occurred: {e}")
break
Explanation:
Added a menu inside user_login() with Login, Register, High Scores, and Quit options.
h (High Scores) will print the high scores for all difficulties and timed mode.
Users can view high scores before logging in or registering.
Quit (q) will exit the program cleanly.
Login requires entering the username and checks if it exists.
Register requires a new username (must be unique).
Handling exceptions and providing meaningful messages.
How to integrate:
Replace your existing user_login() function with this new version.
No other changes needed; the rest of your code references user_login() and works unchanged.
If you want me to help you integrate or test this with your full code, just ask!
if choice == 'l':
if username in user_data:
print(f"Welcome back, {username}!")
return username
else:
print("Username does not exist. Please register.")
elif choice == 'r':
if username not in user_data:
register_user(username)
print(f"User {username} registered successfully!")
return username
else:
print("Username already exists. Please choose a different one.")
else:
print("Invalid choice. Please enter 'l' for Login or 'r' for Register.")
except EOFError:
print("\nInput error: Please ensure you're running this in an interactive console.")
break
except KeyboardInterrupt:
print("\nInput interrupted. Exiting user login.")
break
except Exception as e:
print(f"An error occurred: {e}")
break
def load_high_scores():
"""Load high scores from a file."""
if not os.path.exists(HIGH_SCORES_FILE):
return {}
with open(HIGH_SCORES_FILE, 'r') as file:
high_scores = {}
for line in file:
difficulty, name, score = line.strip().split(',')
high_scores[difficulty] = (name, int(score))
return high_scores
def save_high_score(name, score, difficulty):
"""Save player's name and score to a file."""
ensure_data_directory() # Ensure data directory exists
with open(HIGH_SCORES_FILE, 'a') as file:
file.write(f"{difficulty},{name},{score}\n")
def get_word(difficulty):
"""Select a random word from a given difficulty level."""
return random.choice(DIFFICULTY_WORDS[difficulty])
def display_progress(selected_word, guessed_letters):
"""Display the current state of the guessed word."""
display_word = ''
for letter in selected_word:
if letter in guessed_letters:
display_word += letter + ' '
else:
display_word += '_ '
print("\nCurrent word:", display_word.strip())
def guess_the_word(username):
"""Guess the word game."""
while True: # Loop for playing the game until user decides to exit
print("Welcome to 'Guess the Word'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty] # Set tries based on selected difficulty
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1 # Deduct one attempt for incorrect guess
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!") # Show word on win
break
if remaining_tries <= 0:
print(f"Game over! The correct word was '{selected_word}'.") # Show correct word on loss
score = 0 # Zero score if they fail to guess
save_high_score(username, score, difficulty)
# Asking the player if they want to play again
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break # Exit the loop to stop the game
def display_shark(shark):
"""Display the shark's position."""
print("Shark's position:", shark)
def beat_the_shark(username):
"""A simple race game where player guesses letters and compares to a shark opponent."""
while True: # Loop for playing the game until user decides to exit
print("\nWelcome to 'Beat the Shark'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty] # Set tries based on selected difficulty
# Initialize shark string based on difficulty
if difficulty == 'easy':
shark = "﹏﹏﹏𓂁" # 3 underscores for easy
elif difficulty == 'medium':
shark = "﹏﹏﹏﹏﹏𓂁" # 5 underscores for medium
else:
shark = "﹏﹏﹏﹏﹏﹏﹏﹏𓂁" # 7 underscores for hard
# Display initial shark position
display_shark(shark)
while remaining_tries > 0: # The loop continues as long as there are remaining tries
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess! The shark is still behind!")
else:
remaining_tries -= 1 # Deduct one attempt for incorrect guess
score -= 10
print("Wrong guess! -10 points. The shark moves forward!")
# Remove one '﹏' from the shark to show it moving closer
shark = shark[:-1] # Slice off the last character
if len(shark) <= 1: # If we only have the shark emoji left
shark = '𓂁' # Replace with only the shark emoji
# Display updated shark position
display_shark(shark)
# If the player successfully guesses all letters in the word, they win
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! The shark couldn't catch you!") # Show word on win
break
# If player runs out of tries, the shark catches them
if remaining_tries <= 0:
print(f"The shark caught you! Game over! The correct word was '{selected_word}'.") # Show correct word on loss
score = 0 # Score is zero if caught
save_high_score(username, score, difficulty)
# Asking the player if they want to play again
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break # Exit the loop to stop the game
def timed_guess_the_word(username):
"""Timed Guess the Word game."""
while True: # Loop for playing the game until user decides to exit
print("Welcome to 'Timed Guess the Word'!")
print("You have infinite guesses but must guess the word within the time limit.")
code
# Select time limit
while True:
print("Choose a time limit:")
print("1. 30 seconds")
print("2. 1 minute (60 seconds)")
print("3. 1 minute and 30 seconds (90 seconds)")
time_choice = input("Select a time limit (1, 2, 3): ").strip()
if time_choice == '1':
timer_duration = 30
break
elif time_choice == '2':
timer_duration = 60
break
elif time_choice == '3':
timer_duration = 90
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
start_time = time.time() # Start the timer
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
elapsed_time = time.time() - start_time # Calculate elapsed time
remaining_time = max(0, timer_duration - elapsed_time) # Calculate remaining time (cannot be negative)
print(f"Time remaining: {int(remaining_time)} seconds")
if remaining_time <= 0:
print(f"Time's up! The correct word was '{selected_word}'.") # Show correct word on loss
score = 0
break
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!") # Show word on win
break
save_high_score(username, score, 'timed') # Save high score for timed game
# Asking the player if they want to play again
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break # Exit the loop to stop the game
def display_high_scores(high_scores):
"""Display the high scores."""
print("\nHigh Scores:")
for difficulty in DIFFICULTY_WORDS.keys():
if difficulty in high_scores:
name, score = high_scores[difficulty]
print(f"High Score [Difficulty: {difficulty}]: {name} with {score} points")
else:
print(f"High Score [Difficulty: {difficulty}]: No scores yet")
def start_menu():
"""Display the start menu and handle user choices."""
while True: # Loop for displaying the main menu
print("Pick a game mode!")
print("1. Guess the Word: Earn points by guessing the correct letters.")
print("2. Beat the Shark: Race against a shark by guessing the word correctly.")
print("3. Timed Guess the Word: Infinite guesses but beat the timer!")
try:
choice = input("Select a game (1, 2, or 3), or 'q' to quit: ")
code
if choice == '1':
guess_the_word(username)
elif choice == '2':
beat_the_shark(username)
elif choice == '3':
timed_guess_the_word(username)
elif choice.lower() == 'q':
print("Thank you for playing! Goodbye!")
break
else:
print("Invalid choice. Please try again.")
except KeyboardInterrupt:
print("\nInput interrupted. Exiting the game.")
break
Load high scores at the start
high_scores = load_high_scores()
Display high scores if available
display_high_scores(high_scores)
Load users and handle login/registration
username = user_login()
Start the game
if name == "main":
start_menu() make it so in the log in page make a section that says highscores and in this highscores section save every gamemodes highscores add it all to this code
import random
import os
import sys
import time # Import time for the timer functionality
# Print ASCII Art Banner
ascii_art = """
██╗ ██╗ ██████╗ ██████╗ ██████╗ ██████╗ █████╗ ███╗ ███╗███████╗
██║ ██║██╔═══██╗██╔══██╗██╔══██╗ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
██║ █╗ ██║██║ ██║██████╔╝██║ ██║ ██║ ███╗███████║██╔████╔██║█████╗
██║███╗██║██║ ██║██╔══██╗██║ ██║ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
╚███╔███╔╝╚██████╔╝██║ ██║██████╔╝ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
"""
print(ascii_art)
# Constants
HIGH_SCORES_FILE = 'data/high_scores.txt'
USER_DATA_FILE = 'data/user_data.txt'
# Word lists for different difficulty levels
DIFFICULTY_WORDS = {
'easy': ['cat', 'fish', 'dog', 'bird', 'frog', 'apple', 'table', 'chair', 'book', 'lamp'],
'medium': ['giraffe', 'monkey', 'penguin', 'squirrel', 'elephant', 'dolphin', 'computer', 'pencil', 'candle', 'window'],
'hard': ['chimpanzee', 'extraordinary', 'microorganism', 'unbelievable', 'determination', 'superintendent', 'phenomenon', 'incomprehensible', 'electromagnetic', 'characteristic']
}
# Set number of tries based on difficulty
TRIES = {
'easy': 5,
'medium': 7,
'hard': 10
}
def ensure_data_directory():
"""Ensure the data directory exists."""
if not os.path.exists('data'):
os.makedirs('data')
def load_user_data():
"""Load user data from a file."""
if not os.path.exists(USER_DATA_FILE):
return {}
user_data = {}
with open(USER_DATA_FILE, 'r') as file:
for line in file:
username = line.strip()
user_data[username] = True # Using a dictionary to track registered users
return user_data
def register_user(username):
"""Register a new user."""
ensure_data_directory()
with open(USER_DATA_FILE, 'a') as file:
file.write(username + '\n')
def load_high_scores():
"""Load high scores from a file."""
if not os.path.exists(HIGH_SCORES_FILE):
return {}
high_scores = {}
with open(HIGH_SCORES_FILE, 'r') as file:
for line in file:
parts = line.strip().split(',')
if len(parts) == 3:
difficulty, name, score_str = parts
try:
score = int(score_str)
# Only keep the highest score per difficulty
if difficulty not in high_scores or score > high_scores[difficulty][1]:
high_scores[difficulty] = (name, score)
except ValueError:
continue
return high_scores
def save_high_score(name, score, difficulty):
"""Save player's name and score to a file."""
ensure_data_directory() # Ensure data directory exists
with open(HIGH_SCORES_FILE, 'a') as file:
file.write(f"{difficulty},{name},{score}\n")
def get_word(difficulty):
"""Select a random word from a given difficulty level."""
return random.choice(DIFFICULTY_WORDS[difficulty])
def display_progress(selected_word, guessed_letters):
"""Display the current state of the guessed word."""
display_word = ''
for letter in selected_word:
if letter in guessed_letters:
display_word += letter + ' '
else:
display_word += '_ '
print("\nCurrent word:", display_word.strip())
def user_login():
"""Handle user login, registration, or viewing high scores."""
user_data = load_user_data()
high_scores = load_high_scores() # Load high scores here to show on demand
while True:
try:
print("\nWelcome! Please choose an option:")
print("Login (l)")
print("Register (r)")
print("View High Scores (h)")
print("Quit (q)")
print("Enter your choice: ", end='', flush=True)
choice = sys.stdin.readline().strip().lower()
if choice == 'l':
print("Enter your username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username in user_data:
print(f"Welcome back, {username}!")
return username
else:
print("Username does not exist. Please register first.")
elif choice == 'r':
print("Enter your desired username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username not in user_data:
register_user(username)
print(f"User {username} registered successfully!")
return username
else:
print("Username already exists. Please choose a different one.")
elif choice == 'h':
print("\n--- High Scores ---")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
if mode in high_scores:
name, score = high_scores[mode]
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: {name} with {score} points")
else:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: No scores yet")
print("-------------------")
elif choice == 'q':
print("Exiting. Goodbye!")
sys.exit(0)
else:
print("Invalid choice. Please enter 'l', 'r', 'h', or 'q'.")
except EOFError:
print("\nInput error: Please ensure you're running this in an interactive console.")
break
except KeyboardInterrupt:
print("\nInput interrupted. Exiting user login.")
break
except Exception as e:
print(f"An error occurred: {e}")
break
def guess_the_word(username):
"""Guess the word game."""
while True:
print("\nWelcome to 'Guess the Word'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
if remaining_tries <= 0:
print(f"Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def display_shark(shark):
"""Display the shark's position."""
print("Shark's position:", shark)
def beat_the_shark(username):
"""A simple race game where player guesses letters and compares to a shark opponent."""
while True:
print("\nWelcome to 'Beat the Shark'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
# Initialize shark string based on difficulty
if difficulty == 'easy':
shark = "﹏﹏﹏𓂁"
elif difficulty == 'medium':
shark = "﹏﹏﹏﹏﹏𓂁"
else:
shark = "﹏﹏﹏﹏﹏﹏﹏﹏𓂁"
display_shark(shark)
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess! The shark is still behind!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points. The shark moves forward!")
# Remove one '﹏' from the shark string
if len(shark) > 1:
shark = shark[:-1]
if len(shark) <= 1:
shark = '𓂁'
display_shark(shark)
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! The shark couldn't catch you!")
break
if remaining_tries <= 0:
print(f"The shark caught you! Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def timed_guess_the_word(username):
"""Timed Guess the Word game."""
while True:
print("\nWelcome to 'Timed Guess the Word'!")
print("You have infinite guesses but must guess the word within the time limit.")
# Select time limit
while True:
print("Choose a time limit:")
print("1. 30 seconds")
print("2. 1 minute (60 seconds)")
print("3. 1 minute and 30 seconds (90 seconds)")
time_choice = input("Select a time limit (1, 2, 3): ").strip()
if time_choice == '1':
timer_duration = 30
break
elif time_choice == '2':
timer_duration = 60
break
elif time_choice == '3':
timer_duration = 90
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
start_time = time.time()
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
elapsed_time = time.time() - start_time
remaining_time = max(0, timer_duration - elapsed_time)
print(f"Time remaining: {int(remaining_time)} seconds")
if remaining_time <= 0:
print(f"Time's up! The correct word was '{selected_word}'.")
score = 0
break
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
save_high_score(username, score, 'timed')
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def display_high_scores(high_scores):
"""Display the high scores."""
print("\nHigh Scores:")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
if mode in high_scores:
name, score = high_scores[mode]
print(f"{mode_name} mode: {name} with {score} points")
else:
print(f"{mode_name} mode: No scores yet")
def start_menu():
"""Display the start menu and handle user choices."""
while True:
print("\nPick a game mode!")
print("1. Guess the Word: Earn points by guessing the correct letters.")
print("2. Beat the Shark: Race against a shark by guessing the word correctly.")
print("3. Timed Guess the Word: Infinite guesses but beat the timer!")
try:
choice = input("Select a game (1, 2, or 3), or 'q' to quit: ")
if choice == '1':
guess_the_word(username)
elif choice == '2':
beat_the_shark(username)
elif choice == '3':
timed_guess_the_word(username)
elif choice.lower() == 'q':
print("Thank you for playing! Goodbye!")
break
else:
print("Invalid choice. Please try again.")
except KeyboardInterrupt:
print("\nInput interrupted. Exiting the game.")
break
if __name__ == "__main__":
# Load and display high scores at the start
high_scores = load_high_scores()
display_high_scores(high_scores)
# User login or registration
username = user_login()
# Start main menu
start_menu()
Summary of what this does:
At program start, prints ASCII art and current high scores.
In login, users can:
Login (l)
Register (r)
View High Scores (h)
Quit (q)
High scores for easy, medium, hard, and timed modes are always shown when requested.
Saves and loads scores properly, keeping highest scores per difficulty.
The code is properly indented and ready to run.
If you'd like help testing or further enhancements, feel free to ask!
def save_high_score(name, score, difficulty):
"""Save player's name and score to a file."""
ensure_data_directory() # Ensure data directory exists
with open(HIGH_SCORES_FILE, 'a') as file:
file.write(f"{difficulty},{name},{score}\n")
def get_word(difficulty):
"""Select a random word from a given difficulty level."""
return random.choice(DIFFICULTY_WORDS[difficulty])
def display_progress(selected_word, guessed_letters):
"""Display the current state of the guessed word."""
display_word = ''
for letter in selected_word:
if letter in guessed_letters:
display_word += letter + ' '
else:
display_word += '_ '
print("\nCurrent word:", display_word.strip())
def user_login():
"""Handle user login, registration, or viewing high scores."""
user_data = load_user_data()
high_scores = load_high_scores() # Load high scores here to show on demand
code
while True:
try:
print("\nWelcome! Please choose an option:")
print("Login (l)")
print("Register (r)")
print("View High Scores (h)")
print("Quit (q)")
print("Enter your choice: ", end='', flush=True)
choice = sys.stdin.readline().strip().lower()
if choice == 'l':
print("Enter your username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username in user_data:
print(f"Welcome back, {username}!")
return username
else:
print("Username does not exist. Please register first.")
elif choice == 'r':
print("Enter your desired username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username not in user_data:
register_user(username)
print(f"User {username} registered successfully!")
return username
else:
print("Username already exists. Please choose a different one.")
elif choice == 'h':
print("\n--- High Scores ---")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
if mode in high_scores:
name, score = high_scores[mode]
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: {name} with {score} points")
else:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: No scores yet")
print("-------------------")
elif choice == 'q':
print("Exiting. Goodbye!")
sys.exit(0)
else:
print("Invalid choice. Please enter 'l', 'r', 'h', or 'q'.")
except EOFError:
print("\nInput error: Please ensure you're running this in an interactive console.")
break
except KeyboardInterrupt:
print("\nInput interrupted. Exiting user login.")
break
except Exception as e:
print(f"An error occurred: {e}")
break
def guess_the_word(username):
"""Guess the word game."""
while True:
print("\nWelcome to 'Guess the Word'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
if remaining_tries <= 0:
print(f"Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def display_shark(shark):
"""Display the shark's position."""
print("Shark's position:", shark)
def beat_the_shark(username):
"""A simple race game where player guesses letters and compares to a shark opponent."""
while True:
print("\nWelcome to 'Beat the Shark'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
# Initialize shark string based on difficulty
if difficulty == 'easy':
shark = "﹏﹏﹏𓂁"
elif difficulty == 'medium':
shark = "﹏﹏﹏﹏﹏𓂁"
else:
shark = "﹏﹏﹏﹏﹏﹏﹏﹏𓂁"
display_shark(shark)
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess! The shark is still behind!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points. The shark moves forward!")
# Remove one '﹏' from the shark string
if len(shark) > 1:
shark = shark[:-1]
if len(shark) <= 1:
shark = '𓂁'
display_shark(shark)
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! The shark couldn't catch you!")
break
if remaining_tries <= 0:
print(f"The shark caught you! Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def timed_guess_the_word(username):
"""Timed Guess the Word game."""
while True:
print("\nWelcome to 'Timed Guess the Word'!")
print("You have infinite guesses but must guess the word within the time limit.")
code
# Select time limit
while True:
print("Choose a time limit:")
print("1. 30 seconds")
print("2. 1 minute (60 seconds)")
print("3. 1 minute and 30 seconds (90 seconds)")
time_choice = input("Select a time limit (1, 2, 3): ").strip()
if time_choice == '1':
timer_duration = 30
break
elif time_choice == '2':
timer_duration = 60
break
elif time_choice == '3':
timer_duration = 90
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
start_time = time.time()
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
elapsed_time = time.time() - start_time
remaining_time = max(0, timer_duration - elapsed_time)
print(f"Time remaining: {int(remaining_time)} seconds")
if remaining_time <= 0:
print(f"Time's up! The correct word was '{selected_word}'.")
score = 0
break
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
save_high_score(username, score, 'timed')
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def display_high_scores(high_scores):
"""Display the high scores."""
print("\nHigh Scores:")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
if mode in high_scores:
name, score = high_scores[mode]
print(f"{mode_name} mode: {name} with {score} points")
else:
print(f"{mode_name} mode: No scores yet")
def start_menu():
"""Display the start menu and handle user choices."""
while True:
print("\nPick a game mode!")
print("1. Guess the Word: Earn points by guessing the correct letters.")
print("2. Beat the Shark: Race against a shark by guessing the word correctly.")
print("3. Timed Guess the Word: Infinite guesses but beat the timer!")
try:
choice = input("Select a game (1, 2, or 3), or 'q' to quit: ")
code
if choice == '1':
guess_the_word(username)
elif choice == '2':
beat_the_shark(username)
elif choice == '3':
timed_guess_the_word(username)
elif choice.lower() == 'q':
print("Thank you for playing! Goodbye!")
break
else:
print("Invalid choice. Please try again.")
except KeyboardInterrupt:
print("\nInput interrupted. Exiting the game.")
break
if name == "main":
# Load and display high scores at the start
high_scores = load_high_scores()
display_high_scores(high_scores)
code
# User login or registration
username = user_login()
# Start main menu
start_menu() once you click no to the play again make it so you quit the game
def save_high_score(name, score, difficulty):
"""Save player's name and score to a file."""
ensure_data_directory() # Ensure data directory exists
with open(HIGH_SCORES_FILE, 'a') as file:
file.write(f"{difficulty},{name},{score}\n")
def get_word(difficulty):
"""Select a random word from a given difficulty level."""
return random.choice(DIFFICULTY_WORDS[difficulty])
def display_progress(selected_word, guessed_letters):
"""Display the current state of the guessed word."""
display_word = ''
for letter in selected_word:
if letter in guessed_letters:
display_word += letter + ' '
else:
display_word += '_ '
print("\nCurrent word:", display_word.strip())
def user_login():
"""Handle user login, registration, or viewing high scores."""
user_data = load_user_data()
high_scores = load_high_scores() # Load high scores here to show on demand
code
while True:
try:
print("\nWelcome! Please choose an option:")
print("Login (l)")
print("Register (r)")
print("View High Scores (h)")
print("Quit (q)")
print("Enter your choice: ", end='', flush=True)
choice = sys.stdin.readline().strip().lower()
if choice == 'l':
print("Enter your username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username in user_data:
print(f"Welcome back, {username}!")
return username
else:
print("Username does not exist. Please register first.")
elif choice == 'r':
print("Enter your desired username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username not in user_data:
register_user(username)
print(f"User {username} registered successfully!")
return username
else:
print("Username already exists. Please choose a different one.")
elif choice == 'h':
print("\n--- High Scores ---")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
if mode in high_scores:
name, score = high_scores[mode]
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: {name} with {score} points")
else:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: No scores yet")
print("-------------------")
elif choice == 'q':
print("Exiting. Goodbye!")
sys.exit(0)
else:
print("Invalid choice. Please enter 'l', 'r', 'h', or 'q'.")
except EOFError:
print("\nInput error: Please ensure you're running this in an interactive console.")
break
except KeyboardInterrupt:
print("\nInput interrupted. Exiting user login.")
break
except Exception as e:
print(f"An error occurred: {e}")
break
def guess_the_word(username):
"""Guess the word game."""
while True:
print("\nWelcome to 'Guess the Word'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
if remaining_tries <= 0:
print(f"Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def display_shark(shark):
"""Display the shark's position."""
print("Shark's position:", shark)
def beat_the_shark(username):
"""A simple race game where player guesses letters and compares to a shark opponent."""
while True:
print("\nWelcome to 'Beat the Shark'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
# Initialize shark string based on difficulty
if difficulty == 'easy':
shark = "﹏﹏﹏𓂁"
elif difficulty == 'medium':
shark = "﹏﹏﹏﹏﹏𓂁"
else:
shark = "﹏﹏﹏﹏﹏﹏﹏﹏𓂁"
display_shark(shark)
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess! The shark is still behind!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points. The shark moves forward!")
# Remove one '﹏' from the shark string
if len(shark) > 1:
shark = shark[:-1]
if len(shark) <= 1:
shark = '𓂁'
display_shark(shark)
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! The shark couldn't catch you!")
break
if remaining_tries <= 0:
print(f"The shark caught you! Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def timed_guess_the_word(username):
"""Timed Guess the Word game."""
while True:
print("\nWelcome to 'Timed Guess the Word'!")
print("You have infinite guesses but must guess the word within the time limit.")
code
# Select time limit
while True:
print("Choose a time limit:")
print("1. 30 seconds")
print("2. 1 minute (60 seconds)")
print("3. 1 minute and 30 seconds (90 seconds)")
time_choice = input("Select a time limit (1, 2, 3): ").strip()
if time_choice == '1':
timer_duration = 30
break
elif time_choice == '2':
timer_duration = 60
break
elif time_choice == '3':
timer_duration = 90
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
start_time = time.time()
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
elapsed_time = time.time() - start_time
remaining_time = max(0, timer_duration - elapsed_time)
print(f"Time remaining: {int(remaining_time)} seconds")
if remaining_time <= 0:
print(f"Time's up! The correct word was '{selected_word}'.")
score = 0
break
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
save_high_score(username, score, 'timed')
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def display_high_scores(high_scores):
"""Display the high scores."""
print("\nHigh Scores:")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
if mode in high_scores:
name, score = high_scores[mode]
print(f"{mode_name} mode: {name} with {score} points")
else:
print(f"{mode_name} mode: No scores yet")
def start_menu():
"""Display the start menu and handle user choices."""
while True:
print("\nPick a game mode!")
print("1. Guess the Word: Earn points by guessing the correct letters.")
print("2. Beat the Shark: Race against a shark by guessing the word correctly.")
print("3. Timed Guess the Word: Infinite guesses but beat the timer!")
try:
choice = input("Select a game (1, 2, or 3), or 'q' to quit: ")
code
if choice == '1':
guess_the_word(username)
elif choice == '2':
beat_the_shark(username)
elif choice == '3':
timed_guess_the_word(username)
elif choice.lower() == 'q':
print("Thank you for playing! Goodbye!")
break
else:
print("Invalid choice. Please try again.")
except KeyboardInterrupt:
print("\nInput interrupted. Exiting the game.")
break
if name == "main":
# Load and display high scores at the start
high_scores = load_high_scores()
display_high_scores(high_scores)
code
# User login or registration
username = user_login()
# Start main menu
start_menu() make an extra option at the end where it says main menu and it will take you back to the start of the game but if they click yes restart the same gamemode but you click no to play again make it quit
def guess_the_word(username):
"""Guess the word game."""
while True: # Outer loop controls replaying the game or returning to menu/exit
while True: # Inner loop is the game session itself
print("\nWelcome to 'Guess the Word'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
if remaining_tries <= 0:
print(f"Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
break # End inner game loop after one session
# Ask if user wants to play same game again
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again == 'yes':
continue # Start new game session (same game mode)
# If not replaying, ask about returning to main menu or exit
main_menu_choice = input("Return to main menu? (yes/no): ").lower()
if main_menu_choice == 'yes':
return # Return from this function to main menu
else:
print("Thank you for playing! Exiting game.")
sys.exit(0)
Apply the same pattern to beat_the_shark():
python
def beat_the_shark(username):
while True:
while True: # single game session loop
print("\nWelcome to 'Beat the Shark'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
# Initialize shark string based on difficulty
if difficulty == 'easy':
shark = "﹏﹏﹏𓂁"
elif difficulty == 'medium':
shark = "﹏﹏﹏﹏﹏𓂁"
else:
shark = "﹏﹏﹏﹏﹏﹏﹏﹏𓂁"
display_shark(shark)
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess! The shark is still behind!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points. The shark moves forward!")
if len(shark) > 1:
shark = shark[:-1]
if len(shark) <= 1:
shark = '𓂁'
display_shark(shark)
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! The shark couldn't catch you!")
break
if remaining_tries <= 0:
print(f"The shark caught you! Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
break # end single game session
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again == 'yes':
continue
main_menu_choice = input("Return to main menu? (yes/no): ").lower()
if main_menu_choice == 'yes':
return
else:
print("Thank you for playing! Exiting game.")
sys.exit(0)
And timed_guess_the_word():
python
def timed_guess_the_word(username):
while True:
while True: # single game session loop
print("\nWelcome to 'Timed Guess the Word'!")
print("You have infinite guesses but must guess the word within the time limit.")
while True:
print("Choose a time limit:")
print("1. 30 seconds")
print("2. 1 minute (60 seconds)")
print("3. 1 minute and 30 seconds (90 seconds)")
time_choice = input("Select a time limit (1, 2, 3): ").strip()
if time_choice == '1':
timer_duration = 30
break
elif time_choice == '2':
timer_duration = 60
break
elif time_choice == '3':
timer_duration = 90
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
start_time = time.time()
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
elapsed_time = time.time() - start_time
remaining_time = max(0, timer_duration - elapsed_time)
print(f"Time remaining: {int(remaining_time)} seconds")
if remaining_time <= 0:
print(f"Time's up! The correct word was '{selected_word}'.")
score = 0
break
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
save_high_score(username, score, 'timed')
break # end single game session
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again == 'yes':
continue
main_menu_choice = input("Return to main menu? (yes/no): ").lower()
if main_menu_choice == 'yes':
return
else:
print("Thank you for playing! Exiting game.")
sys.exit(0)
Finally, since you return to main menu, your start_menu() will be called as usual again.
If you'd like, I can prepare a full updated file with these changes included. Just ask!
def save_high_score(name, score, difficulty):
"""Save player's name and score to a file."""
ensure_data_directory() # Ensure data directory exists
with open(HIGH_SCORES_FILE, 'a') as file:
file.write(f"{difficulty},{name},{score}\n")
def get_word(difficulty):
"""Select a random word from a given difficulty level."""
return random.choice(DIFFICULTY_WORDS[difficulty])
def display_progress(selected_word, guessed_letters):
"""Display the current state of the guessed word."""
display_word = ''
for letter in selected_word:
if letter in guessed_letters:
display_word += letter + ' '
else:
display_word += '_ '
print("\nCurrent word:", display_word.strip())
def user_login():
"""Handle user login, registration, or viewing high scores."""
user_data = load_user_data()
high_scores = load_high_scores() # Load high scores here to show on demand
code
while True:
try:
print("\nWelcome! Please choose an option:")
print("Login (l)")
print("Register (r)")
print("View High Scores (h)")
print("Quit (q)")
print("Enter your choice: ", end='', flush=True)
choice = sys.stdin.readline().strip().lower()
if choice == 'l':
print("Enter your username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username in user_data:
print(f"Welcome back, {username}!")
return username
else:
print("Username does not exist. Please register first.")
elif choice == 'r':
print("Enter your desired username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username not in user_data:
register_user(username)
print(f"User {username} registered successfully!")
return username
else:
print("Username already exists. Please choose a different one.")
elif choice == 'h':
print("\n--- High Scores ---")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
if mode in high_scores:
name, score = high_scores[mode]
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: {name} with {score} points")
else:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: No scores yet")
print("-------------------")
elif choice == 'q':
print("Exiting. Goodbye!")
sys.exit(0)
else:
print("Invalid choice. Please enter 'l', 'r', 'h', or 'q'.")
except EOFError:
print("\nInput error: Please ensure you're running this in an interactive console.")
break
except KeyboardInterrupt:
print("\nInput interrupted. Exiting user login.")
break
except Exception as e:
print(f"An error occurred: {e}")
break
def guess_the_word(username):
"""Guess the word game."""
while True:
print("\nWelcome to 'Guess the Word'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
if remaining_tries <= 0:
print(f"Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def display_shark(shark):
"""Display the shark's position."""
print("Shark's position:", shark)
def beat_the_shark(username):
"""A simple race game where player guesses letters and compares to a shark opponent."""
while True:
print("\nWelcome to 'Beat the Shark'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
# Initialize shark string based on difficulty
if difficulty == 'easy':
shark = "﹏﹏﹏𓂁"
elif difficulty == 'medium':
shark = "﹏﹏﹏﹏﹏𓂁"
else:
shark = "﹏﹏﹏﹏﹏﹏﹏﹏𓂁"
display_shark(shark)
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess! The shark is still behind!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points. The shark moves forward!")
# Remove one '﹏' from the shark string
if len(shark) > 1:
shark = shark[:-1]
if len(shark) <= 1:
shark = '𓂁'
display_shark(shark)
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! The shark couldn't catch you!")
break
if remaining_tries <= 0:
print(f"The shark caught you! Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def timed_guess_the_word(username):
"""Timed Guess the Word game."""
while True:
print("\nWelcome to 'Timed Guess the Word'!")
print("You have infinite guesses but must guess the word within the time limit.")
code
# Select time limit
while True:
print("Choose a time limit:")
print("1. 30 seconds")
print("2. 1 minute (60 seconds)")
print("3. 1 minute and 30 seconds (90 seconds)")
time_choice = input("Select a time limit (1, 2, 3): ").strip()
if time_choice == '1':
timer_duration = 30
break
elif time_choice == '2':
timer_duration = 60
break
elif time_choice == '3':
timer_duration = 90
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
start_time = time.time()
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
elapsed_time = time.time() - start_time
remaining_time = max(0, timer_duration - elapsed_time)
print(f"Time remaining: {int(remaining_time)} seconds")
if remaining_time <= 0:
print(f"Time's up! The correct word was '{selected_word}'.")
score = 0
break
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
save_high_score(username, score, 'timed')
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def display_high_scores(high_scores):
"""Display the high scores."""
print("\nHigh Scores:")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
if mode in high_scores:
name, score = high_scores[mode]
print(f"{mode_name} mode: {name} with {score} points")
else:
print(f"{mode_name} mode: No scores yet")
def start_menu():
"""Display the start menu and handle user choices."""
while True:
print("\nPick a game mode!")
print("1. Guess the Word: Earn points by guessing the correct letters.")
print("2. Beat the Shark: Race against a shark by guessing the word correctly.")
print("3. Timed Guess the Word: Infinite guesses but beat the timer!")
try:
choice = input("Select a game (1, 2, or 3), or 'q' to quit: ")
code
if choice == '1':
guess_the_word(username)
elif choice == '2':
beat_the_shark(username)
elif choice == '3':
timed_guess_the_word(username)
elif choice.lower() == 'q':
print("Thank you for playing! Goodbye!")
break
else:
print("Invalid choice. Please try again.")
except KeyboardInterrupt:
print("\nInput interrupted. Exiting the game.")
break
if name == "main":
# Load and display high scores at the start
high_scores = load_high_scores()
display_high_scores(high_scores)
code
# User login or registration
username = user_login()
# Start main menu
start_menu() at the end when it says do you wish to play again add an option that says mainmenu(m)
def guess_the_word(username):
"""Guess the word game."""
while True:
print("\nWelcome to 'Guess the Word'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
if remaining_tries <= 0:
print(f"Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
while True:
play_again = input("Do you wish to play again? (yes/no/m for main menu): ").lower()
if play_again == 'yes':
break # Break inner prompt loop, start a new game in outer while
elif play_again == 'm':
return # Return to main menu
elif play_again == 'no':
print("Thank you for playing! Exiting game.")
sys.exit(0)
else:
print("Invalid input. Please enter 'yes', 'no', or 'm'.")
# If reached here and input was 'yes', the outer while continues and game restarts
Apply the same pattern to beat_the_shark():
Replace the bottom part:
python
while True:
play_again = input("Do you wish to play again? (yes/no/m for main menu): ").lower()
if play_again == 'yes':
break
elif play_again == 'm':
return
elif play_again == 'no':
print("Thank you for playing! Exiting game.")
sys.exit(0)
else:
print("Invalid input. Please enter 'yes', 'no', or 'm'.")
And timed_guess_the_word() similarly.
If you want, I can provide the full updated code of each function incorporating this! Would you like the complete updated code for all three game functions with this change?
while True:
try:
print("\nWelcome! Please choose an option:")
print("Login (l)")
print("Register (r)")
print("View High Scores (h)")
print("Quit (q)")
print("Enter your choice: ", end='', flush=True)
choice = sys.stdin.readline().strip().lower()
code
if choice == 'l':
print("Enter your username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username in user_data:
print(f"Welcome back, {username}!")
return username
else:
print("Username does not exist. Please register first.")
elif choice == 'r':
print("Enter your desired username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username not in user_data:
register_user(username)
print(f"User {username} registered successfully!")
return username
else:
print("Username already exists. Please choose a different one.")
elif choice == 'h':
print("\n--- High Scores ---")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
if mode in high_scores:
name, score = high_scores[mode]
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: {name} with {score} points")
else:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: No scores yet")
print("-------------------")
elif choice == 'q':
print("Exiting. Goodbye!")
sys.exit(0)
else:
print("Invalid choice. Please enter 'l', 'r', 'h', or 'q'.")
except EOFError:
print("\nInput error: Please ensure you're running this in an interactive console.")
break
except KeyboardInterrupt:
print("\nInput interrupted. Exiting user login.")
break
except Exception as e:
print(f"An error occurred: {e}")
break
def guess_the_word(username):
"""Guess the word game."""
while True:
print("\nWelcome to 'Guess the Word'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
if remaining_tries <= 0:
print(f"Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def display_shark(shark):
"""Display the shark's position."""
print("Shark's position:", shark)
def beat_the_shark(username):
"""A simple race game where player guesses letters and compares to a shark opponent."""
while True:
print("\nWelcome to 'Beat the Shark'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
code
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
# Initialize shark string based on difficulty
if difficulty == 'easy':
shark = "﹏﹏﹏𓂁"
elif difficulty == 'medium':
shark = "﹏﹏﹏﹏﹏𓂁"
else:
shark = "﹏﹏﹏﹏﹏﹏﹏﹏𓂁"
display_shark(shark)
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess! The shark is still behind!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points. The shark moves forward!")
# Remove one '﹏' from the shark string
if len(shark) > 1:
shark = shark[:-1]
if len(shark) <= 1:
shark = '𓂁'
display_shark(shark)
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! The shark couldn't catch you!")
break
if remaining_tries <= 0:
print(f"The shark caught you! Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def timed_guess_the_word(username):
"""Timed Guess the Word game."""
while True:
print("\nWelcome to 'Timed Guess the Word'!")
print("You have infinite guesses but must guess the word within the time limit.")
code
# Select time limit
while True:
print("Choose a time limit:")
print("1. 30 seconds")
print("2. 1 minute (60 seconds)")
print("3. 1 minute and 30 seconds (90 seconds)")
time_choice = input("Select a time limit (1, 2, 3): ").strip()
if time_choice == '1':
timer_duration = 30
break
elif time_choice == '2':
timer_duration = 60
break
elif time_choice == '3':
timer_duration = 90
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
start_time = time.time()
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
elapsed_time = time.time() - start_time
remaining_time = max(0, timer_duration - elapsed_time)
print(f"Time remaining: {int(remaining_time)} seconds")
if remaining_time <= 0:
print(f"Time's up! The correct word was '{selected_word}'.")
score = 0
break
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
save_high_score(username, score, 'timed')
play_again = input("Do you wish to play again? (yes/no): ").lower()
if play_again != 'yes':
break
def display_high_scores(high_scores):
"""Display the high scores."""
print("\nHigh Scores:")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
if mode in high_scores:
name, score = high_scores[mode]
print(f"{mode_name} mode: {name} with {score} points")
else:
print(f"{mode_name} mode: No scores yet")
def start_menu():
"""Display the start menu and handle user choices."""
while True:
print("\nPick a game mode!")
print("1. Guess the Word: Earn points by guessing the correct letters.")
print("2. Beat the Shark: Race against a shark by guessing the word correctly.")
print("3. Timed Guess the Word: Infinite guesses but beat the timer!")
try:
choice = input("Select a game (1, 2, or 3), or 'q' to quit: ")
code
if choice == '1':
guess_the_word(username)
elif choice == '2':
beat_the_shark(username)
elif choice == '3':
timed_guess_the_word(username)
elif choice.lower() == 'q':
print("Thank you for playing! Goodbye!")
break
else:
print("Invalid choice. Please try again.")
except KeyboardInterrupt:
print("\nInput interrupted. Exiting the game.")
break
start_menu() at the end when it says do you wish to play again add an option that says mainmenu(m) put it all into this code and give me it all together
import random
import os
import sys
import time # Import time for the timer functionality
# Print ASCII Art Banner
ascii_art = """
██╗ ██╗ ██████╗ ██████╗ ██████╗ ██████╗ █████╗ ███╗ ███╗███████╗
██║ ██║██╔═══██╗██╔══██╗██╔══██╗ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
██║ █╗ ██║██║ ██║██████╔╝██║ ██║ ██║ ███╗███████║██╔████╔██║█████╗
██║███╗██║██║ ██║██╔══██╗██║ ██║ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
╚███╔███╔╝╚██████╔╝██║ ██║██████╔╝ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
"""
print(ascii_art)
# Constants
HIGH_SCORES_FILE = 'data/high_scores.txt'
USER_DATA_FILE = 'data/user_data.txt'
# Word lists for different difficulty levels
DIFFICULTY_WORDS = {
'easy': ['cat', 'fish', 'dog', 'bird', 'frog', 'apple', 'table', 'chair', 'book', 'lamp'],
'medium': ['giraffe', 'monkey', 'penguin', 'squirrel', 'elephant', 'dolphin', 'computer', 'pencil', 'candle', 'window'],
'hard': ['chimpanzee', 'extraordinary', 'microorganism', 'unbelievable', 'determination', 'superintendent', 'phenomenon', 'incomprehensible', 'electromagnetic', 'characteristic']
}
# Set number of tries based on difficulty
TRIES = {
'easy': 5,
'medium': 7,
'hard': 10
}
def ensure_data_directory():
"""Ensure the data directory exists."""
if not os.path.exists('data'):
os.makedirs('data')
def load_user_data():
"""Load user data from a file."""
if not os.path.exists(USER_DATA_FILE):
return {}
user_data = {}
with open(USER_DATA_FILE, 'r') as file:
for line in file:
username = line.strip()
user_data[username] = True # Using a dictionary to track registered users
return user_data
def register_user(username):
"""Register a new user."""
ensure_data_directory()
with open(USER_DATA_FILE, 'a') as file:
file.write(username + '\n')
def load_high_scores():
"""Load high scores from a file."""
if not os.path.exists(HIGH_SCORES_FILE):
return {}
high_scores = {}
with open(HIGH_SCORES_FILE, 'r') as file:
for line in file:
parts = line.strip().split(',')
if len(parts) == 3:
difficulty, name, score_str = parts
try:
score = int(score_str)
# Only keep the highest score per difficulty
if difficulty not in high_scores or score > high_scores[difficulty][1]:
high_scores[difficulty] = (name, score)
except ValueError:
continue
return high_scores
def save_high_score(name, score, difficulty):
"""Save player's name and score to a file."""
ensure_data_directory() # Ensure data directory exists
with open(HIGH_SCORES_FILE, 'a') as file:
file.write(f"{difficulty},{name},{score}\n")
def get_word(difficulty):
"""Select a random word from a given difficulty level."""
return random.choice(DIFFICULTY_WORDS[difficulty])
def display_progress(selected_word, guessed_letters):
"""Display the current state of the guessed word."""
display_word = ''
for letter in selected_word:
if letter in guessed_letters:
display_word += letter + ' '
else:
display_word += '_ '
print("\nCurrent word:", display_word.strip())
def user_login():
"""Handle user login, registration, or viewing high scores."""
user_data = load_user_data()
high_scores = load_high_scores() # Load high scores here to show on demand
while True:
try:
print("\nWelcome! Please choose an option:")
print("Login (l)")
print("Register (r)")
print("View High Scores (h)")
print("Quit (q)")
print("Enter your choice: ", end='', flush=True)
choice = sys.stdin.readline().strip().lower()
if choice == 'l':
print("Enter your username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username in user_data:
print(f"Welcome back, {username}!")
return username
else:
print("Username does not exist. Please register first.")
elif choice == 'r':
print("Enter your desired username: ", end='', flush=True)
username = sys.stdin.readline().strip()
if username not in user_data:
register_user(username)
print(f"User {username} registered successfully!")
return username
else:
print("Username already exists. Please choose a different one.")
elif choice == 'h':
print("\n--- High Scores ---")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
if mode in high_scores:
name, score = high_scores[mode]
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: {name} with {score} points")
else:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
print(f"{mode_name} mode: No scores yet")
print("-------------------")
elif choice == 'q':
print("Exiting. Goodbye!")
sys.exit(0)
else:
print("Invalid choice. Please enter 'l', 'r', 'h', or 'q'.")
except EOFError:
print("\nInput error: Please ensure you're running this in an interactive console.")
break
except KeyboardInterrupt:
print("\nInput interrupted. Exiting user login.")
break
except Exception as e:
print(f"An error occurred: {e}")
break
def guess_the_word(username):
"""Guess the word game."""
while True: # outer loop controls replay or main menu or quit
print("\nWelcome to 'Guess the Word'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
if remaining_tries <= 0:
print(f"Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
while True:
play_again = input("Do you wish to play again? (yes/no/m for main menu): ").lower()
if play_again == 'yes':
break
elif play_again == 'm':
return # back to main menu
elif play_again == 'no':
print("Thank you for playing! Exiting game.")
sys.exit(0)
else:
print("Invalid input. Please enter 'yes', 'no', or 'm'.")
def display_shark(shark):
"""Display the shark's position."""
print("Shark's position:", shark)
def beat_the_shark(username):
"""A simple race game where player guesses letters and compares to a shark opponent."""
while True:
print("\nWelcome to 'Beat the Shark'!")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
if difficulty == 'easy':
shark = "﹏﹏﹏𓂁"
elif difficulty == 'medium':
shark = "﹏﹏﹏﹏﹏𓂁"
else:
shark = "﹏﹏﹏﹏﹏﹏﹏﹏𓂁"
display_shark(shark)
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess! The shark is still behind!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points. The shark moves forward!")
if len(shark) > 1:
shark = shark[:-1]
if len(shark) <= 1:
shark = '𓂁'
display_shark(shark)
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! The shark couldn't catch you!")
break
if remaining_tries <= 0:
print(f"The shark caught you! Game over! The correct word was '{selected_word}'.")
score = 0
save_high_score(username, score, difficulty)
while True:
play_again = input("Do you wish to play again? (yes/no/m for main menu): ").lower()
if play_again == 'yes':
break
elif play_again == 'm':
return # back to main menu
elif play_again == 'no':
print("Thank you for playing! Exiting game.")
sys.exit(0)
else:
print("Invalid input. Please enter 'yes', 'no', or 'm'.")
def timed_guess_the_word(username):
"""Timed Guess the Word game."""
while True:
print("\nWelcome to 'Timed Guess the Word'!")
print("You have infinite guesses but must guess the word within the time limit.")
while True:
print("Choose a time limit:")
print("1. 30 seconds")
print("2. 1 minute (60 seconds)")
print("3. 1 minute and 30 seconds (90 seconds)")
time_choice = input("Select a time limit (1, 2, 3): ").strip()
if time_choice == '1':
timer_duration = 30
break
elif time_choice == '2':
timer_duration = 60
break
elif time_choice == '3':
timer_duration = 90
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
if difficulty not in DIFFICULTY_WORDS:
print("Invalid difficulty. Please try again.")
continue
selected_word = get_word(difficulty)
guessed_letters = []
score = 100
remaining_tries = TRIES[difficulty]
start_time = time.time()
while remaining_tries > 0:
display_progress(selected_word, guessed_letters)
print(f"Remaining tries: {remaining_tries}")
elapsed_time = time.time() - start_time
remaining_time = max(0, timer_duration - elapsed_time)
print(f"Time remaining: {int(remaining_time)} seconds")
if remaining_time <= 0:
print(f"Time's up! The correct word was '{selected_word}'.")
score = 0
break
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You've already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in selected_word:
print("Good guess!")
else:
remaining_tries -= 1
score -= 10
print("Wrong guess! -10 points")
if all(letter in guessed_letters for letter in selected_word):
print(f"You guessed the word '{selected_word}'! Congratulations!")
break
save_high_score(username, score, 'timed')
while True:
play_again = input("Do you wish to play again? (yes/no/m for main menu): ").lower()
if play_again == 'yes':
break
elif play_again == 'm':
return # back to main menu
elif play_again == 'no':
print("Thank you for playing! Exiting game.")
sys.exit(0)
else:
print("Invalid input. Please enter 'yes', 'no', or 'm'.")
def display_high_scores(high_scores):
"""Display the high scores."""
print("\nHigh Scores:")
modes = ['easy', 'medium', 'hard', 'timed']
for mode in modes:
mode_name = "Timed" if mode == 'timed' else mode.capitalize()
if mode in high_scores:
name, score = high_scores[mode]
print(f"{mode_name} mode: {name} with {score} points")
else:
print(f"{mode_name} mode: No scores yet")
def start_menu():
"""Display the start menu and handle user choices."""
while True:
print("\nPick a game mode!")
print("1. Guess the Word: Earn points by guessing the correct letters.")
print("2. Beat the Shark: Race against a shark by guessing the word correctly.")
print("3. Timed Guess the Word: Infinite guesses but beat the timer!")
try:
choice = input("Select a game (1, 2, or 3), or 'q' to quit: ")
if choice == '1':
guess_the_word(username)
elif choice == '2':
beat_the_shark(username)
elif choice == '3':
timed_guess_the_word(username)
elif choice.lower() == 'q':
print("Thank you for playing! Goodbye!")
break
else:
print("Invalid choice. Please try again.")
except KeyboardInterrupt:
print("\nInput interrupted. Exiting the game.")
break
if __name__ == "__main__":
# Load and display high scores at the start
high_scores = load_high_scores()
display_high_scores(high_scores)
# User login or registration
username = user_login()
# Start main menu
start_menu()
Summary of changes:
Added "m" option at all "Do you wish to play again?" prompts.
User can enter "m" to return to the main menu immediately.
User can enter "yes" to replay the same mode.
User can enter "no" to quit the program.
Added input validation to ask again if user enters anything else.
Let me know if you want me to help with anything else!