2
\$\begingroup\$

This game that I semi coded is a little bulky and kind of boring. I want to know if there is anything simple I can do to shrink it and add a little spice to the code.

# Word Jumble
#
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word

import random

# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")


print(
"""
           Welcome to Word Jumble!

   Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)


play=input("Do you want to play? (yes or no)")
while play=="yes":
    # pick one word randomly from the sequence
    word = random.choice(WORDS)
    # create a variable to use later to see if the guess is correct
    correct = word

    # create a jumbled version of the word
    jumble =""
    while word:
        position = random.randrange(len(word))
        jumble += word[position]
        word = word[:position] + word[(position + 1):]

    print("The jumble is:", jumble)
    points=100
    guess = input("\nYour guess: ")
    while guess != correct and guess != "":
        print("Sorry, that's not it.")
        hint=input("Do you need a hint?")
        if hint=="yes":
            points=int(points)-10
            if correct=="python":
                print("Its a snake...")
            elif correct=="jumble":
                print("Rhymes with rumble")
            elif correct== "easy":
                print("This one is so simple!")
            elif correct=="difficult":
                print("This is a hard one... its very ________________")
            elif correct=="answer":
                print("You cant find it? the _________ is ___________")
            elif correct=="xylophone":
                print("It is a toy...")
            print("Thanks for takeing the hint, idiot...")
        guess = input("Your guess: ")

    if guess == correct:
        print("That's it!  You guessed it!\n")
        print("Your score is: "+str(points))
        play=input("Do you want to play again? (yes or no)")
    elif guess== "":
        print("You failed...")
        play=input("Do you want to play again? (yes or no)")


print("Thanks for playing.")

input("\n\nPress the enter key to exit.")
\$\endgroup\$
4
\$\begingroup\$

Some comments from this question still apply here.

You do not respect PEP 8 and you should try to split your code into smaller chunks.

Let's change things little by little :

Data over code

Copied from my other answer

Sometimes, you have to write a lot of code because "Hey, I have a lot of logic to write, I have to write code, that's the point of programming" but the point is more to keep things simple and to use the right tool (which is not always code) for the right thing.

Here you are comparing strings to get the relevant hint for an answer. It would be much clearer to store the hint are the words together in a structure. At the moment, I've decided to store this in a list of tuple (a dictionnary would also have done the trick).

WORDS = (
    ("python", "Its a snake..."),
    ("jumble", "Rhymes with rumble"),
    ("easy", "This one is so simple!"),
    ("difficult", "This is a hard one... its very ________________"),
    ("answer", "You cant find it? the _________ is ___________"),
    ("xylophone", "It is a toy..."),
)
...
    # pick one word randomly from the sequence
    word, word_hint = random.choice(WORDS)
...
        print(word_hint)
        print("Thanks for takeing the hint, idiot...")

Extracting logic in a function

The logic to create a jumble version looks like it could and should be put in a function on its own.

Also we can reuse already existing functions : shuffle.

Now, the whole code is much simpler (also, you don't need word AND correct) :

def get_jumble_word(word):
    l = list(word)
    random.shuffle(l)
    return ''.join(l)

...
    word, word_hint = random.choice(WORDS)
    print("The jumble is:", get_jumble_word(word))

A bif of logic

You have :

while guess != word and guess != "":
    # code with no break
if guess == word:
    foo()
elif guess == "":
    bar()

After the loop, we know that condition guess != word and guess != "" is not true anymore (because we would have stayed in the loop otherwise). In order for this condition not to be true, we must have : guess == word or guess == "".

Thus, if condition guess == word in the if branch is not true, we always go in the guess == "" part.

You can rewrite this :

if guess == word:
    foo()
else:
    assert guess == ""
    bar()

Do not repeat yourself

Do not repeat yourself.

Do not repeat yourself.

You have the same last line in both branches of :

if guess == word: 
    print("That's it!  You guessed it!\n") 
    print("Your score is: " + str(points)) 
    play = input("Do you want to play again? (yes or no)") 
else: 
    print("You failed...") 
    play = input("Do you want to play again? (yes or no)")

It probably should be :

if guess == word: 
    print("That's it!  You guessed it!\n") 
    print("Your score is: " + str(points)) 
else: 
    print("You failed...") 
play = input("Do you want to play again? (yes or no)")

More functions

You can define a function to handle getting the yes value from the user, one to handle a game, one to handle the interface (asking yes/no between games) :

def get_input_in_list(prompt, values):
    while True:
        s = input(prompt + '(Your choices are : ' + ', '.join(values) + ')')
        if s in values:
            return s

def game():
    # pick one word randomly from the sequence
    word, word_hint = random.choice(WORDS)
    print("The jumble is:", get_jumble_word(word))
    points = 100
    guess = input("\nYour guess: ")
    while guess != word and guess != "":
        print("Sorry, that's not it.")
        hint = input("Do you need a hint?")
        if hint == "yes":
            points = int(points) - 10
            print(word_hint)
            print("Thanks for takeing the hint, idiot...")
        guess = input("Your guess: ")

    if guess == word:
        print("That's it!  You guessed it!\n")
        print("Your score is: " + str(points))
    else:
        print("You failed...")

def main():
    while input("Do you want to play? (yes or no)") == "yes":
        game()

if __name__ == "__main__":
    main()

Also, I took this chance to add an if main guard.

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.