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 ^_^)?
16 8183
This book has a chapter on it as well as many other chapters on how to program python with games used as examples.
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. -
#when the program it running
-
>> play('python')
-
-
* * * * * *
-
the hidden word has 6 letters
-
turn: 5
-
-
Please enter a letter: p
-
-
#the program should print out
-
-
You're right
-
p * * * * * # I don't know how to write this
-
turn: 5
-
-
Please enter a letter: s
-
-
#the program should print out
-
You're wrong
-
p * * * * * # I don't know how to write this
-
turn: 4
-
-
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. -
#when the program it running
-
>> play('python')
-
-
* * * * * *
-
the hidden word has 6 letters
-
turn: 5
-
-
Please enter a letter: p
-
-
#the program should print out
-
-
You're right
-
p * * * * * # I don't know how to write this
-
turn: 5
-
-
Please enter a letter: s
-
-
#the program should print out
-
You're wrong
-
p * * * * * # I don't know how to write this
-
turn: 4
-
-
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: -
def indexList(s, item, start = 0):
-
return [i+start for (i, let) in enumerate(s[start:]) if let == item]
-
-
base = "******"
-
word = "python"
-
letter = raw_input("Enter a letter: ")
-
if letter in word:
-
lbase = list(base)
-
for pos in indexList(word, letter):
-
lbase[pos] = letter
-
-
base = ''.join(lbase)
-
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: -
def indexList(s, item, start = 0):
-
return [i+start for (i, let) in enumerate(s[start:]) if let == item]
-
-
base = "******"
-
word = "python"
-
letter = raw_input("Enter a letter: ")
-
if letter in word:
-
lbase = list(base)
-
for pos in indexList(word, letter):
-
lbase[pos] = letter
-
-
base = ''.join(lbase)
-
A list is one way. Here's another: -
>>> base = "******"
-
>>> word = "python"
-
>>> guess = 'h'
-
>>> idx = word.find(guess)
-
>>> if idx > -1:
-
... base = base[:idx] + guess + base[idx + 1:]
-
...
-
>>> base
-
'***h**'
-
>>>
But that won't handle more than one occurrence of the letter in the word.
bvdet 2,851
Expert Mod 2GB
Here is a similar way that will handle multiple occurrences of a letter: - def hintStrSub(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)
-
return hint_str
-
-
def indexList(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
- >>> idx_list = indexList('sequentially', 'l')
-
>>> idx_list
-
[9, 10]
-
>>> hint = '*' * len('sequentially')
-
>>> hintStrSub(hint, 'l', idx_list)
-
'*********ll*'
-
>>>
-
a = 'hello'
-
for i in range(len(a)):
-
print a.index('l',a.index('l')+i)
-
-
2
-
3
-
-
Traceback (most recent call last):
-
File "C:/Python25/test.py", line 4, in <module>
-
print a.index('l',a.index('l'))
-
ValueError: substring not found
-
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.
-
a = 'hello'
-
for i in range(len(a)):
-
print a.index('l',a.index('l')+i)
-
-
2
-
3
-
-
Traceback (most recent call last):
-
File "C:/Python25/test.py", line 4, in <module>
-
print a.index('l',a.index('l'))
-
ValueError: substring not found
-
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: -
def indexList(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
-
P.S. Did you take a look at the responses in your other thread? I think they address this same issue.
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.
tried but it only gave me a first index occurrence of an item
This is a neat little function that does what I think you want: -
def indexList(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
-
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: -
>>name = 'John John'
-
>>letter = 'J'
-
>>iList = indexList(name,letter)
-
>>print iList
-
[0]
-
-
#but it should contain
-
[0,5]
-
thank you very much. I've purchased a python book, it explained very well how to make this game work -
so_far = "-" * len(word)
-
-
# create a new so_far to include guess
-
new = ""
-
for i in range(len(word)):
-
if guess == word[i]:
-
new += guess
-
else:
-
new += so_far[i]
-
so_far = new
-
bvdet 2,851
Expert Mod 2GB
I tried this way: -
>>name = 'John John'
-
>>letter = 'J'
-
>>iList = indexList(name,letter)
-
>>print iList
-
[0]
-
-
#but it should contain
-
[0,5]
-
It works for me: - >>> indexList("John John", "J")
-
[0, 5]
-
>>>
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. - #Hangman version 2 R J While-Cooper 19-01-14
-
#NEXT UPDATE WILL ALLOW PHRASES THAT INCLUDE A DELIMITER BETWEEN WORDS
-
-
#THE VARIOUS STAGES OF HANGMAN
-
def scaffold5():
-
print""
-
print " ------|"
-
print " | \|"
-
print " |"
-
print " |"
-
print " /|"
-
print " ____/_|_"
-
-
def scaffold4():
-
print""
-
print " ------|"
-
print " | \|"
-
print " o |"
-
print " |"
-
print " /|"
-
print " ____/_|_"
-
-
def scaffold3():
-
print""
-
print " ------|"
-
print " | \|"
-
print " o |"
-
print " / |"
-
print " /|"
-
print " ____/_|_"
-
-
def scaffold2():
-
print""
-
print " ------|"
-
print " | \|"
-
print " o |"
-
print " /| |"
-
print " /|"
-
print " ____/_|_"
-
-
def scaffold1():
-
print""
-
print " ------|"
-
print " | \|"
-
print " o |"
-
print " /|\ |"
-
print " /|"
-
print " ____/_|_"
-
-
def scaffold0():
-
print""
-
print " ------|"
-
print " | \|"
-
print " o |"
-
print " /|\ |"
-
print " / \ /|"
-
print " ____/_|_"
-
print "YOU'VE BEEN HANGED!"
-
-
#DRAWS SCAFFOLD BASED ON NUMBER OF WRONG_GUESSE
-
def build_scaffold():
-
if wrong_guess == 0:
-
scaffold5()
-
elif wrong_guess ==1:
-
scaffold4()
-
elif wrong_guess ==2:
-
scaffold3()
-
elif wrong_guess ==3:
-
scaffold2()
-
elif wrong_guess ==4:
-
scaffold1()
-
-
-
#IMPORTS TIME FUNCTION FOR DELAYS
-
import time
-
-
#WORD CHOICE LIST
-
medium_word = ['envelope','antelope','elephant','organism','encyclopedia']
-
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']
-
-
-
#ADJUST DIFFICULTY BY CHANGING MAX_GUESSES TO A LOWER NUMBER
-
check_letters = 0
-
max_guesses = 5
-
wrong_guess = 0
-
cont = "y"
-
-
#PRINTS ENTIRE ALPHABET NOT REALLY USED NOW
-
def print_alpha_list():
-
print "The letters you can choose are : ",
-
for letter in alphabet_list:
-
print letter,
-
print ""
-
-
#PRINTS THE LETTERS THAT HAVE BEEN CHOSEN
-
def print_choices():
-
print "The letters you have chosen are : ",
-
for letter in choices:
-
print letter,
-
print ""
-
-
#FUNCTIONS CLEAR THE SCREEN AND ADD A SHORT DELAY BETWEEN ROUNDS
-
#CLEARS SCREEN
-
def cls():
-
print ('\n' *50)
-
-
#SETS A DELAY
-
def wait_time():
-
print "PLEASE WAIT ",
-
for x in range(4):
-
print ". ",
-
time.sleep(0.5)
-
-
#CALLS CLEAR AND DELAY FUNCTIONS
-
def clear_wait():
-
wait_time()
-
cls()
-
-
#ENTERS THE GAME/REPEAT LOOP
-
while cont == "y":
-
-
#CLEARS SCREEN AND REMOVES CHOICES FROM LAST GAME PRINTS ALPHABET FOT THE IDIOTS
-
clear_wait()
-
choices = []
-
print_alpha_list()
-
-
#RANDOMLY CHOOSES A WORD FROM THE WORD LIST, SPLITS IT INTO A LIST
-
#AND GIVE THE NUMBER OF LETTERS IN THE WORD
-
from random import choice
-
wordchosen = choice(medium_word)
-
word = list(wordchosen)
-
len_word = len(word)
-
-
#DOES THE FIRST MASK
-
build_scaffold()
-
print "Guess the word!"
-
print ""
-
print "_ " * len_word
-
-
#YOU GET TO PLAY UNTIL YOU RUN OUT OF GUESSES
-
while wrong_guess < max_guesses:
-
-
#RESETS CHECKING VARIABLES IN GAME LOOP
-
duplicate_letter = 0
-
missing_letter_count = 0
-
check_letters = 0
-
-
-
#ASKS FOR USER INPUT & COVERTS TO LOWER CASE
-
print ""
-
guess = raw_input("Choose a letter .Enter your choice and press <ENTER> --->")
-
guess = guess.lower()
-
-
#SPOTS DUPLICATE LETTERS BY CHECKING IF THE GUESS IS IN THE CHOICES LIST
-
#IF NOT IT ADDS TO THE CHOICES LIST
-
if guess in choices:
-
print "You already picked that letter!"
-
duplicate_letter +=1
-
else:
-
choices.append(guess)
-
-
clear_wait()
-
-
#print word
-
-
#THE ALL IMPORTANT MASK ALGORITHM
-
for letter in word:
-
if letter == letter in word:
-
if letter in choices:
-
print letter,
-
else:
-
missing_letter_count +=1
-
print "_ ",
-
-
#CHECKES IF YOU HAVE WON BECAUSE THERE WILL BE NO DASHES WRITTEN
-
if missing_letter_count == 0:
-
break
-
-
print ""
-
print_choices()
-
print ""
-
-
#CHECKS TO SEE IN THE ANSWER IS WRONG
-
for letter in word:
-
if guess != letter:
-
check_letters +=1
-
if check_letters == len(word) or duplicate_letter != 0:
-
wrong_guess +=1
-
-
build_scaffold()
-
-
#INCREMENTS THE WRONG GUESSES COUNT FOR WRONG OR DUPLICATE ANSWERS
-
if wrong_guess != 0 or duplicate_letter != 0:
-
print "You have had ", wrong_guess, "wrong guesses!"
-
print "You have ", max_guesses - wrong_guess, "guesses left!"
-
-
#PRINTS YOU WIN OR LOSE DEPENDING ON CONDITION, GIVES PLAY AGAIN CHOICE
-
#FINAL SCAFFOLD DRAWN IF WRONNG_GUESS ==MAX_GUESSES
-
if wrong_guess == max_guesses:
-
print "You lose!"
-
print "The word was ",
-
print word
-
print ""
-
scaffold0()
-
print ""
-
cont = raw_input (" Play again? Y/N ? >")
-
cont = cont.lower()
-
wrong_guess = 0
-
else:
-
print ""
-
cont = raw_input ("You Win! Play again? Y/N ? >")
-
cont = cont.lower()
-
-
-
print "Thanks for playing HANGMAN!"
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. - #alternative hangman (beta version without refinements)
-
#rwhile-cooper 08-02-14
-
word = "testword"
-
guesses = []
-
chances = 5
-
-
pos = 0
-
length = len(word)
-
word_mask = "*" * length
-
#need this to compare to the original word
-
wordoriginal = word
-
print word_mask
-
-
#if the workmask matchs the original word you win
-
while wordoriginal != word_mask:
-
guess = raw_input("Enter a letter to guess.")
-
if guess in guesses:
-
print "You already chose that letter."
-
else:
-
guesses.append(guess)
-
-
if word.find(guess) != -1:
-
print "You guessed correctly!"
-
while word.find(guess) !=-1:
-
pos = word.find(guess)
-
#have to replace the letters with dashes or the positions don't work in future goes
-
word = word[:pos] +"_" +word[pos+1:]
-
#adds the correct letters to the wordmask
-
word_mask = word_mask[:pos] + guess + word_mask[(pos+1):]
-
-
else:
-
#updates wrong chances and checks for victory
-
chances -=1
-
print "You guessed wrong. You have ",chances ,"chance left."
-
-
print word_mask
-
if chances == 0:
-
break
-
-
if chances == 0:
-
print "You lost"
-
else:
-
print "You won"
Sign in to post your reply or Sign up for a free account.
Similar topics
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>
...
|
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?...
|
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:...
|
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...
|
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...
|
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...
|
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
|
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...
|
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...
|
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...
|
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...
|
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 =...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
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...
|
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...
|
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...
|
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...
| |