Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Kresher
Sep 11, 2001
Permanent Patient
Another python newbie assignment question time! (Yay, me)

I'm programming a hangman game, and I've got a working version that has 1 flaw I cannot fix.

code:
import random
def read_list_from_file():
    fileRef = open("ty_words.txt","r") # opening file to be read
    localList=[]
    for line in fileRef:
        word = line[0:len(line)-1]  # eliminates trailing '\n'
                                    # of each line (or last character
                                    # if it is the last line of the file)
                                    
        localList.append(word.lower())  # adds word to list in lower case
        
    fileRef.close()
    return localList

def greetings():
    str_response = raw_input("\nDo you want to play? Y- yes, N - no: ")
    if str_response == "y" or str_response == "Y":
        bool_response = True
    else:
        bool_response = False
    return bool_response   

def ask_user_guess():
    print "".join([((ch in letters) and ch or "-") for ch in word])
    guess = raw_input("Please guess a letter/word (%d/%d): " % (guesses, max_try))
    return guess
def good_bye():
    print " Good bye! "

wants_to_play = greetings()

while wants_to_play:

    guesses = 0
    max_try = 6
    word = random.choice(read_list_from_file()) #a word from ty_words.txt is
    letters = []                                #picked
    
    while (guesses<max_try):     #playing until won == True or
        guess = ask_user_guess() #the players makes 6 wrong guesses
        if guess not in word:
            print "You've made a wrong guess."
            guesses+=1 
            continue #only occur syntactically nested in a for or while loop
                     #couldn't use this in a function and make the program work
        if len(guess)>1:
            print "\nYou've guessed the whole word: %s" % (guess)
            if guess.strip() == word: #compares the word guess against the word
                print "\nYour lucky guess is correct!"
            else:
                print "\n Too bad, you were wrong."
        for ch in guess:
            letters.append(ch)
        if set(letters) == set(word):
            print "\nCongratulations, you win!"
            break
        else:
            print "You've guessed wrong too many times"

    wants_to_play = greetings()

good_bye()
note: I'm importing a list of words from a text file.

My prof's objective was to familiarize us with the top level programming using functions.

However, I cannot use the functions to syntactically add 1 to the variable 'guesses', using the continue statement.

Also, when the user makes 6 wrong guesses, I want the program to print "You've guessed wrong too many times.", but it just skips that part and heads back to greetings(). (Not to mention the fact that the wrong guess indicator only goes to (5/6))

I've made a nightmarish hack job that has very little top level programming, and it's going to be a bitch to draw the flow chart for, but I'm drat proud of it.

If you guys could give me some advice as to accomplish the task I wish to do, I'd be really grateful.

Adbot
ADBOT LOVES YOU

Kresher
Sep 11, 2001
Permanent Patient
Ok, thanks for the advice trashmatic.

This is what I've got after working on the program some more (before reading the reply)

code:
import random
def read_list_from_file():
    fileRef = open("ty_words.txt","r") # opening file to be read
    localList=[]
    for line in fileRef:
        word = line[0:len(line)-1]  # eliminates trailing '\n'
                                    # of each line (or last character
                                    # if it is the last line of the file)
                                    
        localList.append(word.lower())  # adds word to list in lower case
        
    fileRef.close()
    return localList

def greetings():
    str_response = raw_input("\nDo you want to play? Y- yes, N - no: ")
    if str_response == "y" or str_response == "Y":
        bool_response = True
    else:
        bool_response = False
    return bool_response   

def ask_user_guess():
    print "".join([((ch in letters) and ch or "-") for ch in word])
    guess = raw_input("Please guess a letter/word (%d/%d): " % (guesses, max_try))
    return guess

def good_bye():
    print " Good bye! "

def check_user_guess():
    if len(guess)>1:
        print "\nYou've guessed the whole word: %s" % (guess)
        if guess.strip() == word: #compares the word guess against the word
            print "\nYour lucky guess is correct!"
        else:
            print "\nToo bad, you were wrong."

def fill_in_blanks():
    for ch in guess:
        letters.append(ch)

