Python Forum
Hangman game, feedback appreciated
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Hangman game, feedback appreciated
#1
I've been taking the OpenClassroom Python course and the recent assignment was a Hangman with several specific requests:
- there should be separate files such as main, functions, etc.
- it should handle the case where the file for player scores doesn't exist and create one

I've tried a few things, my code is running (there might be mistakes I didn't spot when trying it, though). However, since just reading the corrected version is not everything and being a beginner I'd really like to know what I've done wrong (or right) and what could be improved in terms of readability, maintainability, general coding practise and so on.

Feedback greatly appreciated.

PS: being new to this forum I couldn't find how to directly upload .py and .txt files, I'll try looking harder for it.


### THE HANGMAN - MAIN ###
import re
import pickle
from random import randrange
from hangmanFunctions import *  #custom module


nextStep = False
while not nextStep:
    usrName = input("Welcome to the Hangman's game, please enter your name:\n")
    print("Your name is {}, correct? Y/N.\n".format(usrName))
    answ = input("- ")
    validAnsw = isLetter(answ)
    if validAnsw and answ == "y":
        nextStep = True
    elif validAnsw and answ == "n":
        print("Okay, let's try again.\n")
    else:
            print("You should enter a single letter. Let's try again.\n")
            
#open pickledDict, if not there, create file with empty dict
try:
    userScoresDict = unpickleObj()
except FileNotFoundError:
    userScoresDict = {}
    pickleObj(userScoresDict)
    
#check if user exists in dict, if not creates entry
usrInDict = keyInDict(usrName, userScoresDict)
if usrInDict:
    print("You've already been playing and your currents score is {}.\n".format(
        userScoresDict[usrName]))
else:
    print("This is the first time you're playing: welcome!\n")
    userScoresDict[usrName] = 0     #adding usr to dict
    
score = userScoresDict[usrName] #creating score var

print("You will be given a word and must guess it in less than 8\
 strokes. Ready? let's start!\n")

#game loop starts #
ctd = True
while ctd:
    secretW = generateWord() #picking random word
    secretW = secretW.strip()

    #creating the current word with "*" for each letter
    i = 1
    currentW = "*"
    while i < (len(secretW)):
        currentW += "*"
        i += 1
    print("\t{}-letter word : {}\n".format((len(secretW)), currentW))

    #guessing part for user
    strokes = 1
    found = False
    while not found and (strokes <= 8):
        usrInput = input("- ")
        if len(usrInput) == len(secretW):
            currentW = usrInput
            currentW = currentW.strip()     #in case there's any extra space
            if currentW == secretW:
                found = True
                print("Congratulations, you win!")
            else:
                print("Sorry, maybe that was too soon.\n")
        elif re.search(usrInput, secretW) is not None: #if anything matches
            currentW = matchingLW(usrInput, currentW, secretW)
            print("{}\n".format(currentW))
            if currentW == secretW:
                found = True
                print("Congratulations, you win!")
        elif re.match(usrInput, secretW) is None:
            print("Nope, sorry")
        if strokes == 8:
            print("Sorry, 8 strokes, game over.\n\The word was {}.".format(secretW))
        strokes += 1
    if (strokes == 8) and not found:
        score -= 5  #losing points for not finding
    else:
        score += (8-strokes)    #handling the score

    #asking if usr wishes to continue playing or not
    gotAnsw = False
    while not gotAnsw:
        print("So, {}, would you like to play again? Y/N\n".format(usrName))
        answ = input("- ")
        answ = answ.casefold()
        if answ == "y":
            ctd = True
            gotAnsw = True
        elif answ == "n":
            ctd = False
            gotAnsw = True
        else:
            print("Sorry, couldn't read your answer, let's try again.\n")
            
#saving current player's score to dict
userScoresDict[usrName] = score
print("Your score is now {}. See you soon.\n".format(userScoresDict[usrName]))
pickleObj(userScoresDict)   #saves current dict to file
### FUNCTIONS FOR HANGMAN GAME ###
import re
from random import randrange
import pickle


def keyInDict(myKey, myDict):
    """
    Checks whether the given key exists in given dict,
    returns True if so, False otherwise
    """
    if myKey in myDict:
            return True
    else:
            return False    


def pickleObj(myObject):
    """
    Stores a serialized objet into a pickled file
    """
    with open("scores", "wb") as fh:    #file is "scores"
        pickle.dump(myObject, fh, protocol=pickle.HIGHEST_PROTOCOL)


def unpickleObj():
    """
    Reads from a pickled file and returns the serialized object
    """
    with open("scores", "rb") as fh:    #file is "scores"
        myUnpickledObj = pickle.load(fh)
    return myUnpickledObj


def isLetter(param):
    """
    Checks the variable given in parameter and determines whether
    it's a signle letter or not, returns True if single letter,
    False otherwise
    """
    param = param.lower() #turning into lower case
    param = param.strip() #trimming
    if (len(param) == 1) and (re.match("[a-z]", param) is not None):
            return True #char is alphabetical and single
    else:
        return False


def generateWord():
    """
    Chooses at random a word from the wordbank given in file
    """
    myList = open("wordList.txt").readlines()   #creating list from file
    word = myList[randrange(len(myList))]   #word picked at random from list
    return word


def matchingLW(letter, currentW, secretW):
    """
    Replaces every matched letter in the current word
    """
    secretWList = list(secretW) #turning string into list
    currentWList = list(currentW)   #turning string into list
    i = 0
    while i < len(secretW):
        if letter == secretWList[i]:
            currentWList[i] = letter
        i += 1
    resultW = "".join(currentWList)   #turning list into string
    return resultW 
### And here the content of the wordList ###
abasedly
abashing
abatable
abatises
abattoir
abbacies
abbatial
abbesses
abdicate
abdomens
abdomina
abducens
abducent
abducing
Reply


Messages In This Thread
Hangman game, feedback appreciated - by WolfWayfarer - Jul-16-2018, 08:19 AM
RE: Hangman game, feedback appreciated - by buran - Jul-16-2018, 02:29 PM
RE: Hangman game, feedback appreciated - by buran - Jul-19-2018, 08:59 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  A hangman game. mcmxl22 1 2,120 Oct-07-2019, 02:02 PM
Last Post: ichabod801
  tk hangman game joe_momma 0 2,894 Aug-09-2019, 02:48 PM
Last Post: joe_momma
  Looking for feedback on a game I made MrPucake 7 4,373 Apr-04-2018, 01:53 PM
Last Post: MIPython

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020