# word_guessing_game.py

import random

def readFile(path):
    # copied from the 110 course notes
    with open(path, 'rt', encoding="ascii", errors="surrogateescape") as f:
        return f.read()

def getMidsizedWords(words, lo, hi):
    # takes a multiline list of words, and returns
    # another one that only contains words with between
    # lo and hi (inclusive) number of characters
    result = ''
    for word in words.splitlines():
        if (not word.startswith('#')):
            if ((len(word) >= lo) and (len(word) <= hi)):
                result += word + '\n'
    return result

def getWords():
    allWords = readFile('10k_common_words.txt')
    if (getWordLengths() == 'short'):
        shortestWordLength = 4
        longestWordLength = 7
    else:
        shortestWordLength = 10
        longestWordLength = 15
    words = getMidsizedWords(allWords, shortestWordLength, longestWordLength)
    return words

def getRandomWord(words):
    # it would be more efficient if we called
    # splitlines only once.  But this is more
    # in keeping with what we have learned so far...
    return random.choice(words.splitlines())

def getWordLengths():
    while True:
        response = input('Word lengths? [s]hort or [l]ong ')
        if (response == 's'):
            return 'short'
        elif (response == 'l'):
            return 'long'
        else:
            print('Illegal response.  Please try again.')

def keepPlaying():
    while True:
        response = input('Keep playing? [y]es or [n]o ')
        if (response == 'y'):
            return True
        elif (response == 'n'):
            return False
        else:
            print('Illegal response.  Please try again.')

def getGuess():
    while True:
        response = input('Next guess (a letter) --> ')
        if (len(response) != 1):
            print('Please enter a single letter!')
        elif (response.isalpha() == True):
            return response.upper()
        else:
            print('Illegal response.  Please enter a letter!')

def getGuessedWord(targetWord, guesses):
    result = ''
    for c in targetWord:
        if (c in guesses):
            result += c
        else:
            result += '-'
    return result

def playRound(targetWord):
    targetWord = targetWord.upper()
    guessedWord = '-' * len(targetWord)
    guesses = ''
    maxWrong = 5
    wrong = 0
    while ((wrong < maxWrong) and (guessedWord != targetWord)):
        print()
        print('Word so far:', guessedWord)
        print('You have up to', (maxWrong - wrong), 'wrong guesses remaining')
        guess = getGuess()
        if (guess in guesses):
            print('You already guessed that!')
            wrong += 1
        else:
            guesses += guess
            if (guess in targetWord):
                guessedWord = getGuessedWord(targetWord, guesses)
            else:
                print('Sorry, not in the word')
                wrong += 1
    if (wrong == maxWrong):
        print('Oh no, no more guesses.  The word was:', targetWord)
        return False
    else:
        print('You got it!  The word is:', targetWord)
        return True

def playWordGuessingGame():
    words = getWords()
    rounds = wins = 0
    while True:
        rounds += 1
        if (playRound(getRandomWord(words)) == True):
            wins += 1
        print()
        print('Rounds:', rounds)
        print('Wins:', wins)
        if (keepPlaying() == False):
            break
    print('Goodbye!')

playWordGuessingGame()
