# Problem Set 2, hangman.py
# Name: 
# Collaborators:
# Time spent:

# Hangman Game
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
import string

WORDLIST_FILENAME = "words.txt"


def load_words():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist



def choose_word(wordlist):
    """
    wordlist (list): list of words (strings)
    
    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code

# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = load_words()


def is_word_guessed(secret_word, letters_guessed):
    '''
    secret_word: string, the word the user is guessing; assumes all letters are
      lowercase
    letters_guessed: list (of letters), which letters have been guessed so far;
      assumes that all letters are lowercase
    returns: boolean, True if all the letters of secret_word are in letters_guessed;
      False otherwise
    '''
    condition = 0
    for letter in secret_word :
        for list_letter in letters_guessed :
            if (letter == list_letter):
                condition += 1
                
            if (condition == len(secret_word) ):
                return True
             
    return False 

#print (is_word_guessed("a", ["b",'c','a']))    

def get_guessed_word(secret_word, letters_guessed):
    '''
    secret_word: string, the word the user is guessing
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string, comprised of letters, underscores (_), and spaces that represents
      which letters in secret_word have been guessed so far.
    '''
    guessed_char = ""
    for j in secret_word : #range (len(secret_word)):
        for i in range(len(letters_guessed)):
            if (letters_guessed[i] == j):
                guessed_char += letters_guessed[i]
                break
            if (i == len(letters_guessed) -1):
                guessed_char += "_ "            
        
    return guessed_char                
#print( get_guessed_word("tortilla", ['u']))      
#print ( get_guessed_word("tortilla", [])) 
def get_available_letters(letters_guessed):
    '''
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string (of letters), comprised of letters that represents which letters have not
      yet been guessed.
    '''
    complement_i = ''
    
    for i in string.ascii_lowercase:
         for j in range(len(letters_guessed)):
            if (letters_guessed[j] == i):
                letters_guessed[j] == ""
                
                break
            elif (j == len(letters_guessed) -1) :
                complement_i += i
                
            
             
    return complement_i

   
def hangman(secret_word):
    '''
    secret_word: string, the secret word to guess.
    
    Starts up an interactive game of Hangman.
    
    * At the start of the game, let the user know how many 
      letters the secret_word contains and how many guesses s/he starts with.
      
    * The user should start with 6 guesses

    * Before each round, you should display to the user how many guesses
      s/he has left and the letters that the user has not yet guessed.
    
    * Ask the user to supply one guess per round. Remember to make
      sure that the user puts in a letter!
    
    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the 
      partially guessed word so far.
    
    Follows the other limitations detailed in the problem write-up.
    '''
    num_guesses = 6
    letters_guessed = [""]    
    letters_left = ""
    prov_variable = get_guessed_word(secret_word, letters_guessed)
    vowels = ["a","e","i","o","u"]
    warnings = 3
    print ("welcome to the game hangman" , "\n" , "I am thinking of a word that is", len(secret_word) , "letters long" ,"------------------------------------------", "\n" ,"Available letters:" , string.ascii_lowercase )

    while num_guesses != 0 :
        print ( "\n" ,"You have", num_guesses , "guesses left" , "\n", "you have", warnings , "warnings left")
        user_input = str.lower(input("Please guess a letter: "))
        
        if( not str.isalpha(user_input)  or len(user_input) != 1 or is_word_guessed(user_input, letters_guessed) ):
            print ("that is not a proper character" , get_guessed_word(secret_word, letters_guessed) , "------------------------------------------")
            warnings -= 1
            if(warnings == 0): 
                print ("You lose a guess, please read CAREFULLY the instructions", get_guessed_word(secret_word, letters_guessed) ,"------------------------------------------" )
                num_guesses -=1
                warnings = 3        
            continue
        letters_guessed.append(user_input)                   
##checks if the word has been guessed        
        if (prov_variable != get_guessed_word(secret_word, letters_guessed)):
            print ("Good guess : " , get_guessed_word(secret_word, letters_guessed))
            prov_variable = get_guessed_word(secret_word, letters_guessed)            
            letters_left = get_available_letters(letters_guessed)
        elif (is_word_guessed(user_input, vowels)):
            print ("nice try : " , get_guessed_word(secret_word, letters_guessed))
            num_guesses -= 2
            letters_left = get_available_letters(letters_guessed)
        else :
            print ("nice try : " , get_guessed_word(secret_word, letters_guessed))
            num_guesses -= 1
            letters_left = get_available_letters(letters_guessed)    
        
        if (get_guessed_word(secret_word, letters_guessed) == secret_word ):
            print ("you won, your score is :" , len(letters_guessed) * num_guesses )
            break
            
        if (num_guesses == 0):
            print ("You lost, the word was", secret_word )
            break
        print ("------------------------------------------", "\n" , "available letters:" , letters_left)
        

# When you've completed your hangman function, scroll down to the bottom
# of the file and uncomment the first two lines to test
#(hint: you might want to pick your own
# secret_word while you're doing your own testing)


# -----------------------------------

def remove_character (character , word):
    new_word = ""
    for letter in word:
        if(letter == character) :
            continue
        else:
            new_word += letter
            
    return new_word        

def match_with_gaps(my_word, other_word):
    '''
    my_word: string with _ characters, current guess of secret word
    other_word: string, regular English word
    returns: boolean, True if all the actual letters of my_word match the 
        corresponding letters of other_word, or the letter is the special symbol
        _ , and my_word and other_word are of the same length;
        False otherwise: 
    '''
    my_word = remove_character(" ",my_word)
    my_word_chars = list(my_word)
    other_word_chars = list(other_word)
    counter = 0
    test_new_word = ""
    test_other_word = ""    
    for letter in my_word_chars :
        
        #if (counter == len(other_word)):
            
            #return False
        if (len(remove_character(" ", my_word)) != len(other_word)):
            return False
        if (letter == "_"):
                                   
            counter +=1            
            continue           
        
        if (letter == other_word_chars[counter]):
                
            test_new_word += letter
            test_other_word += letter            
            counter += 1
            
        else :
            return False
    
    return test_new_word == test_other_word                      
        
          
#print (match_with_gaps("a_ pl_ ", "ample"))      
  

          
            
            
                
    

def show_possible_matches(my_word):
    '''
    my_word: string with _ characters, current guess of secret word
    returns: nothing, but should print out every word in wordlist that matches my_word
             Keep in mind that in hangman when a letter is guessed, all the positions
             at which that letter occurs in the secret word are revealed.
             Therefore, the hidden letter(_ ) cannot be one of the letters in the word
             that has already been revealed.

    '''
    bol = 0
    for word in wordlist :
        if (match_with_gaps(my_word, word)):
            print (word)
            bol = 1
        
    if (bol == 0 ): 
        print("no hay")



def hangman_with_hints(secret_word):
    '''
    secret_word: string, the secret word to guess.
    
    Starts up an interactive game of Hangman.
    
    * At the start of the game, let the user know how many 
      letters the secret_word contains and how many guesses s/he starts with.
      
    * The user should start with 6 guesses
    
    * Before each round, you should display to the user how many guesses
      s/he has left and the letters that the user has not yet guessed.
    
    * Ask the user to supply one guess per round. Make sure to check that the user guesses a letter
      
    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the 
      partially guessed word so far.
      
    * If the guess is the symbol *, print out all words in wordlist that
      matches the current guessed word. 
    
    Follows the other limitations detailed in the problem write-up.
    '''
    num_guesses = 6
    letters_guessed = [""]    
    letters_left = ""
    prov_variable = get_guessed_word(secret_word, letters_guessed)
    vowels = ["a","e","i","o","u"]
    warnings = 3
    print ("welcome to the game hangman" , "\n" , "I am thinking of a word that is", len(secret_word) , "letters long" ,"------------------------------------------", "\n" ,"Available letters:" , string.ascii_lowercase )

    while num_guesses != 0 :
        print ( "\n" ,"You have", num_guesses , "guesses left" , "\n", "you have", warnings , "warnings left")
        user_input = str.lower(input("Please guess a letter: "))
        if(user_input == "*"):
            show_possible_matches(get_guessed_word(secret_word, letters_guessed))
            continue
        if( not str.isalpha(user_input)  or len(user_input) != 1 or is_word_guessed(user_input, letters_guessed) ):
            print ("that is not a proper character" , get_guessed_word(secret_word, letters_guessed) , "------------------------------------------")
            warnings -= 1
            if(warnings == 0): 
                print ("You lose a guess, please read CAREFULLY the instructions", get_guessed_word(secret_word, letters_guessed) ,"------------------------------------------" )
                num_guesses -=1
                warnings = 3        
            continue
        letters_guessed.append(user_input)                   
##checks if the word has been guessed        
        if (prov_variable != get_guessed_word(secret_word, letters_guessed)):
            print ("Good guess : " , get_guessed_word(secret_word, letters_guessed))
            prov_variable = get_guessed_word(secret_word, letters_guessed)            
            letters_left = get_available_letters(letters_guessed)
        elif (is_word_guessed(user_input, vowels)):
            print ("nice try : " , get_guessed_word(secret_word, letters_guessed))
            num_guesses -= 2
            letters_left = get_available_letters(letters_guessed)
        else :
            print ("nice try : " , get_guessed_word(secret_word, letters_guessed))
            num_guesses -= 1
            letters_left = get_available_letters(letters_guessed)    
        
        if (get_guessed_word(secret_word, letters_guessed) == secret_word ):
            print ("you won, your score is :" , len(letters_guessed) * num_guesses )
            break
            
        if (num_guesses == 0):
            print ("You lost, the word was", secret_word )
            break
        print ("------------------------------------------", "\n" , "available letters:" , letters_left)
        

# When you've completed your hangman_with_hint function, comment the two similar
# lines above that were used to run the hangman function, and then uncomment
# these two lines and run this file to test!
# Hint: You might want to pick your own secret_word while you're testing.


if __name__ == "__main__":
    # pass

    # To test part 2, comment out the pass line above and
    # uncomment the following two lines.
    
    #secret_word = choose_word(wordlist)
    #hangman(secret_word)

   
    
    # To test part 3 re-comment out the above lines and 
    # uncomment the following two lines. 
    
    secret_word = choose_word(wordlist)
    hangman_with_hints(secret_word)
