简体   繁体   English

如何在Python中制作刽子手游戏

[英]How to make a hangman game in Python

I found an exercise on a website to make a hangman game.我在一个网站上找到了一个制作刽子手游戏的练习。 Here is what I did:这是我所做的:

score = int(5)
word = 'orange'
guess = str(input('Enter your guess: '))

while score > 0 or guess == 'o' and 'r' and 'a' and 'n' and 'g' and 'e' or 'orange'
    if 'o' or 'r' or 'a' or 'n' or 'g' or 'e' or 'orange' == guess:
        print('CORRECT')
    else:
        score = score - 1
        print('Your score is ' + score)
        print('WRONG')

This code just doesn't work!这段代码是行不通的! Especially the while loop ruins everything?尤其是while loop毁了一切? How to make this actually work.如何使它真正起作用。 I have written this code in the Jupyter notebook.我已经在 Jupyter 笔记本中编写了这段代码。

This is a working example of the guessing game, with some removal of code redundancy and a bit of clean-up.这是猜谜游戏的一个工作示例,删除了一些代码冗余并进行了一些清理。 Important: break-statement inserted inside the if-statement to avoid infinite looping, and new guess prompt inserted in the else-statement:重要提示:在 if 语句中插入 break 语句以避免无限循环,并在 else 语句中插入新的猜测提示:

score = 5
word = 'orange'
guess = str(input('Enter your guess: '))

while (score > 0) or (guess in ('o', 'r', 'a', 'n', 'g', 'e', 'orange')):
    if guess in ('o', 'r', 'a', 'n', 'g', 'e', 'orange'):
        print('CORRECT')
        break
    else:
        score -= 1
        print('WRONG')
        print('Your score is ' + str(score))
        guess = str(input('Enter your guess: '))

Example run:示例运行:

Enter your guess: u
WRONG
Your score is 4
Enter your guess: o
CORRECT

If you want to check guess against a set of different options, use in ;如果您想根据一组不同的选项检查guess ,请使用in ; you can't use and or or like that due to different precedences.由于优先级不同,您不能使用and or or or like that。

if guess in ('o', 'r', 'a', 'n', 'g', 'e', 'orange'):

would work better for you (though that's probably not the only problem in your code).会更好地为您工作(尽管这可能不是您代码中的唯一问题)。

There's lots here to do - 1st, your code only allows for a game of hangman for which the word to be guessed is "orange".这里有很多事情要做 - 第一,你的代码只允许一个刽子手游戏,其中要猜的词是“橙色”。 Fine for a single game, but useless for the second round, unless all players have acute memory problems.单场比赛还好,但第二轮没用,除非所有玩家都有严重的 memory 问题。

So you need to abstract a little - write some pseudo-code down, think about the steps your program is going to need to take in order to perform the operations required in the game.所以你需要abstract一点——写下一些伪代码,想想你的程序需要采取哪些步骤才能执行游戏中所需的操作。

This is like writing down instructions for a human, just in a form that's also close to your final programming language.这就像为人类写下指令,只是形式也接近你的最终编程语言。

So something like:所以像:

# choose a word to play the game with, save it to the variable called word
word = 'orange'
# Reserve a list of letters that have been guessed.
# Start off with it empty - do the same to keep track of 
# good and bad guesses
guesses = []
good_guesses = []
bad_guesses = []
# Reserve a number of bad tries allowed before game over
bad_tries_before_game_over = 5
# Reserve a number of bad tries so far
bad_tries_so_far = 0

# Start a loop, we'll come back to this point each time 
# the player makes a new guess.
# There are two conditions when to not loop and those are:
# 1. when the player has won by guessing all the letters or
# 2. when the player has lost by getting too many wrong tries
# we'll use a variable called "finished" to track whether either of these conditions is met
finished = False
while not finished:
    guess = str(input('Enter your guess: '))

    # Check whether the person already guessed this letter
    if guess in guesses:
        print ( "You already guessed that letter.")
        print ( "Try using a letter you've not already guessed.")
        print ( guesses )
    else:
        # if guess is correct, then great, otherwise, add bad tries + 1
        if guess in word:
            print ( "Yes, {g} is in the word.".format(g=guess) )
            guesses.append(guess)
            good_guesses.append(guess)
        else:
            print ( "No, {g} is not in the word.".format(g=guess) )
            guesses.append(guess)
            bad_guesses.append(guess)
            bad_tries_so_far = bad_tries_so_far  + 1

        if bad_tries_so_far > bad_tries_before_game_over:
            print ( "Hangman. Game over. ")
            finished = True

        if set(word)==set(good_guesses):
            print ( "Hooray, you saved the man!.")
            finished = True

Over time, you'll naturally think in python and it will kind of become its own pseudo code.随着时间的推移,您自然会想到python,它会变成自己的伪代码。 But it's best to at least try and work your ideas out on paper, or in English (or whatever language is your natural one) first, just to set out the logical flow that you want the game to have.但最好至少先尝试在纸上或用英语(或任何适合您的语言)将您的想法付诸实践,以制定您希望游戏具有的逻辑流程。

Well, here's one that I made.嗯,这是我做的一个。 It's slightly more interactive and realistic, but making the words are kind of annoying.它的互动性和现实性稍强一些,但制作文字有点烦人。 If you want to make it more fun, try adding more words with a random word generator or something like that, make the hangman more realistic, or adding game modes and VS matches.如果你想让它更有趣,尝试使用随机词生成器或类似的东西添加更多词,让刽子手更逼真,或者添加游戏模式和 VS 比赛。 I hope this helps =)我希望这会有所帮助=)

