How to Not Count Letters Again in Python Hangman

Member Avatar

Well, just to give you a scrap of confidence ... the prof has given yous good advice. Now for the details ... !

First, yous demand to program your code. Brand a plan (sometimes called pseudocode) that doesn't become into the details, just clearly and generally spells out exactly how the game will be played. By "generally", I mean that you can say things like

              ... while True:    alphabetic character = do_turn    if letter in puzzle and letter of the alphabet non in already_used:       add_to_puzzle    else:       increase_misses       print message ...            

And so yous tin can see that the plan doesn't requite any details every bit to HOW some of these steps volition happen; it's simply a large-picture plan.

Do that first. Post it here if you like, and we can give pointers.

And so, create each function. I would practice each role separately and make sure it works past testing it. The testing happens by passing the office typical arguments, and making sure it gives the right return values back.

Thus:

              # Code version 1  def get_secret():     """Become the secret discussion/phrase"""     input = raw_input(word)     # etc.  # examination get_secret give-and-take = get_secret() print discussion            
              # Code version 2  def get_secret():     """Become the secret word/phrase"""     input = raw_input(word)     # etc.  def do_turn(display, misses):    print display    # etc.  # test get_secret discussion = get_secret() print word  # exam do_turn display = "_ETTE_" misses = 2 letter = do_turn(display, misses) print letter of the alphabet            

And and so on. The idea hither is this:

(i) Each function should do *one* thing. (The version of get_secret in your lawmaking tries to do besides much, which paradoxically makes information technology less useful because it has trouble plumbing equipment into the big picture.

(2) The purposes of making functions are to (a) isolate actions similar do_turn so that you can focus on just doing that ane thing (that'southward the main benefit for y'all at present), and (b) creating code that tin be reused elsewhere (that's the chief do good as y'all go further forth).

(3) As y'all write the functions, focus on the requirements your prof has given. Pay attention to what the function should receive, and make sure it returns what it should return. Functions should, for the nearly office, non accept side effects besides returning the value that is specified.

And then: make a programme. Then make functions, one at a time, and test them.

Then finally, put the functions together in your code according to the programme. And information technology should all piece of work out! (hah-hah...debugging oftentimes takes a while :))

Hope information technology helps,
Jeff

Member Avatar

Thanks for the tips, I'm a bit less frustrated now, since yous gave me some ideas that could help me out.

This is my pseudocode that I thought of:

              write "Enter the hugger-mugger word" . . . write estimate a letter while misses is less than 6 and judge is not equal to hugger-mugger word     write guess a letter         if letter of the alphabet guessed is in secret word, then             add letter to brandish and replace underline         else: increase misses by i             print display     if letters guessed equals surreptitious give-and-take         print congratulations, you got the hugger-mugger word            

Here's my new code and then far, and I'yard still stuck on how to get the user to guess a letter and for it to display the underscores and misses from the function "do_turn". I guess I'k having trouble understanding "calling/returning" a function that's defined. Exercise i call in the function or out the function? Likewise, when asking the user for a letter, do i enquire in the function or out?

Then hither'south my code so far, and it isn't running as well smoothly either. Whatsoever help would be great. I really appreciate information technology.

              #stuff the start person sees def get_secret(secret):     """Get the secret word/phrase"""     approximate = raw_input(cloak-and-dagger)           #Stuff the 2nd person sees def do_turn(display,misses):     """     Display the current condition for the user and let them make a guess.     """     misses=0     gauge = raw_input("What alphabetic character would you like to estimate?")     while misses < 6 and guess!=secret:                  for i in range(len(secret)):             if gauge != cloak-and-dagger[i]:                 misses = misses +1             print str(misses)             display = "_ " * len(hugger-mugger)             print display              judge = get_secret(secret) print guess   alphabetic character = do_turn(display,misses) print letter            

Thanks over again!

Member Avatar

Your pseudocode is a great start!

Four things:

(1) You need to not simply write "Enter the secret give-and-take", only also store it.

(2) The final if clause can come outside the loop, since if estimate the cloak-and-dagger give-and-take, then the loop will exit ("fall through").

(iii) All variables need to be initialized. This would be easy to grab in the code, since Python would mutter the outset time you tried to check "misses < 6"

(4) There is no need for the guess a letter outside the loop.

