Skip to content

Instantly share code, notes, and snippets.

@NGWi
Forked from acstrahl/step_by_step_loop.ipynb
Last active March 27, 2025 18:31
Show Gist options
  • Save NGWi/9f64f12944e67c9b9a3bbaa30c36bc2f to your computer and use it in GitHub Desktop.
Save NGWi/9f64f12944e67c9b9a3bbaa30c36bc2f to your computer and use it in GitHub Desktop.
Dataquest Project Lab Walkthrough: Word Raider
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
import random
from faker import Faker
fake = Faker()
# Select random word
selected_word = None
try:
word_bank = open('words.txt', 'a')
except FileNotFoundError:
word_bank = open('words.txt', 'w')
# Attempt to generate a new one:
for _ in range(100):
word = fake.word()
if len(word) == 5:
selected_word = word
word_bank.write(word + '\n') # Save for another time
break
# Give up and use one from the word bank
else:
selected_word = random.choice(word_bank)
word_bank.close()
game_name = "Word Raider"
# Defining game information
incorrect_letters = []
misplaced_letters = []
max_turns = 6
used_turns = 0
print(selected_word)
print(f"Welcome to {game_name}!")
print(f"The word to guess has {len(selected_word)} letters.")
print(f"You have {max_turns} turns to guess the word!")
while used_turns < max_turns:
guess = input("Guess a word: ").lower().strip()
if guess == "stop":
break
if len(guess) != len(selected_word) or not guess.isalpha():
print("Please enter a 5 letter word.")
continue
output = ""
for letter, comparison in zip(guess, selected_word):
if letter == comparison:
output += letter + " "
if letter in misplaced_letters:
misplaced_letters.remove(letter)
continue
elif letter in selected_word:
if letter not in misplaced_letters:
misplaced_letters.append(letter)
else:
if letter not in incorrect_letters:
incorrect_letters.append(letter)
output += "_ "
if guess == selected_word:
print("\nCongratulations you guessed the word!")
break
used_turns += 1
if used_turns == max_turns:
print(f"Game over, you lost. The word was: {selected_word}")
break
print()
print(output)
print("You guessed:", guess)
print("Misplaced letters: ", misplaced_letters)
print("Incorrect letters: ", incorrect_letters)
print(f"You have {max_turns - used_turns} turns left.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment