hangman with strings and list methods

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ilikepython
    Recognized Expert Contributor
    • Feb 2007
    • 844

    hangman with strings and list methods

    Hi I'm new to Python(3 to 4 days) and I'm working on a hangman game and have been having some problems that really annoy me.
    Here is part of my script:
    Code:
    c = input('Would you like to play hangman? Type y or n ')
            
            
            word = sample(('soccer', 'robbery', 'antibiotics'), 1)
            word = str(word)    
            spaces = len(word) - 4
            def hangman():
                print '-------- '
                print '|______| '
                print ' O '
                print ' O '
                print ' O '
                print ' O '
                print ' O '
                print '---- '
                print '|___| '
            def hangman1():
                hangman()
                m = '%s' % ('_ ' * spaces)
                print m 
                number = word.find(letter)
                m.split()
                m.replace('_', letter)
    Problems
    1. I can't get python to replace the "blank" with the letter that my user chose.
    I've tried a lot of things and I'm really getting frustrated.

    2. When I'm running the program I always have to input something in quotes or it will give me some NameError or something. I've tried:
    x = str('x')
    and x = 'x' in a number of ways and it's not working. Please help

    I'm runnning Python 2.5 on Windows Xp

    Note: If you see the '-4' that's another little problem: when the spaces for the word appear it prints 4 more than the chosen word so I put '- 4'(not the best idea) if you can tell me how to fix that, that would be great.


    Thanks
    Last edited by bartonc; Feb 17 '07, 10:18 PM. Reason: added [code][/code] tags
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Originally posted by ilikepython
    Hi I'm new to Python(3 to 4 days) and I'm working on a hangman game and have been having some problems that really annoy me.
    Here is part of my script:
    Code:
    c = input('Would you like to play hangman? Type y or n ')
            
            
            word = sample(('soccer', 'robbery', 'antibiotics'), 1)
            word = str(word)    
            spaces = len(word) - 4
            def hangman():
                print '-------- '
                print '|______| '
                print ' O '
                print ' O '
                print ' O '
                print ' O '
                print ' O '
                print '---- '
                print '|___| '
            def hangman1():
                hangman()
                m = '%s' % ('_ ' * spaces)
                print m 
                number = word.find(letter)
                m.split()
                m.replace('_', letter)
    Problems
    1. I can't get python to replace the "blank" with the letter that my user chose.
    I've tried a lot of things and I'm really getting frustrated.

    2. When I'm running the program I always have to input something in quotes or it will give me some NameError or something. I've tried:
    x = str('x')
    and x = 'x' in a number of ways and it's not working. Please help

    I'm runnning Python 2.5 on Windows Xp

    Note: If you see the '-4' that's another little problem: when the spaces for the word appear it prints 4 more than the chosen word so I put '- 4'(not the best idea) if you can tell me how to fix that, that would be great.


    Thanks
    Hello and welcome to the Python Forum on TSDN! Something weird happend when you pasted you code here, but we'll work on that as we go along.
    #2 for strings, use
    Code:
    inputStr = raw_input("enter a string")
    .
    I'll look at the rest in a bit.

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Originally posted by bartonc
      Hello and welcome to the Python Forum on TSDN! Something weird happend when you pasted you code here, but we'll work on that as we go along.
      #2 for strings, use
      Code:
      inputStr = raw_input("enter a string")
      .
      I'll look at the rest in a bit.
      Go ahead and post the entire code here. That will make things easier for everybody. Please read the "POSTING GUIDELINES" on the right hand side of the page to learn how to use code tags (the # simbol in this editor window). You can edit your post for 5 minutes to try to get it right. I can fix it if you are having trouble, so don't worry about that too much right now.

      Comment

      • ilikepython
        Recognized Expert Contributor
        • Feb 2007
        • 844

        #4
        Originally posted by bartonc
        Go ahead and post the entire code here. That will make things easier for everybody. Please read the "POSTING GUIDELINES" on the right hand side of the page to learn how to use code tags (the # simbol in this editor window). You can edit your post for 5 minutes to try to get it right. I can fix it if you are having trouble, so don't worry about that too much right now.
        Ok
        Code:
        import time
        from time import sleep
        import random
        from random import sample
        
           
        search = True
        while search:
            try:
            
                
                search = False
                c = input('Would you like to play hangman? Type y or n ')
                
                
                word = sample(('soccer', 'robbery', 'antibiotics'), 1)
                word = str(word)    
                spaces = len(word) - 4
                def hangman():
                    print '-------- '
                    print '|______| '
                    print ' O '
                    print ' O '
                    print ' O '
                    print ' O '
                    print ' O '
                    print '---- '
                    print '|___| '
                def hangman1():
                    hangman()
                    m = '%s' % ('_ ' * spaces)
                    print m 
                    number = word.find(letter)
                    m.split()
                    m.replace('_', letter)            
            
                        
            
            except:
                c = str('c') 
            else:
                pass
                
        
                if c == 'y':
                    search = False        
                    sleep(2)
                    print "Alright, let's play "
                    hangman()
         
                    print  '%s' % ('_ ' * spaces)
                    
                else:
                    if c == 'n' :
                        print 'Ok, Buh Bye then'
                        sleep(2)
                        exit()
                    else:
                        c = str(c)
        search = True
        alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
        while search:
            letter = input("Pick a letter. A letter that is missing has already been used")
            
            print alphabet
            if letter in word: 
                print 'There was a %s in the word' % (letter)
                num = alphabet.index(letter)
                del alphabet[num]
                print alphabet
                hangman1()
                        
            else:
                if letter not in word:
                    print 'There was no %s in the word' % (letter)

        Comment

        • bartonc
          Recognized Expert Expert
          • Sep 2006
          • 6478

          #5
          I didn't run this, nor did I work on hangman1() except to give you an idea for structure. This should give you something to go on. You have used many features of the language very well. Hopefully, this will give you some ideas of good structure.
          Code:
          # no need to import the whole module if all you want is one function
          from time import sleep
          from random import sample
          from string import lowercase as letters # string module has useful constants in it.
          
          
          wordTuple = ('soccer', 'robbery', 'antibiotics')
          maxGuesses = 5
          
          def hangman():
              print '-------- '
              print '|______| '
              print ' O '
              print ' O '
              print ' O '
              print ' O '
              print ' O '
              print '---- '
              print '|___| '
          
          
          def hangman1(w, m, c):
              hangman()
          ##    m = '%s' % ('_ ' * spaces)
              print w, m, c
          ##    number = word.find(letter)
          ##    m.split()
          ##    m.replace('_', letter)    
          
          
          while True:
              charCount = 0
              alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                          'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
          
              answer = raw_input('Would you like to play hangman? Type y or n ')
              if answer[0].lower() == 'n':
                  break
          
              word = sample(wordTuple, 1)[0]  # extract the word from sample()'s list
              nSpaces = len(word)
              blanks = '_' * nSpaces
          
              print "Alright, let's play "
              sleep(2)
              while charCount < maxGuesses:
                  hangman()
                  print alphabet
                  letter = ""
                  while letter not in letters:
                      letter = raw_input("Pick a letter. A letter that is missing has already been used").lower()
              
                  if letter in word: 
                      print 'There was a \"%s\" in the word' % letter
                      blanks = hangman1(word, blanks, letter)
              
              ##        num = alphabet.index(letter) a list can do both at once
              ##        del alphabet[num]
                      try:
                          alphabet.remove(letter)
                      except IndexError:
                          pass
                  else:
                      print 'There was no \"%s\" in the word' % letter
                  charCount += 1
          
          print 'Ok, Buh Bye then'
          sleep(2)
          # exit() In python, just run off the end of the module

          Comment

          • ilikepython
            Recognized Expert Contributor
            • Feb 2007
            • 844

            #6
            Thank you very much.
            I appreciate your help.
            I will see how it goes and post the finished script.

            Thanks

            Comment

            • bartonc
              Recognized Expert Expert
              • Sep 2006
              • 6478

              #7
              Originally posted by ilikepython
              Thank you very much.
              I appreciate your help.
              I will see how it goes and post the finished script.

              Thanks
              You are welcome. We'll help you get that hangman1() fuction working if you get stuck.

              I forgot something:
              Code:
              def hangman1(w, m, c):
                  hangman()
              ##    m = '%s' % ('_ ' * spaces)
                  print w, m, c
              ##    number = word.find(letter)
              ##    m.split()
              ##    m.replace('_', letter)
                  return m  # send the result back to caller

              Comment

              • ilikepython
                Recognized Expert Contributor
                • Feb 2007
                • 844

                #8
                One quick question.
                If I have a while loop and a try\except block, can I return back to the beginning of the while loop if let's say an error occured.
                For example:
                Code:
                while True:
                    letter = inputStr = raw_input("Pick a letter")
                    if letter in word:
                        try:
                            alphabet.remove(letter)
                        except ValueError:
                            print ' You already used this letter'
                can I return to the input after the ValueError even if there is more to the while loop after the try\except block??

                Comment

                • bvdet
                  Recognized Expert Specialist
                  • Oct 2006
                  • 2851

                  #9
                  I hope you don't mind, but I have some suggestions.
                  Instead of removing letters from an alphabet list after each guess:
                  Code:
                      guess_list = []
                  ....................
                          guess_list.append(letter)
                          guess_list.sort()
                          print 'So far you have guessed the following letters: %s' % (','.join(guess_list))
                  How about displaying a hint string? Initialize it:
                  Code:
                      hint_string = '_' * len(word)
                  Update the hint string:
                  Code:
                  def get_index(s, item, i=0):
                      i_list = []
                      while True:
                          try:
                              i = s.index(item, i)
                              i_list.append(i)
                              i += 1
                          except:
                              break
                      return i_list
                  
                  def hangman1(hint_str, letter, pos_list):
                      ......................
                      for i in pos_list:
                          lst = [hint_str[:i], ]
                          if len(hint_str) >= i+1:
                              lst.append(hint_str[(i+1):])
                          hint_str = letter.join(lst)
                      print 'Hint: %s' % (hint_str)
                      ........................
                      return hint_str
                  If the user guesses the same letter twice, tell him about it:
                  Code:
                              if letter in hint_string:
                                  print "You have already guessed letter '%s' dodo!" % (letter)
                                  hint_string = hangman1(hint_string, letter, [])
                  Give the user a way out:
                  Code:
                          letter = raw_input("Enter a letter or '?' if you are ready to solve the word.")
                          if letter == '?':
                              hint_string = raw_input("Give it your best shot!")
                              if hint_string == word:
                                  print "Congratulations! You have solved the word!"
                                  break
                              else:
                                  print "You have failed miserably!"
                                  break
                  Here's some output:
                  Code:
                  >>> Alright, let's play 
                  --------
                  |______|
                   O 
                   O 
                   O 
                   O 
                   O 
                  ----
                  |___|
                  Hint: ______
                  So far you have guessed the following letters: c
                  There were 2 occurrences of c in the word.
                  --------
                  |______|
                   O 
                   O 
                   O 
                   O 
                   O 
                  ----
                  |___|
                  Hint: __cc__
                  You entered the word 'soccer'
                  Congratulations! You have solved the word!
                  >>>

                  Comment

                  • bartonc
                    Recognized Expert Expert
                    • Sep 2006
                    • 6478

                    #10
                    Originally posted by ilikepython
                    One quick question.
                    If I have a while loop and a try\except block, can I return back to the beginning of the while loop if let's say an error occured.
                    For example:
                    Code:
                    while True:
                        letter = inputStr = raw_input("Pick a letter")
                        if letter in word:
                            try:
                                alphabet.remove(letter)
                            except ValueError:
                                print ' You already used this letter'
                    can I return to the input after the ValueError even if there is more to the while loop after the try\except block??
                    Yes. That's exactly what the t/e block does. It keeps program flow going the way that you would expect (want) instead of jumping out due to errors.
                    Code:
                    while True:
                        # do stuff
                        if condition # this should include except clause
                            continue    # break's other half
                    I've never tried it, but I'll bet that you have by now.

                    Comment

                    • bartonc
                      Recognized Expert Expert
                      • Sep 2006
                      • 6478

                      #11
                      Originally posted by bvdet
                      I hope you don't mind, but I have some suggestions.
                      Instead of removing letters from an alphabet list after each guess:
                      Jump in any time, B. I really appreciate your input. Great suggestions here, again! Thanks.

                      Comment

                      • ilikepython
                        Recognized Expert Contributor
                        • Feb 2007
                        • 844

                        #12
                        Thanks all for your suggestions.
                        I will post back here when i finish the game.

                        Comment

                        • bartonc
                          Recognized Expert Expert
                          • Sep 2006
                          • 6478

                          #13
                          Originally posted by ilikepython
                          Thanks all for your suggestions.
                          I will post back here when i finish the game.
                          It's a fun language, isn't it? Easy too, I think.

                          Comment

                          • ilikepython
                            Recognized Expert Contributor
                            • Feb 2007
                            • 844

                            #14
                            Originally posted by bvdet
                            I hope you don't mind, but I have some suggestions.

                            Update the hint string:
                            Code:
                            def get_index(s, item, i=0):
                                i_list = []
                                while True:
                                    try:
                                        i = s.index(item, i)
                                        i_list.append(i)
                                        i += 1
                                    except:
                                        break
                                return i_list
                            
                            def hangman1(hint_str, letter, pos_list):
                                ......................
                                for i in pos_list:
                                    lst = [hint_str[:i], ]
                                    if len(hint_str) >= i+1:
                                        lst.append(hint_str[(i+1):])
                                    hint_str = letter.join(lst)
                                print 'Hint: %s' % (hint_str)
                                ........................
                                return hint_str

                            Could you please explain to me the get_index() and hangman1() functions.
                            I don't really understand what get_index is supposed to do.
                            Also, in hangman1() what's the "pos_list" supposed to be.
                            Sorry for my ignorence but I don't really get it.
                            Thanks for your suggestions.

                            Comment

                            • bvdet
                              Recognized Expert Specialist
                              • Oct 2006
                              • 2851

                              #15
                              Originally posted by ilikepython
                              Could you please explain to me the get_index() and hangman1() functions.
                              I don't really understand what get_index is supposed to do.
                              Also, in hangman1() what's the "pos_list" supposed to be.
                              Sorry for my ignorence but I don't really get it.
                              Thanks for your suggestions.
                              Function 'get_index' returns a list of indices (positions) in the text string (word) that matches 'letter'. The function call 'get_index('soc cer', 'c')' returns '[2, 3]' so I know there are 2 occurrances of 'c' in 'soccer' and I know the positions.
                              Code:
                                  for i in pos_list:
                                      lst = [hint_str[:i], ]
                                      if len(hint_str) >= i+1:
                                          lst.append(hint_str[(i+1):])
                                      hint_str = letter.join(lst)
                                  print 'Hint: %s' % (hint_str)
                                  return hint_str
                              Variable 'pos_list' (position list), obtained from function get_index(), is passed to hangman1(). We iterate on 'pos_list' to replace the '_' in hint_string with 'letter' in the correct position for each occurrance of 'letter' in 'word'. If we pass an empty list to hangman1(), no iteration takes place. We want to pass an empty list to hangman1() if:
                              1. The player guessed 'letter' previously.
                              2. 'letter' does not occur in 'word.
                              If you have more questions, please ask. HTH

                              Comment

                              Working...