So we might tweak it similar this:

              get hush-hush word initialize misses to 0 initialize guess to "_"*len(secret give-and-take) while misses is less than 6 and judge is non equal to secret discussion     write guess a letter of the alphabet         if letter of the alphabet guessed is in secret give-and-take, so             add letter to display and supersede underline         else: increase misses by 1             print display if letters guessed equals secret give-and-take         print congratulations, you got the secret word else: print sorry            

As you plough the pseudo-code into code, this will get refined.

Member Avatar

Now virtually functions:

Think of a function as a dedicated servant. You "call" the retainer to fetch yous a burger("cheese", "ketchup", "lettuce", "medium-well"), and the servant returns the burger to yous.

And so hither's an example relevant to your code:

              # create the function -- this code gets stored, but not executed. def new_display(secret_word, old_guess, letter):          # flip the underground word and the approximate: turn A into _ in secret discussion and _ into A in judge.     while True:         if alphabetic character in secret_word:             index = secret_word.find(letter of the alphabet)             secret_word = secret_word.replace(letter, "_",1)             old_guess = old_guess[:index]+letter+old_guess[alphabetize+i:]         else:             pause     render old_guess  # call the role for testing purposes # initialize variables misses = 0 estimate = "_E__E_" secret = "Letter of the alphabet"  # call the office with single letter letter = "R" gauge = new_display(secret, guess, letter of the alphabet)  # bank check the output if guess == "_E__ER":     impress "R: Exam passed" else:     print "R: Exam failed"  # phone call over again with double letter letter = "T" guess = new_display(secret, gauge, letter)  # check output if guess == "_ETTER":     print "T: Exam passed" else:     print "T: Test failed"  # call with letter not in puzzle letter = "Z" guess = new_display(secret, judge, letter)  # check output if guess == "_ETTER":     impress "Z: Test passed" else:     print "Z: Test failed"            

This is non necessarily the almost elegant style to lawmaking the new_display, but information technology illustrates some things.

First, annotation that when the function is *defined*, nothing happens ... except that the lawmaking for the office is stored in a location labeled "new_display". Annotation that if you later make a variable called "new_display", it will clobber the function! :lol:

Second, notation that nosotros call the function from the main code itself. You can call functions from within other functions as well. But for beginning projects, the usual plan is

def fn1
def fn2

master lawmaking calls fn1 and fn2 as needed

3rd, note that the "arguments" (your prof may use the term "parameters") of the function are the values that the master code must supply to the retainer in club for the servant to do his task. In this example, the retainer needs to know the cloak-and-dagger word, the current guess, and the guessed letter.

Fourth, note that the return value (at the end of the function, although functions can also return from the middle if an early on leave is needed) is the command to our retainer to bring back the requested upshot.

Fifth, note that our retainer has but i job to practice: to run through the secret word, and make full in whatever corresponding position in the guess with the letter of the alphabet given. He doesn't print stuff; he doesn't update the number of misses; he just replaces _ with letter of the alphabet.

So at present, having tasked our servant with this one job, we call him anytime we need his service.

Sixth, notice that any scratch piece of work the retainer does is lost when the part returns. Y'all can see in the definition of new_display() that I have the line secret_word = secret_word.replace(letter, "_",1) . You might recall that this would cause the secret_word to become changed permanently in the main code. Just actually, the function receives a copy of the secret_word, and when the part returns, all of its variables "become out of scope" -- that is, are forgotten.

This is why the return value is so important. Information technology is the just issue that the main code will always see from the function.* The changes to old_guess that happen inside the body of new_display() are not kept; this is why when the main code calls new_display(), it has to clobber guess with the render value: guess = new_display(secret, guess, letter) ; otherwise, those changes volition be lost.

Does that help clear things up?

Jeff

* Not true for mutable objects like lists, simply that'southward some other story.

Member Avatar

At that place's so much info that I'm getting dislocated. From the code I take higher up, I even so don't know why secret is not divers in this code:

              #stuff the first person sees def get_secret(secret):     """Get the undercover give-and-take/phrase"""     clandestine = raw_input(secret)      misses = 0 gauge = "_ "*len(secret) print guess #Stuff the 2nd person sees def do_turn(brandish,misses):     """     Display the electric current status for the user and let them make a estimate.     """      approximate = raw_input("What letter would you like to guess?")     while misses < 6 and guess!=cloak-and-dagger:                  for i in range(len(secret)):             if gauge != secret[i]:                 misses = misses +ane             print str(misses)             display = "_ " * len(secret)             print brandish              guess = get_secret(cloak-and-dagger) print guess   letter = do_turn(brandish,misses) print letter of the alphabet            

