(In general you will find http://codereview.stackexchange.com more suitable than SO for how-do-I-implement or refactor questions on incomplete code.)
Ok, you first want to prompt user for the difficulty level, convert that to corresponding wordlength, wordlength, then use those in your word-selecting-and-shuffling code.
This could all do with a little refactoring, and since you need to pass some data around, I refactored into a class with setup()
,play()
methods.
Also you only want to read in your wordlist once (e.g. in the class __init__()
method), not every game.
Note the use of the tuple assignment from dict level_to_wordlength
, and the
compact while-loop idiom in choose_random_word()
import random
import string
class Hangman(object):
def __init__(self, wordlist = 'wordlist.txt'):
self.words = [word.strip() for word in open(wordlist)] # store them uppercase
#self.level = None
#self.min_wordlength = None
#self.max_wordlength = None
self.correct_word = None
self.letters_unused = None
def select_difficulty(self):
while True:
level = raw_input("Choose difficulty: E(asy) M(edium) H(ard) : ")
level = (level or " ")[0].upper()
if level in 'EMH':
return level
print "Error: bad level"
# or store it in self.level if needed
def choose_random_word(self, min_wordlength, max_wordlength):
word = ''
while not( min_wordlength <= len(word) <= max_wordlength ): # note the idiom
word = random.choice(self.words)
self.correct_word = word
def setup(self):
level = self.select_difficulty() # or store it in self.level if needed
# Convert level to wordlength constraints... we could use an if..elif ladder for simplicity,
# but here's a neat idiomatic method using tuple assignment from a dict.
level_to_wordlength = {'E': (6,6), 'M': (7,7), 'H': (8,999)}
min_wordlength, max_wordlength = level_to_wordlength[level]
self.choose_random_word(min_wordlength, max_wordlength)
self.letters_unused = set(string.ascii_uppercase)
def play(self):
letters = list(self.correct_word)
random.shuffle(letters)
word = ''.join(letters)
print("Welcome to my game, solve the puzzle.")
print("Let's play")
# ... you do the rest ...
if __name__ == '__main__':
game = Hangman()
game.setup()
game.play()