473,289 Members | 1,839 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

write a Hangman game

I've seen several versions of Hangman game written in many different computer languages like Pascal, C++, Java and even in my TI calculator ( I don't know what the code mean, but what kind of computer languages developers use). I'm really interesting in written this game using Python, however, I don't know how to start. Can someone help me write the simple version of this game with just a few secret words (without the picture of the man is being hanged ^_^)?
Oct 29 '07 #1
16 8183
bartonc
6,596 Expert 4TB
Hangman Search on the Python Forum. If you hurry, you'll see the list before the search expires.
Oct 29 '07 #2
bartonc
6,596 Expert 4TB
Hangman Search on the Python Forum. If you hurry, you'll see the list before the search expires.
Well, that search expired. Here is one of the longest threads on the subject.
Oct 30 '07 #3
elcron
43
This book has a chapter on it as well as many other chapters on how to program python with games used as examples.
Oct 30 '07 #4
Hangman Search on the Python Forum. If you hurry, you'll see the list before the search expires.
The codes people used in those threats were so complex. So, I need to break the whole thing into small pieces and work on each one.

My first question is how to reveal the * which representes for a hidden letter.
Expand|Select|Wrap|Line Numbers
  1. #when the program it running
  2. >> play('python')
  3.  
  4. * * * * * *
  5. the hidden word has 6 letters
  6. turn: 5
  7.  
  8. Please enter a letter: p
  9.  
  10. #the program should print out
  11.  
  12. You're right
  13. p * * * * * # I don't know how to write this
  14. turn: 5
  15.  
  16. Please enter a letter: s
  17.  
  18. #the program should print out
  19. You're wrong
  20. p * * * * * # I don't know how to write this
  21. turn: 4
  22.  
  23.  
Oct 30 '07 #5
ilikepython
844 Expert 512MB
The codes people used in those threats were so complex. So, I need to break the whole thing into small pieces and work on each one.

My first question is how to reveal the * which representes for a hidden letter.
Expand|Select|Wrap|Line Numbers
  1. #when the program it running
  2. >> play('python')
  3.  
  4. * * * * * *
  5. the hidden word has 6 letters
  6. turn: 5
  7.  
  8. Please enter a letter: p
  9.  
  10. #the program should print out
  11.  
  12. You're right
  13. p * * * * * # I don't know how to write this
  14. turn: 5
  15.  
  16. Please enter a letter: s
  17.  
  18. #the program should print out
  19. You're wrong
  20. p * * * * * # I don't know how to write this
  21. turn: 4
  22.  
  23.  
Ok you need to check if the letter is in the word and then if it is replace the star in the position of the letter with the actual letter:
Expand|Select|Wrap|Line Numbers
  1. def indexList(s, item, start = 0):
  2.     return [i+start for (i, let) in enumerate(s[start:]) if let == item]
  3.  
  4. base = "******"
  5. word = "python"
  6. letter = raw_input("Enter a letter: ")
  7. if letter in word:
  8.     lbase = list(base)
  9.     for pos in indexList(word, letter):
  10.         lbase[pos] = letter
  11.  
  12.     base = ''.join(lbase)
  13.  
Oct 31 '07 #6
bartonc
6,596 Expert 4TB
Ok you need to check if the letter is in the word and then if it is replace the star in the position of the letter with the actual letter:
Expand|Select|Wrap|Line Numbers
  1. def indexList(s, item, start = 0):
  2.     return [i+start for (i, let) in enumerate(s[start:]) if let == item]
  3.  
  4. base = "******"
  5. word = "python"
  6. letter = raw_input("Enter a letter: ")
  7. if letter in word:
  8.     lbase = list(base)
  9.     for pos in indexList(word, letter):
  10.         lbase[pos] = letter
  11.  
  12.     base = ''.join(lbase)
  13.  
A list is one way. Here's another:
Expand|Select|Wrap|Line Numbers
  1. >>> base = "******"
  2. >>> word = "python"
  3. >>> guess = 'h'
  4. >>> idx = word.find(guess)
  5. >>> if idx > -1:
  6. ...     base = base[:idx] + guess + base[idx + 1:]
  7. ...     
  8. >>> base
  9. '***h**'
  10. >>> 
