repl.it
@Jeremiah32556/

hangman game

Python

No description

fork
loading
Files
  • main.py
  • words.txt
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# Hangman game
import random
WORDLIST_FILENAME = "words.txt"
def loadWords():
   
    print("Loading word list from file...")
    inFile = open(WORDLIST_FILENAME, 'r')
    line = inFile.readline()
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def chooseWord(wordlist):
    return random.choice(wordlist)


wordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed):
    for c in secretWord:
        if c not in lettersGuessed:
            return False
    return True


def getGuessedWord(secretWord, lettersGuessed):
    cword=''
    for c in secretWord:
        if c in lettersGuessed:
            cword+=c
        else:
            cword+='_'
    return cword


def getAvailableLetters(lettersGuessed):
   
    
    import string

    abc=string.ascii_lowercase
    letters=''
    for c in abc:
        if c not in lettersGuessed:
            letters+=c
    return letters
    

def hangman(secretWord):
   
    print('Welcome to the game, Hangman!')
    print('I am thinking of a word that is ', len(secretWord), ' letters long.')
    print("-----------")

    guessesAvailable=8
    lettersGuessed=''
    

    while not isWordGuessed(secretWord,lettersGuessed):

        print('You have', guessesAvailable, 'guesses left.')
        print('Available letters:', getAvailableLetters(lettersGuessed))
        guess=input('Please guess a letter:')
        guesslc=guess.lower()

        if guesslc in lettersGuessed:
            print("Oops! You've already guessed that letter:", getGuessedWord(secretWord,lettersGuessed))

        elif guesslc in secretWord:
            lettersGuessed+=guesslc
            print('Good guess:', getGuessedWord(secretWord,lettersGuessed))

        else:
            print('Oops! That letter is not in my word:', getGuessedWord(secretWord,lettersGuessed))
            lettersGuessed+=guesslc
            guessesAvailable-=1

        print("-----------")
        if guessesAvailable==0:
            print('Sorry, you ran out of guesses. The word was', secretWord , '.')
            return False
        

    print ("Congratulations, you won!")
    return True












secretWord = chooseWord(wordlist).lower()
hangman(secretWord)
Fetching token
?