Help for creating a hangman game

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tidiz
    New Member
    • Nov 2008
    • 8

    Help for creating a hangman game

    Hi,

    I'm trying to make a hangman game that should look like this:

    Welcome to Hangman
    ______
    Your guess: c
    Success!
    __cc__
    Your guess: b
    Failure! You have tried tried 1 times!
    __cc__
    .
    .
    .
    Your guess: r
    Success!
    soccer
    You won!

    etc

    In this game I'm trying to make it so that I first need to give a file - where game takes words - at commandline as a parameter to game. I've done that so far that program takes randomly a word from a certain file (here words.txt), prints blanks as a hintword and starts asking letters. My problem is that I can't make the program to check for the letters in word and replace blanks with guessed letter.

    So far my code looks like that:

    Code:
    import sys
    
    if sys.argv[1] == 'words.txt':
        list = open('words.txt','r')
        a = list.readlines()
    
        import random
    
        b = random.choice(a)
        
        print 'Welcome to Hangman'
        c = '_'*(len(b)-1)
        print c
        for i in range(1,6):
            mark = raw_input('Your guess: ')
            check = b.find(mark)
            if check != -1:
                print 'Succes!', mark, 'is in word at position', check
                c = c[:check] + mark + c[check + 1:]
                print c
            else:
                print 'Failure! You have tried tried %d times!' %(i)
    
    else:
        print '[Errno2] No such file or directory: %s' %(sys.argv[1])
    Can anyone tell me how to solve this problem? Sorry for the dots, but I didn't know any other way to get that structure showing right.

    Edit: Thanks for the tip. I edited the code to show right :)
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    I haven't taken a look at your problem yet, but you can enclose your code in code tags, [CODE] and [/CODE], and the parser won't eat the indentation.
    Edit:
    Thanks, that's much better.

    Comment

    • boxfish
      Recognized Expert Contributor
      • Mar 2008
      • 469

      #3
      For some reason, you can't replace a character in a string with another character. The only way I know to get around this is to slice the string into two pieces and put the new character between them. It seems like there must be a better way to do this, but here it is:
      Code:
      c = c[:check] + mark + c[check + 1:]
      And list is a reserved word. You shouldn't be using it as a variable name.
      Hope this helps.

      Comment

      • tidiz
        New Member
        • Nov 2008
        • 8

        #4
        Thanks for the help. It helped to replace those blanks with letters, but now I encountered a new one problem. If we have a word "soccer" and we are guessing the letter "c", program only takes the first letter and converts it, but not the other c. So here we would end in result "__c___". So in the end we will have result "soc_er".

        I edited the current code for the first post.

        Comment

        • boxfish
          Recognized Expert Contributor
          • Mar 2008
          • 469

          #5
          How about replacing the letters from b with underlines after they have been guessed?
          Edit:
          Never mind, that would make the user have to guess the same letter more than once.

          Comment

          • tidiz
            New Member
            • Nov 2008
            • 8

            #6
            I think I need to fix that find-structure so that program wont stop finding at the first hit, but also checks the whole word for hits. Any recommendations for how to do this would be great as I am not very skilled with python... yet :)

            Comment

            • boxfish
              Recognized Expert Contributor
              • Mar 2008
              • 469

              #7
              I have a book on Python with a hangman game example in it. It works something like
              Code:
              Clear out c.
              For each letter in b:
                  If the letter is equal to mark:
                      Add mark to c.
                  Else:
                      Add a blank to c.
              Hope this helps.
              Edit:
              Sorry, still won't work. Try it like this:
              Code:
              Create a new string.  Let's call it new_c.
              For each letter in b:
                  If the letter is equal to mark:
                      Add mark to new_c.
                  Else:
                      Add a letter from the old c to new_c.
              Replace c with new_c.

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                This returns a list of indexes of letter in word s:
                [code=Python]def idxList(s, letter, idx=0):
                ''' Return a list of indices of "letter" in string "s".'''
                if not type(s) == str:
                raise AttributeError, 'Argument 0 must be a string'
                idxList = []
                while True:
                idx = s.find(letter, idx)
                if idx == -1:
                return idxList
                idxList.append( idx)
                idx += 1[/code]

                Example:
                >>> idxList('missis sippi', 's')
                [2, 3, 5, 6]
                >>>

                To substitute the letters in the hint string, create a list of letters:

                [code=Python]list(hint_strin g)[/code]

                Iterate on the indexes list, and assign the list item to letter.

                [code=Python]string_list[idx] = letter[/code]

                Join the letters to form the new hint string:

                [code=Python]''.join(string_ list)[/code]

                Comment

                • tidiz
                  New Member
                  • Nov 2008
                  • 8

                  #9
                  Hi,

                  Thanks to you all for help. Somehow I wasn't able to make my code working exactly how you suggested, so I made it in different way. Maybe this coding isn't the best possible, but at least this works :)

                  Code:
                  import sys
                  
                  if sys.argv[1] == 'words.txt':
                      list1 = open('words.txt','r')
                      list2 = []
                      for word in list1.readlines():
                          sana = word.replace('\n','')
                          list2.append(sana)
                  
                      import random
                  
                      b = random.choice(list2)
                  
                      print 'Welcome to Hangman'
                      hint = '_'*len(b)
                      print hint
                  
                      counter = 0
                  
                      while counter < 5:
                          if hint == b:
                              print 'You win!'
                              print 'Goodbye'
                              break
                          else:
                              pass
                          mark = raw_input('Your guess: ')
                          if mark == '':
                              counter += 1
                              print 'Failure! You have tried tried %d times!' %(counter)
                          else:
                              counter2 = 0
                              if mark in hint:
                                  counter += 1
                                  print 'Failure! You have tried tried %d times!' %(counter)
                                  print hint
                              elif mark in b:
                                  print 'Success!'
                                  for i in b:
                                      if mark == i:
                                          x = list(hint)
                                          x[counter2] = mark
                                          hint = "".join(x)
                                      counter2 += 1
                                  if hint != b:
                                      print hint
                                  else:
                                      pass
                              else:
                                  counter += 1
                                  print 'Failure! You have tried tried %d times!' %(counter)
                                  if counter != 5:
                                      print hint
                                  else:
                                      pass
                  
                      else:
                          print 'Game over! you lose!'
                          print 'The word was %s' %(b)
                          print 'Goodbye'
                  
                  else:
                      print "[Errno 2] No such file or directory: '%s'" %(sys.argv[1])

                  Comment

                  Working...