But that won't handle more than one occurrence of the letter in the word.
Oct 31 '07 #7
bvdet
2,851 Expert Mod 2GB
Here is a similar way that will handle multiple occurrences of a letter:
Expand|Select|Wrap|Line Numbers
  1. def hintStrSub(hint_str, letter, pos_list):
  2.     for i in pos_list:
  3.         lst = [hint_str[:i], ]
  4.         if len(hint_str) >= i+1:
  5.             lst.append(hint_str[(i+1):])
  6.         hint_str = letter.join(lst)
  7.     return hint_str
  8.  
  9. def indexList(s, item, i=0):
  10.     i_list = []
  11.     while True:
  12.         try:
  13.             i = s.index(item, i)
  14.             i_list.append(i)
  15.             i += 1
  16.         except:
  17.             break
  18.     return i_list
Expand|Select|Wrap|Line Numbers
  1. >>> idx_list = indexList('sequentially', 'l')
  2. >>> idx_list
  3. [9, 10]
  4. >>> hint = '*' * len('sequentially')
  5. >>> hintStrSub(hint, 'l', idx_list)
  6. '*********ll*'
  7. >>> 
Oct 31 '07 #8
Expand|Select|Wrap|Line Numbers
  1. a = 'hello'
  2. for i in range(len(a)):
  3.     print a.index('l',a.index('l')+i)
  4.  
  5. 2
  6. 3
  7.  
  8. Traceback (most recent call last):
  9.   File "C:/Python25/test.py", line 4, in <module>
  10.     print a.index('l',a.index('l'))
  11. ValueError: substring not found
  12.  
I would like to find all indexes of letter l in the list, I got them but had this error. How can I fix this.
Oct 31 '07 #9
ilikepython
844 Expert 512MB
Expand|Select|Wrap|Line Numbers
  1. a = 'hello'
  2. for i in range(len(a)):
  3.     print a.index('l',a.index('l')+i)
  4.  
  5. 2
  6. 3
  7.  
  8. Traceback (most recent call last):
  9.   File "C:/Python25/test.py", line 4, in <module>
  10.     print a.index('l',a.index('l'))
  11. ValueError: substring not found
  12.  
I would like to find all indexes of letter l in the list, I got them but had this error. How can I fix this.
This is a neat little function that does what I think you want:
Expand|Select|Wrap|Line Numbers
  1. def indexList(s, item, i=0):
  2.     i_list = []
  3.     while True:
  4.         try:
  5.             i = s.index(item, i)
  6.             i_list.append(i)
  7.             i += 1
  8.         except:
  9.             break
  10.     return i_list
  11.  
P.S. Did you take a look at the responses in your other thread? I think they address this same issue.
Oct 31 '07 #10
bartonc
6,596 Expert 4TB
P.S. Did you take a look at the responses in your other thread? I think they address this same issue.
I've merge the two. Seems like the same issue to me.
Oct 31 '07 #11
tried but it only gave me a first index occurrence of an item
Nov 1 '07 #12
This is a neat little function that does what I think you want:
Expand|Select|Wrap|Line Numbers
  1. def indexList(s, item, i=0):
  2.     i_list = []
  3.     while True:
  4.         try:
  5.             i = s.index(item, i)
  6.             i_list.append(i)
  7.             i += 1
  8.         except:
  9.             break
  10.     return i_list
  11.  
P.S. Did you take a look at the responses in your other thread? I think they address this same issue.
I tried this way:

Expand|Select|Wrap|Line Numbers
  1. >>name = 'John John'
  2. >>letter = 'J'
  3. >>iList = indexList(name,letter)
  4. >>print iList
  5. [0]
  6.  
  7. #but it should contain
  8. [0,5]
  9.  
Nov 1 '07 #13
thank you very much. I've purchased a python book, it explained very well how to make this game work

Expand|Select|Wrap|Line Numbers
  1. so_far = "-" * len(word)
  2.  
  3. # create a new so_far to include guess
  4. new = ""
  5. for i in range(len(word)):
  6.      if guess == word[i]:
  7.            new += guess
  8.      else:
  9.            new += so_far[i]
  10. so_far = new
  11.  
Nov 1 '07 #14
bvdet
2,851 Expert Mod 2GB
I tried this way:

Expand|Select|Wrap|Line Numbers
  1. >>name = 'John John'
  2. >>letter = 'J'
  3. >>iList = indexList(name,letter)
  4. >>print iList
  5. [0]
  6.  
  7. #but it should contain
  8. [0,5]
  9.  
It works for me:
Expand|Select|Wrap|Line Numbers
  1. >>> indexList("John John", "J")
  2. [0, 5]
  3. >>> 
Nov 1 '07 #15
This is my beginner version using lists. Made me feel like a programming god. Done in version 2.7.5

Would welcome any comments, I think my solution is unusual at least.

Expand|Select|Wrap|Line Numbers
  1. #Hangman version 2 R J While-Cooper 19-01-14
  2. #NEXT UPDATE WILL ALLOW PHRASES THAT INCLUDE A DELIMITER BETWEEN WORDS
  3.  
  4. #THE VARIOUS STAGES OF HANGMAN
  5. def scaffold5():
  6.     print""
  7.     print "   ------|"
  8.     print "   |    \|"
  9.     print "         |"
  10.     print "         |"
  11.     print "        /|"
  12.     print "   ____/_|_"
  13.  
  14. def scaffold4():
  15.     print""
  16.     print "   ------|"
  17.     print "   |    \|"
  18.     print "   o     |"
  19.     print "         |"
  20.     print "        /|"
  21.     print "   ____/_|_"
  22.  
  23. def scaffold3():
  24.     print""
  25.     print "   ------|"
  26.     print "   |    \|"
  27.     print "   o     |"
  28.     print "  /      |"
  29.     print "        /|"
  30.     print "   ____/_|_"
  31.  
  32. def scaffold2():
  33.     print""
  34.     print "   ------|"
  35.     print "   |    \|"
  36.     print "   o     |"
  37.     print "  /|     |"
  38.     print "        /|"
  39.     print "   ____/_|_"
  40.  
  41. def scaffold1():
  42.     print""
  43.     print "   ------|"
  44.     print "   |    \|"
  45.     print "   o     |"
  46.     print "  /|\    |"
  47.     print "        /|"
  48.     print "   ____/_|_"
  49.  
  50. def scaffold0():
  51.     print""
  52.     print "   ------|"
  53.     print "   |    \|"
  54.     print "   o     |"
  55.     print "  /|\    |"
  56.     print "  / \   /|"
  57.     print "   ____/_|_"
  58.     print "YOU'VE BEEN HANGED!"
  59.  
  60. #DRAWS SCAFFOLD BASED ON NUMBER OF WRONG_GUESSE
  61. def build_scaffold():
  62.     if wrong_guess == 0:
  63.         scaffold5()
  64.     elif wrong_guess ==1:
  65.         scaffold4()
  66.     elif wrong_guess ==2:
  67.         scaffold3()
  68.     elif wrong_guess ==3:
  69.         scaffold2()
  70.     elif wrong_guess ==4:
  71.         scaffold1()
  72.  
  73.  
  74. #IMPORTS TIME FUNCTION FOR DELAYS
  75. import time
  76.  
  77. #WORD CHOICE LIST
  78. medium_word = ['envelope','antelope','elephant','organism','encyclopedia']
  79. alphabet_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','o','p','q','r','s','t','u','v','w','x','y','z']
  80.  
  81.  
  82. #ADJUST DIFFICULTY BY CHANGING MAX_GUESSES TO A LOWER NUMBER
  83. check_letters = 0
  84. max_guesses = 5
  85. wrong_guess = 0
  86. cont = "y"
  87.  
  88. #PRINTS ENTIRE ALPHABET NOT REALLY USED NOW
  89. def print_alpha_list():
  90.     print "The letters you can choose are : ",
  91.     for letter in alphabet_list:
  92.         print letter,
  93.     print ""
  94.  
  95. #PRINTS THE LETTERS THAT HAVE BEEN CHOSEN
  96. def print_choices():
  97.     print "The letters you have chosen are : ",
  98.     for letter in choices:
  99.         print letter,
  100.     print ""
  101.  
  102. #FUNCTIONS CLEAR THE SCREEN AND ADD A SHORT DELAY BETWEEN ROUNDS
  103. #CLEARS SCREEN
  104. def cls():
  105.     print ('\n' *50)
  106.  
  107. #SETS A DELAY
  108. def wait_time():
  109.     print "PLEASE WAIT ",
  110.     for x in range(4):
  111.         print ". ",
  112.         time.sleep(0.5)
  113.  
  114. #CALLS CLEAR AND DELAY FUNCTIONS
  115. def clear_wait():
  116.     wait_time()
  117.     cls()
  118.  
  119. #ENTERS THE GAME/REPEAT LOOP
  120. while cont == "y":
  121.  
  122.     #CLEARS SCREEN AND REMOVES CHOICES FROM LAST GAME PRINTS ALPHABET FOT THE IDIOTS
  123.     clear_wait()
  124.     choices = []
  125.     print_alpha_list()
  126.  
  127.     #RANDOMLY CHOOSES A WORD FROM THE WORD LIST, SPLITS IT INTO A LIST
  128.     #AND GIVE THE NUMBER OF LETTERS IN THE WORD
  129.     from random import choice
  130.     wordchosen = choice(medium_word)
  131.     word = list(wordchosen)
  132.     len_word = len(word)
  133.  
  134.     #DOES THE FIRST MASK
  135.     build_scaffold()
  136.     print "Guess the word!"
  137.     print ""
  138.     print "_ " * len_word
  139.  
  140.     #YOU GET TO PLAY UNTIL YOU RUN OUT OF GUESSES
  141.     while wrong_guess < max_guesses:
  142.  
  143.         #RESETS CHECKING VARIABLES IN GAME LOOP
  144.         duplicate_letter = 0
  145.         missing_letter_count = 0
  146.         check_letters = 0
  147.  
  148.  
  149.         #ASKS FOR USER INPUT & COVERTS TO LOWER CASE
  150.         print ""
  151.         guess = raw_input("Choose a letter .Enter your choice and press <ENTER> --->")
  152.         guess = guess.lower()
  153.  
  154.         #SPOTS DUPLICATE LETTERS BY CHECKING IF THE GUESS IS IN THE CHOICES LIST
  155.         #IF NOT IT ADDS TO THE CHOICES LIST
  156.         if guess in choices:
  157.             print "You already picked that letter!"
  158.             duplicate_letter +=1
  159.         else:
  160.             choices.append(guess)
  161.  
  162.         clear_wait()
  163.  
  164.         #print word
  165.  
  166.         #THE ALL IMPORTANT MASK ALGORITHM
  167.         for letter in word:
  168.             if letter == letter in word:
  169.                 if letter in choices:
  170.                     print letter,
  171.                 else:
  172.                     missing_letter_count +=1
  173.                     print "_ ",
  174.  
  175.         #CHECKES IF YOU HAVE WON BECAUSE THERE WILL BE NO DASHES WRITTEN
  176.         if missing_letter_count == 0:
  177.             break
  178.  
  179.         print "" 
  180.         print_choices()                 
  181.         print ""
  182.  
  183.         #CHECKS TO SEE IN THE ANSWER IS WRONG
  184.         for letter in word:
  185.             if guess != letter:
  186.                 check_letters +=1
  187.         if check_letters == len(word) or duplicate_letter != 0:
  188.             wrong_guess +=1
  189.  
  190.         build_scaffold()
  191.  
  192.         #INCREMENTS THE WRONG GUESSES COUNT FOR WRONG OR DUPLICATE ANSWERS
  193.         if wrong_guess != 0 or duplicate_letter != 0:
  194.             print "You have had ", wrong_guess, "wrong guesses!"
  195.             print "You have ", max_guesses - wrong_guess, "guesses left!"
  196.  
  197.     #PRINTS YOU WIN OR LOSE DEPENDING ON CONDITION, GIVES PLAY AGAIN CHOICE
  198.     #FINAL SCAFFOLD DRAWN IF WRONNG_GUESS ==MAX_GUESSES
  199.     if wrong_guess == max_guesses:
  200.         print "You lose!"
  201.         print "The word was ",
  202.         print word
  203.         print ""
  204.         scaffold0()
  205.         print ""
  206.         cont = raw_input ("  Play again? Y/N ? >")
  207.         cont = cont.lower()
  208.         wrong_guess = 0
  209.     else:
  210.         print ""
  211.         cont = raw_input ("You Win!  Play again? Y/N ? >")
  212.         cont = cont.lower()
  213.  
  214.  
  215. print "Thanks for playing HANGMAN!"
Jan 19 '14 #16
Here's a real quick n dirty solution using a different technique - involves breaking the strings apart and using the the position of characters to draw a map. No hangman drawn on this one but it's dead simple.
Expand|Select|Wrap|Line Numbers
  1. #alternative hangman (beta version without refinements)
  2. #rwhile-cooper 08-02-14
  3. word = "testword"
  4. guesses = []
  5. chances = 5
  6.  
  7. pos = 0
  8. length = len(word)
  9. word_mask = "*" * length
  10. #need this to compare to the original word
  11. wordoriginal = word
  12. print word_mask
  13.  
  14. #if the workmask matchs the original word you win   
  15. while wordoriginal != word_mask:
  16.     guess = raw_input("Enter a letter to guess.")
  17.     if guess in guesses:
  18.         print "You already chose that letter."
  19.     else:
  20.         guesses.append(guess)
  21.  
  22.     if word.find(guess) != -1:
  23.         print "You guessed correctly!"
  24.         while word.find(guess) !=-1:
  25.                 pos =  word.find(guess)
  26.                 #have to replace the letters with dashes or the positions don't work in future goes
  27.                 word = word[:pos] +"_" +word[pos+1:]
  28.                 #adds the correct letters to the wordmask
  29.                 word_mask = word_mask[:pos] + guess + word_mask[(pos+1):]
  30.  
  31.     else:
  32.         #updates wrong chances and checks for victory
  33.         chances -=1
  34.         print "You guessed wrong. You have ",chances  ,"chance left."
  35.  
  36.     print word_mask
  37.     if chances == 0:
  38.         break
  39.  
  40. if chances == 0:
  41.     print "You lost"
  42. else:
  43.     print "You won"
Feb 8 '14 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: tigrfire | last post by:
So I'm trying to write a hangman game and the output is coming out a little strange. Here's my code thus far: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> ...
18
ilikepython
by: ilikepython | last post by:
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: c = input('Would you like to play hangman?...
4
by: princessfrost | last post by:
Hi! I was wondering if someone could please help me with a hangman program that I have to do. I have some ideas, but really don't know what to do or where to start. My program needs to be:...
47
by: araujo2nd | last post by:
Originally Posted by araujo2nd my name is andre, im from south africa, i was wondering if any1 could help me with a hangman application, im now in grade 11 and have a huge portfolio piece to do by...
0
by: Madmartigan | last post by:
Hi I'm a newbie to C# and have been instructed to create a Hangman game in SharpDevelop. I don't want the answer to the full code, just some help along the way. I have included my code thus...
5
by: av3rage | last post by:
I have never done any programming in my life but I have decided to go into engineering and in doing so we have to take this intro to programming course and I am pretty clueless. I am starting to get...
8
by: tidiz | last post by:
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
1
by: AlexSc | last post by:
Hi to All, I am doing on a hangman project, Where this is a very simple one, where player would guess the word and if it is correct the letter would be from "-" to the correct letter once all...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.