Как отобразить предыдущие буквы слова на следующем шаге печати? - PullRequest
0 голосов
/ 24 марта 2020

Прошу вашей снисходительности в этом отношении, потому что я только начинаю Python программирование. Я написал программу, которая представляет собой игру палача. Это игра, в которой мы угадываем букву случайного слова. Я хотел бы сохранить вывод, чтобы ранее угаданные буквы можно было увидеть на следующем шаге. Это мой код:


import random
import collections


def code_of_hangamn_game():   
    list_of_words=['victory','python','code','computer','knife','mouse','language','calculator',
    'destination','desire','scientist','mathematics','inventor','speaker','cosmos','building',
    'emergency','economy','dictionary','printer','accommodation']
    random_word=random.choice(list_of_words)
    number_of_repetitions_of_letters= collections.Counter(random_word)
    print(random_word)
    player_chances=10
    letters_to_guess = len(random_word)
    dictionary_of_letters={}
    while player_chances>0:
        input_letter=input("\nYou random a word which consist of " +str(len(random_word))+" letters. Please enter a single letter. ")
        if input_letter.isalpha()==True and len(input_letter)==1:
            if input_letter in random_word:
                if input_letter in dictionary_of_letters:
                    print("\nYou change the entered letter, because this letter was entered")

                else:
                    dictionary_of_letters[input_letter]={number_of_repetitions_of_letters.get(input_letter)}
                    number_of_repetitions_of_letter = number_of_repetitions_of_letters.get(input_letter)
                    letters_to_guess -= number_of_repetitions_of_letter
                    print("\nYou guessed that " + input_letter + " is in a random word.You have " + str(letters_to_guess) + " letters to guess.")
                    for index in range(len(random_word)):
                        if random_word[index]==input_letter:
                            print(random_word[index], end="")
                        else:
                            print("-", end="")
                    if letters_to_guess==0:
                        print("\nYou win! Congratulations")
                        exit()
            else :
                player_chances -=1
                print ("\nYou didn't guess the letter. You have " + str(player_chances) + " chances left.")
                if player_chances==0:
                    print("\nUnfortunately you lost. Play again")
                    exit()


        if input_letter.isalpha()==False or len(input_letter)!=1:
            print("\nYou didn't enter a single letter. Please try again ")


code_of_hangamn_game()

Это мой текущий вывод:

code

You random a word which consist of 4 letters. Please enter a single letter. c

You guessed that c is in a random word.You have 3 letters to guess.
c---
You random a word which consist of 4 letters. Please enter a single letter. o

You guessed that o is in a random word.You have 2 letters to guess.
-o--
You random a word which consist of 4 letters. Please enter a single letter. q

You didn't guess the letter. You have 9 chances left.

You random a word which consist of 4 letters. Please enter a single letter. w

You didn't guess the letter. You have 8 chances left.

You random a word which consist of 4 letters. Please enter a single letter. d

You guessed that d is in a random word.You have 1 letters to guess.
--d-
You random a word which consist of 4 letters. Please enter a single letter. fw2

You didn't enter a single letter. Please try again

You random a word which consist of 4 letters. Please enter a single letter. 2

You didn't enter a single letter. Please try again

You random a word which consist of 4 letters. Please enter a single letter. e

You guessed that e is in a random word.You have 0 letters to guess.
---e
You win! Congratulations

Я бы хотел, чтобы вывод был в такой форме:

code

You random a word which consist of 4 letters. Please enter a single letter. c

You guessed that c is in a random word.You have 3 letters to guess.
c---
You random a word which consist of 4 letters. Please enter a single letter. o

You guessed that o is in a random word.You have 2 letters to guess.
co--
You random a word which consist of 4 letters. Please enter a single letter. q

You didn't guess the letter. You have 9 chances left.

You random a word which consist of 4 letters. Please enter a single letter. w

You didn't guess the letter. You have 8 chances left.

You random a word which consist of 4 letters. Please enter a single letter. d

You guessed that d is in a random word.You have 1 letters to guess.
cod-
You random a word which consist of 4 letters. Please enter a single letter. fw2

You didn't enter a single letter. Please try again

You random a word which consist of 4 letters. Please enter a single letter. 2

You didn't enter a single letter. Please try again

You random a word which consist of 4 letters. Please enter a single letter. e