If you're still wondering how this code works, I'll try and explain as much as possible.如果您仍然想知道这段代码是如何工作的,我会尽可能多地尝试和解释。 First of all, I imported time to make pauses, making it more dramatic.首先,我输入了时间来暂停,让它更具戏剧性。 If you want to remove the pauses, be my guest.如果你想消除停顿,请成为我的客人。

The first bunch of code is just the beginning and all that.第一批代码只是开始而已。 You could delete/change it if you want如果需要,您可以删除/更改它

After, it asks you to input your name.之后,它会要求您输入您的姓名。 Like I said, completely optional.就像我说的,完全可选。

Next, it tells you to enter a number.接下来,它会告诉您输入一个数字。 Each number has a specific word.每个数字都有一个特定的单词。

Then, it's time to guess.然后,是时候猜测了。 I should explain what will happen.我应该解释会发生什么。 Let's say the word is secret.假设这个词是秘密的。 That's 6 letters.那是6个字母。

It would look like this:它看起来像这样:

_ _

_ _

_ _

_ _

_ _

_ _

Then it asks you to start guessing.然后它要求你开始猜测。 If you had your 10 tries, you lose.如果你尝试了 10 次,你就输了。 Let's say you managed to guess an "s".假设您设法猜到了一个“s”。 This happens:有时候是这样的:

s s

_ _

_ _

_ _

_ _

_ _

Hope this explains everything.希望这能解释一切。 I'm working on this code and planning to add a party mode next.我正在编写此代码并计划接下来添加派对模式。

Have a great day =)祝你有美好的一天 =)

Phantom幻影

import time
    time.sleep(5)
    print('Welcome to... hangman!')
    time.sleep(2)
    print("Are you ready? Ok, let's start.")
    time.sleep(3)
    name =input("What is your name? ")
    time.sleep(1)
    print("Hello, " + name + ". Time to play hangman! I wish you good luck- you'll need it.")
    time.sleep(3)
    darealword=int(input('Please enter a number. 1-30 only> '))
    if darealword==1:
        word='hypothesize'
    elif darealword==2:
        word='tube'
    elif darealword==3:
        word='blow'
    elif darealword==4:
        word='volume'
    elif darealword==5:
        word='parachute'
    elif darealword==6:
        word='biography'
    elif darealword==7:
        word='paragraph'
    elif darealword==8:
        word='abortion'
    elif darealword==9:
        word='exaggerate'
    elif darealword==10:
        word='complain'
    elif darealword==11:
        word='diagram'
    elif darealword==12:
        word='produce'
    elif darealword==13:
        word='abnormal'
    elif darealword==14:
        word='account'
    elif darealword==15:
        word='interactive'
    elif darealword==16:
        word='jump'
    elif darealword==17:
        word='goalkeeper'
    elif darealword==18:
        word='glimpse'
    elif darealword==19:
        word='story'
    elif darealword==20:
        word='coal'
    elif darealword==21:
        word='weave'
    elif darealword==22:
        word='dynamic'
    elif darealword==23:
        word='credibility'
    elif darealword==24:
        word='rhythm'
    elif darealword==25:
        word='trunk'
    elif darealword==26:
        word='admire'
    elif darealword==27:
        word='observation'
    elif darealword==28:
        word='rough'
    elif darealword==29:
        word='representative'
    else:
        word='thought'
    time.sleep(3)
    print("Start guessing... you can do this.")
    time.sleep(1)
    guesses = ''
    turns = 10
    while turns > 0:         
        failed = 0               
        for char in word:      
            if char in guesses:    
                print(char,)
            else:
                print("_",)    
                failed += 1    
        if failed == 0:
            time.sleep(5)        
            print('Aaaaaaand... you...') 
            time.sleep(3)
            print('won!!!!! I congratulate you, '+ name +'.')
            break              
        print
        guess = input("Guess a character> ") 
        guesses += guess                    
        if guess not in word:  
            turns -= 1        
            print("Sorry, this character isn't in the word. Don't get it wrong next time.")    
            # print("You have", + turns, 'more guesses')
            if turns == 0:        
                print("Aaaaaaand... you...")
                time.sleep(3)
                print("lost. I feel bad. Better luck next time. And if you're wondering, the word is "+ word +'.')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM