我刚刚开始练习python。这是我制作的游戏(Hangman)的代码。我想知道如何缩短此代码并使它看起来更专业。
# importing random function
import random, hanged
from word_meaning import meanings
# Dictionary of random words
word_dict = '''whistle,
park,
picayune,
attach,
grubby,
gusty,
neck,
necessary,
day,
compete,
memory,
interfere,
sophisticated,
lumpy,
spiky,
frail'''.split(',\n')
# System chooses a random word
rand_word = word_dict[random.randint(0, len(word_dict)-1)]
print('Welcome to HANGMAN.\nGuess correct letters to complete the hidden word, Else hangman will be Hanged')
n = len(rand_word)
hidden_word = ((n-1)*'*')
hidden_word_1 = hidden_word.split('*')
print(f'Hidden Word: {hidden_word}*')
print(f'Hint: {meanings[str(rand_word)]}'
这是从另一个文件导入的字典。它给出了隐藏单词的含义作为提示
chances = 10
def user_lose():
global chances
print(f'Oops wrong guess\n Chances Left : {chances - 1}')
if chances > 1:
chances -= 1
user_guess()
else:
hanged.hangman()
hanged.Hangman()这是显示hangman图片的函数。从另一个文件导入
def user_guess():
global chances
if '' in hidden_word_1:
user_input = str(input('\nGuess a letter: ')[0]).lower()
if user_input in rand_word:
if user_input in hidden_word_1:
user_lose()
else:
if chances > 0:
letter_index = rand_word.index(user_input)
letter_index_r = rand_word.rindex(user_input)
hidden_word_1[letter_index] = user_input
hidden_word_1[letter_index_r] = user_input
print(hidden_word_1)
user_guess()
else:
user_lose()
else:
print('Hurrah, You saved Hangman')
user_guess()