You guessed that e is in a random word.You have 0 letters to guess.
code

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

Ответы [ 2 ]

2 голосов
/ 24 марта 2020

Вы можете попробовать этот код:

word = 'pythony'
guess = 'y'
w = '-' * len(word)

def split(word): 
  return [char for char in word]  

word_split = split(word)

word_guess_split = split(w)

def find_char(word, guess):
  b = []
  for pos, char in enumerate(word):
    if char == guess:
      b.append(pos)
  return b

def insert_char(word_guess, guess, pos):
  for i in range(len(pos)):
    word_guess[pos[i]] = guess
  return word_guess

pos = find_char(word_split, guess)

wg = insert_char(word_guess_split, guess, pos)

print(''.join(wg))

Выход:

-y----y

Угадайте больше:

guess_1 = 'p'

pos_1 = find_char(word_split, guess_1)

wg = insert_char(word_guess_split, guess_1, pos_1)

print(''.join(wg))

Выход:

py----y
0 голосов
/ 24 марта 2020

Я пытался использовать ваш код, но это не сработало, вы можете сказать мне, почему?

import random
import collections
def split (word):
    return[letter for letter in word]

def find_char(random_word, guess):
    list_of_position=[]
    for pos, letter in enumerate(random_word):
        if letter == guess:
            list_of_position.append(pos)
        return list_of_position

def insert_letter(word_guess, guess, pos):
    for i in range(len(pos)):
        word_guess[pos[i]] = guess
    return word_guess

def code_of_hangamn_game():   
    list_of_words=['victory','python','code','computer','knife','mouse','language','calculator',
    'destination','desire','scientist','mathematics','inventor','speaker','cosmos','building',
    'emergency','economy','dictionary','printer','accommodation']
    random_word=random.choice(list_of_words)
    number_of_repetitions_of_letters= collections.Counter(random_word)
    hidden_word="-"*len(random_word)
    print(random_word)
    random_word_split=split(random_word)
    hidden_word_split=split(hidden_word)
    player_chances=10
    letters_to_guess = len(random_word)
    dictionary_of_letters={}
    while player_chances>0:
        input_letter=input("\nYou random a word which consist of " +str(len(random_word))+" letters. Please enter a single letter. ")
        if input_letter.isalpha()==True and len(input_letter)==1:
            if input_letter in random_word:
                if input_letter in dictionary_of_letters:
                    print("\nYou change the entered letter, because this letter was entered")

                else:
                    dictionary_of_letters[input_letter]={number_of_repetitions_of_letters.get(input_letter)}
                    number_of_repetitions_of_letter = number_of_repetitions_of_letters.get(input_letter)
                    letters_to_guess -= number_of_repetitions_of_letter
                    print("\nYou guessed that " + input_letter + " is in a random word.You have " + str(letters_to_guess) + " letters to guess.")
                    pos = find_char(random_word_split, input_letter)
                    wg = insert_letter(hidden_word_split, input_letter, pos)
                    print(''.join(wg))
                    if letters_to_guess==0:
                        print("\nYou win! Congratulations")
                        exit()
            else :
                player_chances -=1
                print ("\nYou didn't guess the letter. You have " + str(player_chances) + " chances left.")
                if player_chances==0:
                    print("\nUnfortunately you lost. Play again")
                    exit()


        if input_letter.isalpha()==False or len(input_letter)!=1:
            print("\nYou didn't enter a single letter. Please try again ")

code_of_hangamn_game()

это вывод:

knife

You random a word which consist of 5 letters. Please enter a single letter. n

You guessed that n is in a random word.You have 4 letters to guess.
-----

You random a word which consist of 5 letters. Please enter a single letter. k

You guessed that k is in a random word.You have 3 letters to guess.
k----

You random a word which consist of 5 letters. Please enter a single letter. i

You guessed that i is in a random word.You have 2 letters to guess.
k----

You random a word which consist of 5 letters. Please enter a single letter. f

You guessed that f is in a random word.You have 1 letters to guess.
k----

You random a word which consist of 5 letters. Please enter a single letter. e

You guessed that e is in a random word.You have 0 letters to guess.
k----

You win! Congratulations

код распознает только первую букву а следующих букв нет. Можете ли вы исправить код в моем примере

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...