Nathan Bone
Nathan Bone

Reputation: 13

Random word game python 3.5

Hi i'm completely new to programming and have been trying to teach myself python, I have been trying to create a program that selects a word then shuffles the letters and prompts the user to input their guess within 3 tries. The problem I'm having is when a wrong answer is input it reshuffles the letters of the chosen word or returns a completely different word, here is my code:

import random
import sys

##Welcome message
print ("""\tWelcome to the scrambler,
  select [E]asy, [M]edium or [H]ard
  and you have to guess the word""")

##Select difficulty
difficulty = input("> ")
difficulty = difficulty.upper()

##For counting number of guesses it takes
tries = 0

while tries < 3:
    tries += 1

##Starting the game on easy
if difficulty == 'E':
    words = ['teeth', 'heart', 'police', 'select', 'monkey']
    chosen = random.choice(words)
    letters = list(chosen)
    random.shuffle(letters)
    scrambled = ''.join(letters)
    print (scrambled)

    guess = input("> ")

    if guess == chosen:
        print ("Congratulations!")
        break
    else:
        print ("you suck")

else:
    print("no good")
    sys.exit(0)

As you can see I've only gotten as far as easy, I was trying to do it piece by piece and managed to overcome other problems but I can't seem to fix the one I'm having. Any help would be appreciated with the problem I'm having or any other issues you may spot in my code.

Upvotes: 0

Views: 389

Answers (1)

Mathieu Bour
Mathieu Bour

Reputation: 696

A few improvements and fixes for your game.

import random
import sys

# Game configuration
max_tries = 3

# Global vars
tries_left = max_tries

# Welcome message
print("""\tWelcome to the scrambler,
select [E]asy, [M]edium or [H]ard
and you have to guess the word""")


# Select difficulty
difficulty = input("> ")
difficulty = difficulty.upper()

if difficulty == 'E':
    words = ['teeth', 'heart', 'police', 'select', 'monkey']
    chosen = random.choice(words)
    letters = list(chosen)
    random.shuffle(letters)
    scrambled = ''.join(letters)
else:
    print("no good")
    sys.exit(0)

# Now the scrambled word fixed until the end of the game

# Game loop
print("Try to guess the word: ", scrambled, " (", tries_left, " tries left)")

while tries_left > 0:
    print(scrambled)
    guess = input("> ")

    if guess == chosen:
        print("Congratulations!")
        break
    else:
        print("You suck, try again?")
        tries_left -= 1

Tell me if you don't understand something, I would be a pleasure to help you.

Upvotes: 1

Related Questions