Hangman add a new word

This is the place for queries that don't fit in any of the other categories.

Hangman add a new word

Postby MattLR » Wed May 07, 2014 1:38 pm

Hi guys, made an account just for this :)
have made a hangman game with help of other sources online however i word like the player to have the ability to add their own words.
For example at the start of the game it will ask the and whatever word they type in will be added to the word list. Thanks for all the help :)

Matt


Code: Select all
import random
import sys

# Creating pictures for hangman
# Triple quotes are used, therefore the speech/pictures can be continued down multiple lines
hangman_pics = ["""
  +---+
  |   |
      |
      |
      |
      |
=========""", """
  +---+
  |   |
  O   |
      |
      |
      |
=========""", """
  +---+
  |   |
  O   |
  |   |
      |
      |
=========""", """
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========""", """
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========""", """
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========""", """
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
========="""]

# ---------------------------------------------------------- #

# Welcome user and difficulty selection
print("""

          ----------------------------
          |  Welcome to Hangman!     |
          |                          |
          |  Select a difficulty:    |
          |  1. Easy (2-4 Letters)   |
          |  2. Medium (5-7 Letters) |
          |  3. Hard (8+ Letters)    |
          |                          |
          |  4. Exit Game            |
          |                          |
          ----------------------------
""")

def add_word():
    os.system("cls")
    print ("Old Word List:",",".join(words))
    new_word = input("Input new word:")
    if len(new_word)>0:
        words.append(new_word)
        os.system("cls")
        print ("New word list",",".join(words))
        input("press enter to continue")


       
# Word list for each difficulty
difficulty = int(input("      What difficulty do you pick (1-4)?: "))

if difficulty == 1:
    words = ("pen art bell book exam test flag quiz math ink ict ").split()
if difficulty == 2:
    words = ("history paper clock drawing mouse biology question maths school teacher learn student").split()
if difficulty == 3:
    words = ("calculator geography alphabet computer computing dictionary chemistry scissors science ").split()

new_word = input("Enter a new word: ")
   
# ------------------------------------------------------------ #

def getRandomWord(wordList):
    # This function returns a random string from the passed list of strings
    wordIndex= random.randint(0, len(wordList) -1)
    return wordList[wordIndex]
def displayBoard (hangman_pics, missedLetters, correctLetters, secretWord):
    print(hangman_pics[len(missedLetters)])
    print()
    print ("Missed letters:", end=" ")
    for letter in missedLetters:
        print(letter, end=" ")
    print()
    blanks = "_" * len(secretWord)
    for i in range(len(secretWord)): # Replace blanks with correct letters
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
    for letter in blanks: #show the secret word with spaces inbbertween each letter
        print(letter, end=" ")
    print()
def getGuess(alreadyGuessed):
    # Returns the letter the player entered. This function also avoids errors and makes sure the player entered a simgle letter.
    while True:
        guess = input("Guess a letter: ")
        guess = guess.lower()
        if len(guess) != 1:
             print ("Please enter a single letter.")
        elif guess in alreadyGuessed:
             print("You have already guessed that letter, please try another: ")
        elif guess not in "qwertyuiopasdfghjklzxcvbnm":
             print ("Please enter a letter in the english alphabet")
        else:
            return guess

def playAgain():
    # This function returns True if theplayer wants to play again
    print ("Do you want to play again? ('yes' or 'no')")
    return input ().lower().startswith("y")
print ("\n------------------------------------------\n")
print ("H A N G M A N")
missedLetters = ""
correctLetters = ""
secretWord = getRandomWord(words)
gameIsDone = False
while True:
    displayBoard(hangman_pics, missedLetters, correctLetters, secretWord)
    # Let the player type in their guess
    guess = getGuess(missedLetters + correctLetters)
    if guess in secretWord:
        correctLetters = correctLetters + guess
        # Check if the player has won
        foundAllLetters = True
        for i in range(len(secretWord)):
            if secretWord[i] not in correctLetters:
                foundAllLetters = False
                break
        if foundAllLetters:
             print ("\n------------------------------------------------------")
             print ("Yes! The secret word is '" + secretWord + "'! You have won!"
                    )
             gameIsDone = True
    else:
        missedLetters = missedLetters + guess
        # Check if player has guessed too many times and lost
        if len(missedLetters) == len(hangman_pics) -1:
            displayBoard(hangman_pics, missedLetters, correctLetters, secretWord)
            print ("You have run out of  guesses!\nAfter " + str(len(missedLetters)) + "missed guesses and " + str(len(correctLetters)) + " correct guesses, the secret word was '" + secretWord + "'")
            gameIsDone = True

    # Ask the player if they want to play again when the game has finished
    # if the player want to play again, all aspects of the game are restarted and a new word is chosen
    if gameIsDone:
        if playAgain():
            missedLetters = ""
            correctLetters = ""
            gameIsDone = False
            secretWord = getRandomWord(words)
        else:
            print ("Okay, thankyou for playing :)\n\nGoodbye!")

            break

Last edited by stranac on Wed May 07, 2014 1:44 pm, edited 2 times in total.
Reason: First post lock.
MattLR
 
Posts: 1
Joined: Wed May 07, 2014 1:31 pm

Re: Hangman add a new word

Postby Mekire » Wed May 07, 2014 1:57 pm

Moved to general coding help as this seems more like a general python basics question than a game programming question.
If you want to be able to add words and have them carry over between sessions then you will need to learn about opening and writing to files.

Try writing it in isolation. Just a program that takes input from the user and adds it to a file containing your words. Get rid of everything else and just figure out how to do that. Then put it together. Don't try to do everything at once.

-Mek
User avatar
Mekire
 
Posts: 1009
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 2 guests