2.3 Implementation into PBL Project
import pandas as pd
import random
import sys
# student-developed procedure update_progress, includes sequencing, selection, and iteration.
def update_progress(letter, word, blanks, progress):
for i in range(len(word)):
if letter == word[i]:
blanks[i*2] = word[i]
# keeps track of progress, if progress = word, the user has won
progress[i] = word[i]
words = pd.read_json("files/words.json")
word = random.choice(words["words"].values)
lives = 7
# creates a list, number of blanks depends on length of the word
# the blanks list and the progress list stores the number of letters that the user has guessed correctly (data abstraction), list is used rather than defining a variable for every single letter (managing complexity?)
blanks = ["_", " "]*len(word)
progress = [" "]*len(word)
while lives > 0:
if "".join(progress) == word:
print("You Win!")
sys.exit()
print("".join(blanks))
user_input = input("Enter a letter.")
if user_input.lower() in word:
print(f"The letter {user_input} is in the word")
update_progress(user_input.lower(),word,blanks,progress)
else:
lives-=1
print(f"Sorry! The letter {user_input} is not in the word.")
if lives == 0:
print(f"You Lost! The word was {word}.")
sys.exit()
Brief Explanation
As shown, this program randomly chooses words from a database file that I created called words.json. The program reads what is inside the file (read_json) and randomly chooses a work from there. This program uses the pandas libraries that we learned about in order to perform this operation. The contents of the words.json file is shown below (generated with PIL!)
from PIL import Image
db = Image.open('../images/wordsdbfile.png')
display(db)