Python Program for a Word Scramble Game
Beginner · Games and random numbers
In a word scramble game the letters of a word are mixed up, and the player has to work out the original word. This program scrambles each word with the random module, checks a set of sample guesses, and keeps score.
Program
word_scramble.py
import random
words = ["python", "school", "garden", "planet", "rocket"]
guesses = ["python", "scholo", "garden", "plane", "rocket"] # the player's answers
# To play for real: guess = input("Unscramble it: ").lower()
score = 0
for i in range(len(words)):
word = words[i]
letters = list(word)
random.shuffle(letters)
scrambled = "".join(letters)
while scrambled == word: # never show the word unscrambled
random.shuffle(letters)
scrambled = "".join(letters)
print(f"Word {i + 1}: {scrambled.upper()} guess: {guesses[i]}", end=" ")
if guesses[i] == word:
print("Correct!")
score += 1
else:
print("Wrong, it was", word)
print("Score:", score, "out of", len(words))
Output
Word 1: PYNOTH guess: python Correct! Word 2: OSOHCL guess: scholo Wrong, it was school Word 3: NAEDRG guess: garden Correct! Word 4: NTELPA guess: plane Wrong, it was planet Word 5: TKROEC guess: rocket Correct! Score: 3 out of 5
How it works
list(word)splits the word into a list of letters, becauserandom.shuffle()can mix up a list but not a string."".join(letters)glues the shuffled letters back into a string.- The
whileloop shuffles again if the letters happen to land back in the original order. - Each guess is compared with the real word, and
scorecounts the correct ones. - The scrambled letters change on every run, but the score is always 3 out of 5, since the guesses are fixed.
Another way to write it
Using random.sample()
Using random.sample()
import random
word = "computer"
scrambled = "".join(random.sample(word, len(word)))
print("Scrambled:", scrambled)
print("Same letters as the word?", sorted(scrambled) == sorted(word))
Output
Scrambled: mcopuert Same letters as the word? True
random.sample(word, len(word)) returns all the letters of the string in a random order in one step, and comparing the sorted letters shows that only their order changed.
Try it yourself
After a wrong guess, give a hint by printing the first letter of the word.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises