1

I'm trying to create a hangman game with python. I know there is still a lot to complete but I'm trying to figure out the main component of the game which is how to compare the user inputted string (one letter) with the letters in one of the three randomly selected words.

import random

print("Welcome to hangman,guess the five letter word")
words =["china", "ducks", "glass"]
correct_word = (random.choice(words))
guess = input(str("Enter your guess:"))
guess_left = 10
guess_subtract = 1
if guess == "":
    guess_left = guess_left - guess_subtract
    print("you have" + guess_left + "guesses left")
Rish
  • 804
  • 8
  • 15
  • 2
    Please dont link to code, your question should be self-contained. That said, the hangman problem pops up on SO daily; surely you've found some workable base solution from your searches? – roganjosh Dec 27 '18 at 22:37
  • 2
    Code needs to be in your post, not in external links, images or comments. What if those external sites go down 5 years from now? – Random Davis Dec 27 '18 at 22:37
  • Is the user expected to give a word or just a single letter to the input? – Chris Doyle Dec 27 '18 at 22:41
  • they are supposed to input a single letter –  Dec 27 '18 at 22:42
  • Possible duplicate of [How to check a string for specific characters?](https://stackoverflow.com/questions/5188792/how-to-check-a-string-for-specific-characters) – erik258 Dec 27 '18 at 22:53
  • Looking for more of how to cross check a single inputted letter and compare that to a five letter word to check if that inputted letter matches up with a letter in the five letter word. –  Dec 27 '18 at 23:01
  • take the correct word and break into list of characters https://stackoverflow.com/questions/9833392/break-string-into-list-of-characters-in-python. Then check if the input is in that list (ie ‘if guess in character_list:’) or ‘if guess not in character_list:’ – chitown88 Dec 27 '18 at 23:03

4 Answers4

1

I think you need a skeleton and then spend some time to improve the game.

import random

print "Welcome to hangman, guess the five letter word"

words = ["china", "ducks", "glass"]
correct_word = (random.choice(words))

trials = 10

for trial in range(trials):
    guess = str(raw_input("Enter character: "))

    if (len(guess) > 1):
        print "You are not allowed to enter more than one character at time"
        continue

    if guess in correct_word:
        print "Well done! '" + guess + "' is in the list!"
    else:
        print "Sorry " + guess + " does not included..."

Your next step could be print out something like c_i__ as well as the number of trials left. Have fun :)

When you finish with the implementation, take some time and re-implement it using functions.

Daedalus
  • 295
  • 2
  • 17
  • Thanks for the advice I will be sure to add this! –  Dec 27 '18 at 23:16
  • Sorry don't have 15 reputation. –  Dec 27 '18 at 23:22
  • Sorry I have another question if you could help me. How could I tell the program to stop accepting guesses when all the letters in the word were guessed correctly? –  Dec 27 '18 at 23:41
1

I've completed this project yesterday; (to anyone else reading this question) take inspiration if needed.

import random

stages = ['''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========
''', '''
  +---+
  |   |
      |
      |
      |
      |
=========
''']

#used to choose random word
random_lst=['addition','adequate','adjacent','adjusted','advanced','advisory','advocate','affected','aircraft','alliance','although','aluminum','analysis','announce','anything','anywhere','apparent','appendix','approach','approval','argument','artistic','assembly']
chosen_word = random.choice(random_lst)


#used to create display list + guess var
print("Welcome to hangman! ")
print("--------------------")
print("you have 6 lives." )
print("   ")
print (stages[-1])

display = []
for letters in chosen_word:
  display += "_"

print(display)
print("  ")

#used to check if guess is equal to letter, and replace pos in display if yes. 



lives = 6
game_over = False
#use the var guesses to store guesses and print at every guess to let player know what letters they tried already.
guesses = ""


while not game_over:
  guess = input("Guess a letter. ")
  print("  ")
  guesses += (guess + " , ")
  for pos in range(len(chosen_word)):
    letter = chosen_word[pos
    if letter == guess:]
      display[pos] = letter
      print("√")
      print("- - -")
      print("   ")
  if display.count("_") == 0:
    print("Game over. ")
    game_over = True
  elif guess not in chosen_word:
    lives -= 1
    print(f"Wrong letter. {lives} lives left. ") 
    print("- - - - - - - - - - - - - - - - - - -")
    print("   ")
  if lives == 0:
    print (stages[0])
  elif lives == 1:
    print (stages[1])
  elif lives == 2:
    print (stages[2])
  elif lives == 3:
    print(stages[3])
  elif lives == 4:
    print(stages[4])
  elif lives == 5:
    print(stages[5])
  elif lives == 6:
    print(stages[6])
  elif lives == 0:
    game_over = True
    print("Game over. ")
  print(f"letters chosen: {guesses}") 
  print("   ")
  print(display)
  print("   ")
  if lives == 0 or display.count("_") == 0:  
    break
  

if lives == 0:
  print("Game over. You lose.")
elif lives > 0:
  print("Congrats, you win! ")
 
timelyfor
  • 49
  • 5
0

What you can do is treat the string like an array/list. So if you use loops:

x = ""#let's assume this is the users input
for i in range(len(y)): #y is the string your checking against
    if x == y[i]:

from here what I'm thinking is that if they are equal it would add that letter to a string

Let's say the string is "Today was fun" then would have an array like this, [""."" and so on but you'd have to find a way to factor in spaces and apostrophes. So if the letter is == to that part of the string

#this is a continuation of the code, so under if
thearray[theposition] == the letter

But looking a your code your game is diffrent from the regular one so, also consider using a while look

gamewon = False
number of trials = 10

while gamewon == False and number of trials > 0:
    #the whole checking process 
    if x == guess:
       gamewon == True
       print ........# this is if your doing word for word else use 
       the code above
     else:
         number  of trials = number of trials - 1

I think that's it I know its a bit all over the place but you can always ask for help and I'll explain plus I was referring to your code things i thought you could fix

0

First you should accept both a and A by using guess = guess.lower(). The you have to search the string for the character guessed and find the positions.

guess = guess.lower()

# Find the position(s) of the character guessed
pos = [idx for idx,ch in enumerate(correct_word) if ch == guess]

if pos:
    print('Letter Found')

guess_left -= 1

Another way to understand the for-loop is:

pos = []
for idx,ch in enumerate(correct_word):
    if ch == guess:
        pos.append(idx)
slayer
  • 643
  • 7
  • 14
  • Im still new to python and I am having a hard time figuring out what this line is telling the program to do: pos = [idx for idx,ch in enumerate(correct_word) if ch == guess] –  Dec 27 '18 at 23:14
  • This is another way to write a for loop. It says, for an idx,ch in the enumerated list so that the first character will be in the variable `ch` with index 0. Then the next `ch` will be the next character with index 1. Then the `if` is checking only for `ch` that are equal to the letter that was guessed. If this is true, then put the idx into a list called `pos`. It's python's fancy way of combining a for-loop and if statement into one line. – slayer Dec 27 '18 at 23:37