patternpythonModerate
Worded Mastermind game in Python
Viewed 0 times
wordedmastermindgamepython
Problem
Just completed a /r/dailyprogrammer challenge. Challenge #238 to be precise.
A Github repository with the wordbank.txt is available here.
```
import random
difficulty = {1: [4, 5, 6], 2: [7, 8],
3: [9, 10, 11], 4: [12, 13],
5: [14, 15]
}
#Keys are the various word lengths for each difficulty (1-5).
acceptedWord = []
#Start a blank list, used in getWords()
def getWords():
while True:
try:
level = int(input("What difficulty would you like? (1,2,3,4,5) "))
break
except (ValueError, KeyError):
print("That is not a number")
#Take a numerical input from the user, attempt to parse it, if it fails, carry on the loop.
num = random.choice(difficulty[level])
#num (used to store word lengths) is a random choice from the available lengths for the selected difficulty.
with open('wordbank.txt', 'r') as file:
#Open the file containing word-bank
for x in map(str.upper, map(str.strip, file.readlines())):
#loop over the stripped down words
if len(x) == num:
acceptedWord.append(x)
#If length of word is equal to random choice from suitable lengths, add it to a list.
#Random index from total number of items in list.
answers = random.sample(acceptedWord, num)
#picks a selection of the available words. Amount of words = word length.
trueWord = answers[random.randint(0, len(answers)-1)]
#trueWord = answer. Random item of the shortlisted avaliable words
print('\n'.join(answers))
#Prints hints.
game(trueWord)
def game(trueWord):
for x in range(0,5):
#The user has 5 guesses
print("Guesses Left: ", 5-x)
userInput = input("Guess: ").upper()
#All guesses/inputs are parsed to uppercase.
userList = list(userInput)
#List of the letters the user inputed
trueList = list(trueWord)
#List of letter of
A Github repository with the wordbank.txt is available here.
```
import random
difficulty = {1: [4, 5, 6], 2: [7, 8],
3: [9, 10, 11], 4: [12, 13],
5: [14, 15]
}
#Keys are the various word lengths for each difficulty (1-5).
acceptedWord = []
#Start a blank list, used in getWords()
def getWords():
while True:
try:
level = int(input("What difficulty would you like? (1,2,3,4,5) "))
break
except (ValueError, KeyError):
print("That is not a number")
#Take a numerical input from the user, attempt to parse it, if it fails, carry on the loop.
num = random.choice(difficulty[level])
#num (used to store word lengths) is a random choice from the available lengths for the selected difficulty.
with open('wordbank.txt', 'r') as file:
#Open the file containing word-bank
for x in map(str.upper, map(str.strip, file.readlines())):
#loop over the stripped down words
if len(x) == num:
acceptedWord.append(x)
#If length of word is equal to random choice from suitable lengths, add it to a list.
#Random index from total number of items in list.
answers = random.sample(acceptedWord, num)
#picks a selection of the available words. Amount of words = word length.
trueWord = answers[random.randint(0, len(answers)-1)]
#trueWord = answer. Random item of the shortlisted avaliable words
print('\n'.join(answers))
#Prints hints.
game(trueWord)
def game(trueWord):
for x in range(0,5):
#The user has 5 guesses
print("Guesses Left: ", 5-x)
userInput = input("Guess: ").upper()
#All guesses/inputs are parsed to uppercase.
userList = list(userInput)
#List of the letters the user inputed
trueList = list(trueWord)
#List of letter of
Solution
Some obvious changes that I'd make:
Reviewed code:
More, I'd split the
- rename all the variables / methods such that they follow the snake_case convention
- remove all the obvious comments and rather add a docstrings into each function instead
- add only one space before and after any operator (except if we're passing some arguments into a function / class)
- after
,you should have a space
- the
acceptedWordlist should be defined within thegetWords()function (the same goes for thedifficultydictionary). (or better yet, remove its declaration completely and use list comprehension instead)
- you should add
if __name__ == '__main__'
user_listis already a list so you don't have to specify the exact same thing here:for item in list(user_list).
- use string formatting when you print something: this:
print(correct_guess, "out of ", len(true_list), "correct.")will become this:print("{} out of {}".format(correct_guess, len(true_list)))
- when you use
withto open a file in read mode, you can omitras that's passed by default.
Reviewed code:
import random
def get_words():
"""Docstring goes here"""
difficulty = {1: [4, 5, 6], 2: [7, 8], 3: [9, 10, 11], 4: [12, 13], 5: [14, 15]}
while True:
try:
level = int(input("What difficulty would you like? (1,2,3,4,5) "))
break
except (ValueError, KeyError):
print("That is not a number")
num = random.choice(difficulty[level])
with open('wordbank.txt') as file:
accepted_word = [x for x in map(str.upper, map(str.strip, file.readlines())) if len(x) == num]
answers = random.sample(accepted_word, num)
true_word = answers[random.randint(0, len(answers) - 1)]
print('\n'.join(answers))
game(true_word)
def game(true_word):
"""Docstring goes here"""
for x in range(0, 5):
print("Guesses Left: {}".format(5 - x))
user_input = input("Guess: ").upper()
user_list, true_list = list(user_input), list(true_word)
if user_input == true_word:
print("Well done, you guessed correctly")
get_words()
correct_guess = 0
for item in user_list:
if item == true_list[user_list.index(item)]:
correct_guess += 1
print("{} out of {}".format(correct_guess, len(true_list)))
print("Bad luck! The answer was: {}".format(true_word))
get_words()
if __name__ == '__main__':
get_words()More, I'd split the
get_words() methods into two methods: get_user_level() and get_words():def get_user_level():
"""Docstring goes here"""
difficulty = {1: [4, 5, 6], 2: [7, 8], 3: [9, 10, 11], 4: [12, 13], 5: [14, 15]}
while True:
try:
level = int(input("What difficulty would you like? (1,2,3,4,5) "))
break
except (ValueError, KeyError):
print("That is not a number")
return random.choice(difficulty[level])
def get_words():
"""Docstring goes here"""
num = get_user_level()
with open('wordbank.txt') as file:
accepted_word = [x for x in map(str.upper, map(str.strip, file.readlines())) if len(x) == num]
answers = random.sample(accepted_word, num)
true_word = answers[random.randint(0, len(answers) - 1)]
print('\n'.join(answers))
game(true_word)Code Snippets
import random
def get_words():
"""Docstring goes here"""
difficulty = {1: [4, 5, 6], 2: [7, 8], 3: [9, 10, 11], 4: [12, 13], 5: [14, 15]}
while True:
try:
level = int(input("What difficulty would you like? (1,2,3,4,5) "))
break
except (ValueError, KeyError):
print("That is not a number")
num = random.choice(difficulty[level])
with open('wordbank.txt') as file:
accepted_word = [x for x in map(str.upper, map(str.strip, file.readlines())) if len(x) == num]
answers = random.sample(accepted_word, num)
true_word = answers[random.randint(0, len(answers) - 1)]
print('\n'.join(answers))
game(true_word)
def game(true_word):
"""Docstring goes here"""
for x in range(0, 5):
print("Guesses Left: {}".format(5 - x))
user_input = input("Guess: ").upper()
user_list, true_list = list(user_input), list(true_word)
if user_input == true_word:
print("Well done, you guessed correctly")
get_words()
correct_guess = 0
for item in user_list:
if item == true_list[user_list.index(item)]:
correct_guess += 1
print("{} out of {}".format(correct_guess, len(true_list)))
print("Bad luck! The answer was: {}".format(true_word))
get_words()
if __name__ == '__main__':
get_words()def get_user_level():
"""Docstring goes here"""
difficulty = {1: [4, 5, 6], 2: [7, 8], 3: [9, 10, 11], 4: [12, 13], 5: [14, 15]}
while True:
try:
level = int(input("What difficulty would you like? (1,2,3,4,5) "))
break
except (ValueError, KeyError):
print("That is not a number")
return random.choice(difficulty[level])
def get_words():
"""Docstring goes here"""
num = get_user_level()
with open('wordbank.txt') as file:
accepted_word = [x for x in map(str.upper, map(str.strip, file.readlines())) if len(x) == num]
answers = random.sample(accepted_word, num)
true_word = answers[random.randint(0, len(answers) - 1)]
print('\n'.join(answers))
game(true_word)Context
StackExchange Code Review Q#156533, answer score: 10
Revisions (0)
No revisions yet.