def user_win_loss():
    if set(letters) == set(word):
        print "\nCongratulations, you win!"
    else:
        print "You've guessed wrong too many times"
    

wants_to_play = greetings()

while wants_to_play:

    guesses = 0
    max_try = 6
    word = random.choice(read_list_from_file()) #a word from ty_words.txt is
    letters = []                                #picked
    user_won = False
    
    while (guesses<max_try) and (user_won == False):     #playing until won == True or
        guess = ask_user_guess() #the players makes 6 wrong guesses
        if guess not in word:
            print "You've made a wrong guess."
            guesses+=1 
            continue #only occur syntactically nested in a for or while loop
                     #couldn't use this in a function and make the program work
        check_user_guess()
        fill_in_blanks()
        
    user_won = user_win_loss()

    wants_to_play = greetings()

good_bye()
I didn't really touch it much, other than cutting out bits of the code to fit the top level programming model. (Also added the variable user_won to control)

I think I should be able to draw a flow chart now and think it through, but I better study for the midterm on wednesday first.

Kresher
Sep 11, 2001
Permanent Patient

trashmatic posted:

Try to clarify with your teacher what the "top level programming model" (I found nothing on Google) means with respect to your code. I think it's leading you further away from a solution. Functions are generally to take input data, perform a specific task, and return data -- not act as cutely named containers for fragments of your program's control structures.

The following is what my prof showed us as an example of "top level" programming.

code:
##  One player guessing game :
##
##  The program picks a number and the user (player) guesses
##
##  Version 2: (added to version 1)
##        MANY GAMES DEPENDING ON USER: nested while loops
##        additions wrt version 1: marked with v2
##        
##  Version 1:
##        only one game
##        no limitation of number of times the user guesses
##        hence the user cannot lose and
##        the program finishes when the user (player) wins
## 
##  1st look at USAGE OF FUNCTIONS AND SUBROUTINES (THAT WE CREATE):
##  FUNCTIONS WITH NO PASSAGE OF PARAMETERS
##  (notice the parenthesis with no variables inside)


## SUBROUTINES AND FUNCTIONS

def welcome():
    print "Welcome to the guessing game - Version 2!\n"

## only new function needed for v3
def invite_user_to_play():
    str_response = raw_input("\nDo you want to play? Y- yes, N - no: ")
    if str_response == "y" or str_response == "Y":
        bool_response = True
    else:
        bool_response = False
    return bool_response        ## both variables,
                                ## str_response and bool_response
                                ## are LOCAL to the function
                                ## invite_user_to_play()

def program_picks():
    num = random.randint(1,10)  ## num is a variable LOCAL to
                                ## the function program_picks
    return num

def ask_user_for_number():
    num = int(raw_input("Please enter a number between " + str(1) \
                        + " and " + str(10) + ": "))
    return num

def check_if_user_guessed():
    return  (user_number == the_number)

def inform_user_won():
    print " Dear player, you have won! "

def say_good_bye():
    print " Good Bye!"

    

## TOP LEVEL
    
## general initializations at top level
import random


welcome()

wants_to_play = invite_user_to_play()  # v2

while   wants_to_play:                 # v2

    the_number = program_picks()
    won = False

    while (not won):   # same as:  while (won == False):

        user_number = ask_user_for_number()

        won = check_if_user_guessed()   ## this will eventually change
                                        ## the variable won to
                                        ## the boolean value True
        

    # here the inner while is over, therefore the user won
    inform_user_won()
    
    
    wants_to_play = invite_user_to_play()   # v2
    

# here the outer while loop is over, since
# the user does not want to play any more, we say good_bye
say_good_bye()   # v2
    
### END OF PROGRAM
Am I doing it right? The big chunks of codes are subroutines, no?

Kresher
Sep 11, 2001
Permanent Patient
Yes, my class will be learning about local&global variables on friday after tomorrow's midterm.

Also, my prof told us that she usually codes/teaches in Java, and this is her first time teaching the introductory CS course.

  • Locked thread