Может ли кто-нибудь помочь мне с палачом?

1

Я использую python 2.7.1 для создания игры в палач. Я пытаюсь позволить пользователю выбрать, следует ли воспроизводить игру до окончания игры. Я пытаюсь использовать переменную keep_playing, но она не работает. Кроме того, в guesses=word_len * ['_'], я хочу иметь пробел между подчеркиваниями, потому что, если они склеиваются, я не вижу, сколько букв осталось. Это мой код палача:

from random import *
import os


keep_playing = True
def print_game_rules(max_incorrect,word_len):
    print"you have only 7 chances to guess the right answer"
    return

def get_letter():
    print
    letter = raw_input("Guess a letter in the mystery word:") 
    letter.strip()
    letter.lower()
    print
    os.system('cls')
    return letter
def display_figure(hangman):
    graphics = [
    """
        +--------+
         |
         |
         |
         |
         |
         |
     ====================
    """,
    """
        +-------
        |      o
        |
        |
        |
        |
    ====================
    """,
    """
        +-------
        |      o
        |      +   
        |      |
        |
        |
    ======================
    """,
    """
        +-------
        |       o
        |    ---+
        |       |
        |    
        |  
        |   
    =====================
    """,
    """
        +-------
        |       o
        |    ---+---
        |       |
        |        
        |         
        |     
        |
    =====================
    """,
    """
        +-------
        |       o
        |    ---+---
        |       |
        |      / 
        |     /   
        |    /     
        |     
    =====================
    """,
    """
        +-------
        |       o
        |    ---+---
        |       |
        |      / \   
        |     /   \  
        |    /     \    
        |     
    =====================
    """]

    print graphics[hangman]
    return



animals=["horse","donkey","dinosaur","monkey","cat","aligator","butterfly","buffallo","dragon"]
word=choice(animals)
word_len=len(word)
guesses=word_len * ['_']
max_incorrect=6
alphabet="abcdefghijklmnopqrstuvxyz"
letters_tried=""
number_guesses=0
letters_correct=0
incorrect_guesses=0


print_game_rules(max_incorrect,word_len)
while (incorrect_guesses != max_incorrect) and (letters_correct != word_len):
    letter=get_letter()
    if len(letter)==1 and letter.isalpha():
        if letters_tried.find(letter) != -1:
            print "You already picked", letter
        else:
            letters_tried = letters_tried + letter
            first_index=word.find(letter)
            if  first_index == -1:
                incorrect_guesses= incorrect_guesses +1
                print "The",letter,"is not the mystery word."
            else:
                print"The",letter,"is in the mystery word."
                letters_correct=letters_correct+1
                for i in range(word_len):
                    if letter == word[i]:
                        guesses[i] = letter

    else:
        print "Please guess a single letter in the alphabet."
    display_figure(incorrect_guesses)

    print ''.join(guesses)
    print "Letters tried so far: ", letters_tried
    if incorrect_guesses == max_incorrect:
        print "Sorry, too many incorrect guesses. You are hanged."
        print "The word was",word
        keep_playing = False
    if letters_correct == word_len:
        print "You guessed all the letters in the word!"
        print "The word was",word
        keep_playing = False



while keep_playing == False:
    user = raw_input("\n\tShall we play another game? [y|n] ")
    again = "yes".startswith(user.strip().lower())
    if again:
        keep_playing = True
    if not again:
        break

raw_input ("\n\n\nPress enter to exit")
Теги:
console

2 ответа

3

print ''.join(guesses) можно преобразовать в print ' '.join(guesses), задавая пробелы между буквами

вам нужно сделать keep_playing = False до while keep_playing == False:, а основной игровой цикл должен быть в функции, которая вызывается из этого цикла if keep_playing == True:

  • 1
    Промежутки между буквами. Я много пробовал на keep_playing , но так и не получил. Можете ли вы дать мне пример?
1

Следующее сделает то, что вы хотите сделать.

from random import *
import os


keep_playing = True
def print_game_rules(max_incorrect,word_len):
    print"you have only 7 chances to guess the right answer"
    return
def get_letter():
    print
    letter = raw_input("Guess a letter in the mystery word:") 
    letter.strip()
    letter.lower()
    print
    os.system('cls')
    return letter
def display_figure(hangman):
    graphics = [
    """
        +--------+
         |
         |
         |
         |
         |
         |
     ====================
    """,
    """
        +-------
        |      o
        |
        |
        |
        |
    ====================
    """,
    """
        +-------
        |      o
        |      +   
        |      |
        |
        |
    ======================
    """,
    """
        +-------
        |       o
        |    ---+
        |       |
        |    
        |  
        |   
    =====================
    """,
    """
        +-------
        |       o
        |    ---+---
        |       |
        |        
        |         
        |     
        |
    =====================
    """,
    """
        +-------
        |       o
        |    ---+---
        |       |
        |      / 
        |     /   
        |    /     
        |     
    =====================
    """,
    """
        +-------
        |       o
        |    ---+---
        |       |
        |      / \   
        |     /   \  
        |    /     \    
        |     
    =====================
    """]

    print graphics[hangman]
    return

while keep_playing:
    animals=["horse","donkey","dinosaur","monkey","cat","aligator","butterfly","buffallo","dragon"]
    word=choice(animals)
    word_len=len(word)
    guesses=word_len * ['_']
    max_incorrect=6
    alphabet="abcdefghijklmnopqrstuvxyz"
    letters_tried=""
    number_guesses=0
    letters_correct=0
    incorrect_guesses=0
    print_game_rules(max_incorrect,word_len)

    while (incorrect_guesses != max_incorrect) and (letters_correct != word_len):
        letter=get_letter()
        if len(letter)==1 and letter.isalpha():
            if letters_tried.find(letter) != -1:
                print "You already picked", letter
            else:
                letters_tried = letters_tried + letter
                first_index=word.find(letter)
                if  first_index == -1:
                    incorrect_guesses= incorrect_guesses +1
                    print "The",letter,"is not the mystery word."
                else:
                    print"The",letter,"is in the mystery word."
                    letters_correct=letters_correct+1
                    for i in range(word_len):
                        if letter == word[i]:
                            guesses[i] = letter
        else:
            print "Please guess a single letter in the alphabet."

        display_figure(incorrect_guesses)
        print ' '.join(guesses)
        print "Letters tried so far: ", letters_tried

        if incorrect_guesses == max_incorrect:
            print "Sorry, too many incorrect guesses. You are hanged."
            print "The word was",word
            break
        if letters_correct == word_len:
            print "You guessed all the letters in the word!"
            print "The word was",word
            break

    user = raw_input("\n\tShall we play another game? [y|n] ")
    again = "yes".startswith(user.strip().lower())
    if again:
        keep_playing = True
    else:
        break

raw_input ("\n\n\nPress enter to exit")

Ещё вопросы

Сообщество Overcoder
Наверх
Меню