简单的python子手游戏 [英] Simple python hangman game

查看:85
本文介绍了简单的python子手游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的python hangman游戏有点麻烦.我想我大部分时候都没有这个机制(不是100%自信),但是每当用户输入一封信时,在印制电路板时我都会遇到一些问题.应该找到存储该索引的索引,然后转到该索引并用猜测的字母替换它.目前它还不能替代字母,当它在猜出字母后重新印制在木板上时,它只会不断地增加更多的星星.例如,如果单词的长度为6个字母,则会打印出6个星.当您猜到一个字母时,它会用12个星星重印木板,以此类推.如何在单词中替换字母并将其填充在同一块板上打印出来.另外,当游戏结束时,如果他们想继续玩并循环播放整个游戏,如何提示他们进入游戏游戏又结束了吗?代码如下:

I am having a little bit of trouble with my python hangman game. I think I have the mechanisms down for the most part (not 100% confident) but I am having a bit of issues when it comes to printing out the board whenever the user enters in a letter. It is supposed to find the index where that is stored and then go to that index and replace it with the guessed letter. At the moment it doesn't replace the letter and when it reprints out the board after a guessed letter it just keeps adding more stars to the end. For example if the word is 6 letters long it prints out 6 stars. When you guess a letter it reprints the board with 12 stars and so on. How can I make it replace the letter when it is in the word and print that same board out with that letter filled in. Also when the game is over how do I prompt them to enter in if they want to keep playing and loop the whole game over again? The code is below:

import random

listOfWords = ("hangman", "chairs", "backpack", "bodywash", "clothing", "computer", "python", "program", "glasses", "sweatshirt", "sweatpants", "mattress", "friends", "clocks", "biology", "algebra", "suitcase", "knives", "ninjas", "shampoo")
randomNumber = random.randint(0, len(listOfWords) - 1)
guessWord = listOfWords[randomNumber]
theBoard = []
wrong = []
guessedLetter = int(0)

#Will create the board using a new list and replace them with stars
def makeBoard(word):
    for x in word: #will go through the number of letters in the word that is chosen and for each letter will append a star into theBoard list
        theBoard.append('*') 
    return ''.join(theBoard) #Will print the list without having the [] and the commas

def guessing(letter): #This is for guessing the letters
    win = int(0) #Will be used to see if the user wins
    count = int(0) #Will be used to replace the star with a letter
    if letter.lower() in guessWord: # converts to lowercase and goes through the word 
        guessedLetter = guessWord.index(letter) #create a variable called guessedLetter that will take the index of the letter guessed by the user
        while (count != guessedLetter): #while loop to look for the index of the guessed letter
            count += 1
            if (count == guessedLetter): # will go into the board and replace the desired index with the letter if it matches
                theBoard[count] = letter

    for x in theBoard: # loop to go through theBoard to see if any '*' are there. If none are found it will say you win
        if (x != '*'):
            win += 1
    if (win == len(theBoard)):
        print("You win!")

def main():
   print(guessWord) 
   level = input("Enter a difficulty level: ")
   print("The word is: " + makeBoard(guessWord))
   if (level == '1'):
       print("You have selected the easy difficulty.")
       while (len(wrong) != 9):
           userGuess = input("Enter in the letter you want to guess: ")
           guessing(userGuess)
           if userGuess not in guessWord:
               wrong.append(userGuess)
           print("You have " + str(len(wrong)) + " guesses. Guessed letters: " + str(wrong))
           if (len(wrong) == 9):
               level = input("You have lost. If you would like to play again then enter in the difficulty level, or 4 to exit")
               if (level != 4):
                   randomNewNumber = random.randint(0, len(listOfWords) - 1)
                   guessNewWord = listOfWords[randomNewNumber]
               if (level == 4):
                   sys.exit(0)

   if (level == '2'):
       print("You have selected the medium difficulty.")
       print("The word is: " + makeBoard(guessWord))
       while (len(wrong) != 7):
           userGuess = input("Enter in the letter you want to guess: ")
           guessing(userGuess)
           if userGuess not in guessWord:
               wrong.append(userGuess)
           print("You have " + str(len(wrong)) + " guesses. Guessed letters: " + str(wrong))
   if (level == '3'):
       print("You have selected the hard difficulty.")
       print("The word is: " + makeBoard(guessWord))
       while (len(wrong) != 5):
           userGuess = input("Enter in the letter you want to guess: ")
           guessing(userGuess)
           if userGuess not in guessWord:
               wrong.append(userGuess)
           print("You have " + str(len(wrong)) + " guesses. Guessed letters: " + str(wrong))


main()    

我已解决有关用第一个字母正确显示的问题,但第一个字母除外.例如,如果单词是python,即使您猜不显示p,它也会显示为* ython.这是执行替换的代码:

I have fixed the problem about it redisplaying with the proper letter except for the first one. Example if the word is python it comes up as *ython even if you guess the p it doesn't display. Here is the code that does the replacing:

def guessing(letter): #This is for guessing the letters
    win = int(0) #Will be used to see if the user wins
    count = int(0) #Will be used to replace the star with a letter
    guessedLetter = guessWord.index(letter) #create a variable called guessedLetter that will take the index of the letter guessed by the user
    if letter.lower() in guessWord: # converts to lowercase and goes through the word 
        while (count != guessedLetter): #while loop to look for the index of the guessed letter
            count = count + 1
            if (count == guessedLetter): # will go into the board and replace the desired index with the letter if it matches
                theBoard[count] = letter
                print("The word is: " + ''.join(theBoard))

    for x in theBoard: # loop to go through theBoard to see if any '*' are there. If none are found it will say you win
        if (x != '*'):
            win += 1
    if (win == len(theBoard)):
        print("You win!")

推荐答案

修改并测试了Saelyth示例-现在它正在运行:)

Modified and tested Saelyth example - so now it is working game :)

#!/usr/bin/python3

import random

class Hangman():

    def Playing(self):
        listOfWords = ["example", "says", "python", "rocks"]

        again = True
        while again:

            guessWord = random.choice(listOfWords)
            board = "*" * len(guessWord)
            alreadySaid = set()
            mistakes = 7

            print(" ".join(board))

            guessed = False
            while not guessed and mistakes > 0:

                whatplayersaid = input("Guess a letter: ")

                if whatplayersaid in guessWord:
                    alreadySaid.add(whatplayersaid)
                    board = "".join([char if char in alreadySaid else "*" for char in guessWord])
                    if board == guessWord:
                        guessed = True
                else:
                    mistakes -= 1
                    print("Nope.", mistakes, "mistakes left.")

                print(" ".join(board))

            again = (input("Again [y/n]: ").lower() == 'y')

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

Hangman().Playing()

这篇关于简单的python子手游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