I kind of empathize what y'all're saying, merely isn't "secret" stored in the office get_secret? then when i type guess = "_"*len(secret), isn't hugger-mugger divers? This might be asking for too much, just do you think you can set/delete whatsoever is wrong with my code right now so I tin kind of start fresh. Everytime I get frustrated, I can't seem to think and this programme is due tomorrow dark (no sleep for me). I'll proceed working on information technology, and if I effigy information technology out, i'll mail service the updated code. Cheers once more!

Member Avatar

Lamentable for the overload. :) Your code is improving.

Here's a walkthrough of your lawmaking up to the fault:

lines 2-4: the function get_secret is divers. No code is executed yet; no variables are divers.

line half-dozen: misses is ready to 0

line 7: judge is gear up to "_" * len( ... expect, there is no variable called cloak-and-dagger.

So you lot volition definitely have to call get_secret before you try to prepare judge.

Two more than issues, and and so it'll work.

(1) get_secret() should not accept secret as a parameter, since our servant should not have to know the underground in order to get the secret!

(2) get_secret() will have to return the secret in social club for your principal lawmaking to receive it. Sentry the difference hither:

              ## BAD ## >>> def get_secret():     """Become the hugger-mugger give-and-take/phrase"""        cloak-and-dagger = raw_input("Enter the secret word: ")  >>> misses = 0 >>> get_secret() Enter the surreptitious word: phlerm >>> guess = "_"*len(clandestine)  Traceback (nigh recent phone call last):   File "<pyshell#8>", line 1, in <module>     guess = "_"*len(secret) NameError: proper noun 'hole-and-corner' is not defined >>>            

Why the error? Because the variable 'hugger-mugger' is defined inside the office get_secret. It is a local variable; it is in the "namespace" of get_secret(). When get_secret() returns, all of the local variables "get out of telescopic" -- are forgotten. That is, our retainer'south scratchwork is thrown abroad.

So the remedy is to return the of import effect:

              ## Adept ## >>> def get_secret():     secret = raw_input("Enter the secret discussion: ")     return hush-hush  # <<< 1  >>> misses = 0 >>> my_secret = get_secret()  # <<< 2 Enter the secret word: phlerm >>> guess = "-"*len(my_secret) >>> print guess ------ >>> impress my_secret phlerm >>>            

In the line marked <<< ane, the role returns the necessary value. This is its only means of communicating with the exterior code.

In the line marked <<< 2, the main code calls the function and stores the render value in my_secret. This is the just ways that the main code has of communicating with the part.

And so the key is: all of the variables inside the function are individual, or "local". The only connectedness the part has with the outside earth is receiving parameters (when chosen) and returning a value back to the caller.

So here's the modified pair of functions:

              # Define all your functions Starting time earlier the master code.  #stuff the starting time person sees def get_secret():     """Get the hole-and-corner word/phrase"""     secret = raw_input("Enter the secret word: ")     return secret  #Stuff the second person sees # This function was trying to do the whole game.  Your prof'southward directions gave you lot # the blueprint for this function.  Information technology does 1 matter: get the user'southward gauge. def do_turn(brandish, misses):     """     Display the electric current status for the user and let them make a judge.     """     print display     print "You take missed %d times." % misses      guess = raw_input("What letter practice you guess? ")     return estimate  misses = 0 secret = get_secret() print cloak-and-dagger  brandish = "-"*len(secret) letter of the alphabet = do_turn(brandish,misses) print letter            

Hope it helps,
Jeff

Member Avatar

So this is what I accept at present. I wanted to apply your loop for replacing the underscores, but I don't recall I was taught that complexity. Is at that place a way to supplant the underscores using a different method in new_display?

Here'south are the 2 codes for comparison, merely unfortunately mine doesn't work.

#1

              # Ascertain all your functions Outset before the main code. #stuff the first person sees def get_secret():     """Become the surreptitious give-and-take/phrase"""     undercover = raw_input("Enter the hush-hush word: ")     return hugger-mugger   #Stuff the second person sees # This function was trying to do the whole game.  Your prof's directions gave yous # the design for this office.  It does one matter: get the user's approximate. def do_turn(display, misses):     """     Display the electric current status for the user and allow them brand a guess.     """     render display     print "You have missed %d times." % misses        #This is where we tin can update the messages guessed def new_display(hush-hush, display, estimate):     """Displays the replacement of underscores with letters that the user has guessed"""     misses = 0     while Truthful:         if gauge in secret:             alphabetize = secret.find(guess)             secret = secret.supplant(letter, "_",1)             display = display[:index]+guess+display[index+1:]         else:             misses = misses+i     return secret,display  misses = 0 hugger-mugger = get_secret() print secret  display = "-"*len(secret) alphabetic character = do_turn(display,misses) print letter  clandestine,display = new_display(secret,brandish,guess) print secret,display            

#2

              # Ascertain all your functions FIRST before the chief code. #stuff the outset person sees def get_secret():     """Go the hole-and-corner word/phrase"""     secret = raw_input("Enter the secret word: ")     return secret   #Stuff the second person sees # This function was trying to exercise the whole game.  Your prof'south directions gave you # the design for this office.  It does one affair: get the user's estimate. def do_turn(brandish, misses):     """     Brandish the electric current status for the user and let them make a guess.     """     render display     impress "You accept missed %d times." % misses        #This is where we tin can update the letters guessed def new_display(underground, display, guess):     """Displays the replacement of underscores with letters that the user has guessed"""     misses = 0     while True:         for i in range (len(undercover)):             if secret[i] == guess:                 print guess             else:                 misses = misses+1     return underground,display  misses = 0 hush-hush = get_secret() impress underground  display = "-"*len(secret) letter = do_turn(brandish,misses) impress letter  secret,brandish = new_display(secret,display,gauge) print secret,display            

I know when i used len(underground), surreptitious isn't defined and so I don't know how to browse the letters for the secret way dorsum in the beginning function.

Now I wish I knew some programming before coming to this course. Anyways, thanks for all your aid Jeff. Much appreciated.

Member Avatar

Non a problem. It's worth it to have people come back and say "It worked! I learned something!"

Allow'southward focus on the new_display part and walk through information technology

              #This is where we can update the letters guessed def new_display(underground, display, estimate):     """Displays the replacement of underscores with messages that the user has guessed"""     misses = 0     while Truthful:         for i in range (len(secret)):             if secret[i] == gauge:                 print judge             else:                 misses = misses+1     render secret,display            

And so imagine dispatching the function and saying, "Here'due south the secret discussion 'phlerm', the current brandish '------', and the estimate 'e'."

At line iv, misses is set to 0. This is NOT the same variable equally 'misses' in the main lawmaking, because it is inside the function. Information technology is a local variable.

At line five, we brainstorm the loop. Since the status will never be false, we'll need to intermission or return out of the loop somewhere...

At line 6, we begin a for-loop. Since our secret word is 'phlerm', the range(len(secret) is [0,i,2,iii,4,5], so we have "for i in [0,ane,2,3,4,v]:"

At line 7, we bank check hugger-mugger against 'e' and print it if information technology is. This volition work out similar this:

i screen
0
1
2
3 e
four
5

otherwise (line 10), misses += ane. So past the time the for loop is done, at that place will exist an e on the screen and misses will exist 5.

And so, because nosotros're done with the for loop, the while loop at present executes again ... printing another e and bringing misses up to ten. And then....

You get the idea. This was definitely not what you had in mind. For 1 thing, the brandish variable never gets updated. For some other, you didn't want to print stuff on the screen.

So what did you lot accept in mind? Write a plan for new_display(). NOTICE that new_display() does non have the responsibleness of keeping track of the misses. That's not its task!

Jeff

Member Avatar

so where in the code should i update misses or display misses? should it be in the part do_turn considering that'southward where teh display gets updated?

i suppose my programme is that while Truthful, if the letter is guessed correctly, it will browse the letters in cloak-and-dagger and if it matches, the alphabetic character guessed would supersede the underscore. the loops nevertheless continues until misses are less than half-dozen or until letters guessed is equal to the secret word. also, for each correct guess, the misses should not increase, therefore i should create an if,elif, else cake?

I guess what i'g likewise dislocated about are where the variables should exist, inside the function or part of the chief code.

Member Avatar

The variables should be within the principal code. All variables inside the function are "local" -- scratchwork, basically -- and will be forgotten when the role returns.

Then the main code is going to keep rails of the undercover, the electric current display, the number of misses, and the user's gauge.

Your plan is more like the program for the overall game rather than for new_display(). What new_display needs to do is simply accept the secret, the current display, and the estimate and return the new brandish. So my plan would be something like

              for i in range(len(secret)):    if the judge is equal to hole-and-corner[i], the new brandish[i] = estimate.    otherwise, the new brandish[i] = erstwhile display[i].  Then return the new brandish            

Run into whether that programme works and then plow information technology into code. The only trick will be that you tin't direct assign to a string (brandish = "h" gives an fault). And so you'll need a different mode to build upwards the new display string.

Jeff

Member Avatar

Yous simply take to update the "display" variable and keep track of misses as in this snippet.

              def new_display(secret, display, gauge, misses):           """Displays the replacement of underscores with letters that the user has       guessed"""       index=secret.discover(guess)       display_list=[ eachltr for eachltr in display ]       if (alphabetize > -1) and (display_list[index]=="_"):  ## non already replaced          display_list[index]=guess          display="".join(display_list)       else:          misses += 1       render brandish, misses            

Information technology would be simplier if "brandish" were declared as a listing and yous only worked with a listing. That would avoid converting to a listing and so converting back to a cord.

Member Avatar

Practiced point wooee, except that his prof specified the function header for new_display as

new_display(secret, brandish, alphabetic character) --> new_display, replacement count.

And then he pretty much has to do information technology as above, except that I left out the part about "replacementcount += i" (Oops)

Jeff

Member Avatar

I changed a bit of stuff here and in that location just the output looks similar i'm getting somewhere. I still can't grasp the idea of how to write a lawmaking creating a variable to call the function to replace the underscore. hither's my code so far:

              #stuff the first person sees def get_secret():     """Get the secret word/phrase"""     hugger-mugger = raw_input("Enter the surreptitious discussion: ")     return undercover   #Stuff the second person sees def do_turn(display, misses):     """     Display the current status for the user and permit them make a approximate.     """     render do_turn     print "You have missed %d times." % misses     guesses = raw_input("What letter would you like to guess?")     return guesses  #This is where we tin update the letters guessed def new_display(hole-and-corner, display, guess):     """Displays the replacement of underscores with letters that the user has guessed"""     while True:         if approximate in secret:             display = display.supersede("_", guess)         else:             misses = misses + 1     return display, judge   hole-and-corner = get_secret() print hush-hush  misses = 0 display = "Words and then far:" + "_"*len(undercover) letter = do_turn(brandish,misses) guesses = do_turn(display, misses) print guesses print letter of the alphabet print display  guess = raw_input("What letter would you like to guess?") display,gauge = new_display(hole-and-corner,display,judge) print brandish,approximate            

and wow, 300 views...i wonder if my fellow classmates are reading this. if so, effort not to coompletely re-create my code incase the prof questions my code being like to others. lol =)

Member Avatar

OK,

(ane) what's the purpose of line 13, "return do_turn"? 'Cause what that does is return the entire office code itself ... not something useful in most cases. I recall if you lot simply take it out, the function works equally needed.

(2) In new_display, line 23 has the effect of replacing the *commencement* _ character with the guess.

(iii) the "while True" loop that starts in line 21 will never exit.

(ii) and (iii) together propose that you want to call up nearly

* How practise you know which _ in guess to change? and
* How do you know when to stop checking and render the result?

(4) What'due south the purpose of calling do_turn twice in lines 34 and 35?

Jeff

Member Avatar

I ever got the impression that I should return the role or variables inside the role in order for me to get an output from information technology in the main code. Should I have my while loop in the main code then? Since information technology will only recognize the start "_", will this be better?

              #This is where nosotros can update the letters guessed def new_display(hush-hush, display, guess):     """Displays the replacement of underscores with letters that the user has guessed"""     misses = 0     while True:         if guess in secret:             for i in range (len(secret)):                 if secret[i] == guess:                     brandish = display.replace("_", guess)                 else:                     misses +=1     return display, guess            

As for returning the part twice, I guess I was wanting to display "Words so far" and the letter guessed. And to update both, I wanted to render the office at split up times. Should I have created more variables within the function and call that variable in the main code?

Sorry, every bit you lot tin come across I actually suck at programming and I tin't hands grasp the thought behind this. =/

Member Avatar

Ya know, my first C coding form, I had to have a Comp Sci friend sit down downwardly and explain in excruciating detail how #include worked. In that location was simply some block that all of the sudden went "Click!" and I was hooked.

I always got the impression that I should return the office or variables within the function in guild for me to get an output from information technology in the main code.

The variables that you care about ... aye, admittedly; return those. That'southward how the role communicates with the code that calls it.

Return the function itself? Never. Or at to the lowest degree, almost never. I've never written code that needed to.

Should I take my while loop in the principal lawmaking and then?

Aye.

Since it will simply recognize the first "_", will this be better?

First stride: accept out the while loop

              #This is where we tin can update the messages guessed def new_display(secret, display, guess):     """Displays the replacement of underscores with letters that the user has guessed"""     misses = 0     if guess in hush-hush:         for i in range (len(secret)):             if secret[i] == guess:                 display = display.supercede("_", judge)             else:                 misses +=ane     render display, guess            

Adjacent step: detect that you never practice annihilation with the variable 'misses'. You don't render it; and once the part returns, it is forgotten. And so you can eliminate it entirely from the lawmaking:

              #This is where we can update the letters guessed def new_display(hush-hush, display, guess):     """Displays the replacement of underscores with letters that the user has guessed"""     if guess in secret:         for i in range (len(secret)):             if secret[i] == estimate:                 brandish = brandish.replace("_", approximate)     return display, guess            

The side by side thing is that you aren't returning what your prof said y'all had to render, which was display and replacement_count. The replacement count was supposed to go along rails of the number of times yous had replaced a certain letter.

              #This is where we tin can update the letters guessed def new_display(undercover, display, gauge):     """Displays the replacement of underscores with letters that the user has guessed"""     rep_count = 0     if guess in secret:         for i in range (len(secret)):             if secret[i] == estimate:                 display = display.replace("_", approximate)                 rep_count += 1     return display, rep_count            

If y'all run this, you will find now that the rep_count returns the right value, but the display is nonetheless wrong. The problem is that you need to find some way of identifying the detail index i where the replacement is supposed to happen.

I liked wooee's suggestion of using a list -- are yous familiar with those?

Or, do you lot know how to exercise string slices?

Jeff

Member Avatar

not familiar with lists, simply i'm familiar with string splicing. i thought that for i in range(len(secret)) already finds which "_" to replace.

my misses don't seem to be updating, and isn't the while loop almost basically the same as the variables inside the new_display office? it feels similar i'm suppose to be using the same lawmaking to proceed the while loop running until the word is guessed(or under vi tries)

does this while loop in the main lawmaking expect anything remotely right?

              #This is where we can update the messages guessed def new_display(secret, brandish, estimate):     """Displays the replacement of underscores with letters that the user has guessed"""     rep_count = 0     if estimate in clandestine:         display = brandish.replace("_", guess)     else:         rep_count = rep_count + one     return display, rep_count    undercover = get_secret() print hole-and-corner   judge = raw_input("What letter would you lot similar to guess?") misses = 0 display = "Words then far:" + "_"*len(secret) letter = do_turn(display,misses) while (misses<six) and (guess<len(cloak-and-dagger)):     display = "Words then far:" + "_"*len(underground)     for i in range(len(hole-and-corner)):         if underground[i] == guess:             display = display.replace("_", approximate)         else:             misses = misses+1             impress misses             print letter of the alphabet             print display  display,rep_count = new_display(secret,display,estimate) impress display,rep_count            

i volition also be seeing my prof tomorrow for some assistance, so i gauge i'm trying to larn as much as i tin can today before seeing him tomorrow, to prevent me from looking similar an idiot.

Member Avatar

This is an app that should be coded as a class with self.misses as a variable, merely it would be too much to hope for that you take already covered classes. Anyhow, modified code to account for non being able to laissez passer misses to the function

              def new_display(secret, brandish, guess):           """Displays the replacement of underscores with letters that the user has       guessed"""       replacement_count = 0       alphabetize=secret.discover(guess)       display_list=[ eachltr for eachltr in brandish ]       if (index > -i) and (display_list[alphabetize]=="_"):  ## non already replaced          display_list[alphabetize]=guess          display="".join(display_list)          replacement_count += ane        return display, replacement_count ## display, replacement_count = new_display(secret, display, guess) if replacement_count:     ## letter was found and replaced    total_replacement += replacement_count else:    ## no letter replaced=miss    misses += 1            

WOW, I just became a "Junior Poster in Preparation". Judge I'll have to visit here more than often. My available time is hit and miss though.

Member Avatar

              if guess in clandestine:         ##-----  this will supersede every "_" with guess.  You have to replace a specific position         ## or utilise count to detect the number to add together to rep_count         ## or you tin use find() and add one to any position establish to use as a first         ##     parameter to notice()         ## add together print statements to see what is happening         impress "before changing 'brandish'", display         brandish = display.supervene upon("_", gauge)         print "later on irresolute 'brandish '", display            

Another way to convert when gauge is found (if this is whatever easier to understand)

              new_display=""    if guess in hugger-mugger:       index = secret.notice(estimate)       for j in range(0, len(display)):          this_char=display[j]          if j != index:          ##   copy what is in display             new_display += this_char          else:                   ## replace this letter             new_display += approximate             rep_count += i    else:         new_display = display              ## nothing found=continue the same render new_display, rep_count            

Member Avatar

i will effort them out tomorrow evening. i have a midterm tomorrow for my biochem class and i really should showtime studying tom. i'll update my code for you guys tomorrow, the twenty-four hour period that it's besides due. even if i don't finish this before submission, i'd even so similar to piece of work on this even after since i take to get this sooner or later. thanks for everything. volition answer tomorrow.

Member Avatar

On further reflection, in that location's an easier solution than what I suggested. My version would be

              #This is where we can update the letters guessed def new_display(surreptitious, display, guess):     """Displays the replacement of underscores with letters that the user has guessed"""     rep_count = 0     new_d = ""     for i in range(len(secret)):         if secret[i] == gauge:             new_d += guess             rep_count += ane         else:             new_d += display[i]     return new_d, rep_count            

It functions by maxim, OK, let's accept a blank new display. Then go character by grapheme through secret. If secret matches the guess, and then add together the guess to the new brandish. Otherwise, add together display to the new display. Then each character in the new display will come either from cloak-and-dagger (if the approximate matches that character) or from the old display (if not).

Then if display == "--TT--" and secret == "Letter" and approximate == "Due east", then new_d builds up similar this:

              alphabetize  new_d 0        -           # from display ane        -E         # judge matched! ii        -ET       # from display 3        -ETT     # from display four        -ETTE   # judge matched! 5        -ETTE-  # from display            

That's a lot easier than either the lists or slices I was mentioning.

---

The while loop that yous threw into your code was i step forward, one step dorsum. You want to let the user to accept turns within the while loop, so line 20 should go in that block. Line 22 has the outcome of resetting display every turn, which you don't desire. And the for loop is unnecessary.

The best way to build the while loop in the main code is to plan information technology based on the fact that you now have two spiffy new functions: 1 that gets the user guess and one that creates the new display based on the judge *and* returns the number of times that the guess was in the hugger-mugger.

And then your bones while loop in the primary lawmaking will be

              while the user withal isn't dead yet:    do_turn(...)            # fill in the ... with your variables    display, count = new_display(...)    if the user got a hit:       print an encouraging message    else:       make sure the user gets one step closer to hanging            

And if you think about information technology, that's how you would play hangman yourself.

Jeff

Member Avatar

Jeff's pseudo-code with total_replacement and misses fields added to keep track of successes vs failures

              total_replacement=0 misses=0 total_guesses=0 while the_user_still_isn't_dead_yet:    do_turn(...)            # fill in the ... with your variables    total_guesses += 1    display, count = new_display(...)    if count:     ## letter was institute and replaced       total_replacement += count       impress an encouraging bulletin    else:    ## no letter replaced=miss       misses += 1       make sure the user gets one step closer to hanging impress "You lot guessed %d times, with %d letters replaced and %d misses" %         (total_guesses, total_replacements, misses)            

Edit: In this version of hangman if the 'secret word' is "abac" and the approximate is an "a", are both a's replaced or just one? It affects the way the function replaces.

Member Avatar

it's suppose to supercede both."

"abac"
a_a

gotta run for my autobus now. gonna be late for class. cheers for your help!

Member Avatar

hi, so i talked to my prof today and i told him if it was okay to ask for suggestions/help online and he said information technology would be academic dishonesty. and then, i'll be rewriting the whole code so i know i understand this. can the moderator delete this post altogether?

thanks for everyone's time in helping, merely i'm gonna accept to stick with asking for help from my prof and his teaching administration.

Member Avatar

Your integrity is duly admired. If you remember one thing, remember this:

The only way to communicate to a function is past passing information technology parameters; the only style to get info back is from the return value.

Jeff

Member Avatar

Here is the lawmaking I used for my Sonic the Hedgehog hangman game

              import random HANGMANPICS = ['''    +---+   |   |       |       |       |       | =========''', '''    +---+   |   |   O   |       |       |       | =========''', '''    +---+   |   |   O   |   |   |       |       | =========''', '''    +---+   |   |   O   |  /|   |       |       | =========''', '''    +---+   |   |   O   |  /|\  |       |       | =========''', '''    +---+   |   |   O   |  /|\  |  /    |       | =========''', '''    +---+   |   |   O   |  /|\  |  / \  |       | ========='''] words = 'sonic knuckles amy shadow tails rouge large eggman robotnik vector silver foam cheese chao froggy chaosemerald masteremerald sallyacorn mobius unitedfederation naugus snively angelisland deathegg badnik greenhill chemicalplant worldring chaoscontrol tornado robotropolis newmegaopolis vanilla metalrobotnik metalsonic robotgenerator decoe bocoe freedomfighters'.split()  def getRandomWord(wordList):     # This function returns a random string from the passed list of strings.     wordIndex = random.randint(0, len(wordList) - 1)     render wordList[wordIndex]  def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):     print(HANGMANPICS[len(missedLetters)])     impress()      print('Missed letters:', end=' ')     for letter in missedLetters:         print(letter, finish=' ')     print()      blanks = '_' * len(secretWord)      for i in range(len(secretWord)): # replace blanks with correctly guessed letters         if secretWord[i] in correctLetters:             blanks = blanks[:i] + secretWord[i] + blanks[i+ane:]      for alphabetic character in blanks: # bear witness the secret word with spaces in between each letter         print(letter, end=' ')     print()  def getGuess(alreadyGuessed):     # Returns the letter the role player entered. This function makes sure the player entered a unmarried letter, and non something else.     while True:         print('Guess a letter.')         guess = input()         gauge = guess.lower()         if len(guess) != 1:             print('Please enter a single letter of the alphabet.')         elif judge in alreadyGuessed:             print('You take already guessed that letter. Choose again.')         elif guess non in 'abcdefghijklmnopqrstuvwxyz':             print('Please enter a LETTER.')         else:             return approximate  def playAgain():     # This function returns True if the player wants to play over again, otherwise it returns Simulated.     print('Do yous desire to play again? (yeah or no)')     render input().lower().startswith('y')   print('H A North One thousand M A N') missedLetters = '' correctLetters = '' secretWord = getRandomWord(words) gameIsDone = False  while Truthful:     displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)      # Let the player type in a alphabetic character.     guess = getGuess(missedLetters + correctLetters)      if estimate in secretWord:         correctLetters = correctLetters + approximate          # Check if the player has won         foundAllLetters = True         for i in range(len(secretWord)):             if secretWord[i] not in correctLetters:                 foundAllLetters = False                 intermission         if foundAllLetters:             print('Yes! The secret word is "' + secretWord + '"! You lot have won!')             gameIsDone = Truthful     else:         missedLetters = missedLetters + guess          # Check if role player has guessed as well many times and lost         if len(missedLetters) == len(HANGMANPICS) - 1:             displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)             print('Yous have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' right guesses, the word was "' + secretWord + '"')             gameIsDone = True      # Ask the histrion if they want to play again (but only if the game is done).     if gameIsDone:         if playAgain():             missedLetters = ''             correctLetters = ''             gameIsDone = Simulated             secretWord = getRandomWord(words)         else:             break            

Member Avatar

I wondered how hard it would be to use a cord/list of single bytes for the hangman picture and substitute the single byte every time there is an wrong approximate. Not besides difficult, but it may not exist worth the fourth dimension either.

              def print_hangman(list_in, wrong_guess):     print "*"*thirty     print "".join(list_in)     lit = "%d wrong guess" % (wrong_guess)     if ane != wrong_guess:         lit += "es"     print lit  hangman_pic='''     +---+   |   |       |       |       |       |       | ========='''  wrong_guess_pic = [("O", 21),                    ("|", 29),                    ("/", 28),                    ("\\", 30),                    ("|", 37),                    ("/", 44),                    ("\\", 46)]  new_pic = list(hangman_pic) wrong_guess=0  ## simulate incorrect guesses for ctr in range(len(wrong_guess_pic)):     tup = wrong_guess_pic[wrong_guess]     new_pic[tup[ane]] = tup[0]     wrong_guess += i      print_hangman(new_pic, wrong_guess)            

amosbobeat.blogspot.com

Source: https://www.daniweb.com/forums/thread93602.html

0 Response to "How to Not Count Letters Again in Python Hangman"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel