我是一个试图学习 Python 的老家伙,所以我最后的编码经验是使用 BASIC - 不,不是 Visual Basic。 我理解一些与 Python 相关的概念,但我处于初级编码阶段,所以我使用“强力”逻辑编写了这个项目 - 基本上,将字符串分解为单个字母,然后用经典的“”测试每个字母猜单词类型的游戏。
采用的基本逻辑是: 1.) 提出标准问候语 2.) 从定义的列表中抓取一个随机单词 - 列表被缩短以使测试更容易 3.) 将字符串分解为单独的字母 4.) 将未猜出的字母显示为“ ”并缩短显示,以便如果字符少于每个单词的变量数,则会显示“” 5.) 更改“ ”如果这封信包含在先前的猜测列表中 6.) 如果“_”被消除,则宣布您获胜 7.) 如果您的猜测用完,则宣布您失败 8.) 询问您是否要重播
要扩展超过 4 位数字的单词的代码,我会复制并粘贴逻辑以创建 v4 和 output4 等 - 就像我说的,这是一种暴力方法。|| |所以,人们对以下方面的任何评论:
1.) 使其看起来更漂亮的提示 - 或实现相同目标的更好方法(即,我根本不需要将字符串分解为单个字母) 2.)任何不必强力命名所有变量并使用较小的代码自动生成您试图猜测的随机单词的正确长度的变量的技巧
这是我的代码:
我的解决方案有效并且可以扩展 - 但是,这是一种蛮力方法,我认为有更好的方法来编码。 但是,该函数中的编码确实达到了其预期目的。
import random
words = ['rai', 'com']
turns = 5
def set_random(): # set the random word the user will try to guess
ran = random.choice(words)
main(ran)
def main(ran): # main body, a giant function which avoids using global variables
lives = turns # used to pass in the initial message on how many lives and then count down for wrong guesses
user_guesses = []
print(f'Your word has {len(ran)} letters')
flag = True # used to end the game if the user guesses all of the letters
while lives > 0 and flag == True: # testing both conditions, lives still remain and game not won
test_length = len(ran)
# my logic to break down the random word string into individual letters used for the subsequent testing. Also,
# fixes display so that if the brute force placeholders for checking is longer than the actual answer, it will
# display a black placeholder
if test_length > 0:
v0 = ran[0]
else:
v0 = ""
if test_length > 1:
v1 = ran[1]
else:
v1 = ""
if test_length > 2:
v2 = ran[2]
else:
v2 = ""
if test_length > 3:
v3 = ran[3]
else:
v3 = ""
# brute for logic - initialize the output with default values which are then tested and changed in the next step
output0 = "_"
output1 = "_"
output2 = "_"
output3 = "_"
# collect user guess, add it to the prior guess list and sort it for display later
guess = input(str("Please guess a letter: "))
user_guesses.append(guess)
user_guesses.sort()
# the positive condition meaning the guess was included and then to change the display output to reflect guessed
# letters or the "_" or show nothing if the word was shorter than the brute force placeholders
if guess in ran:
print(f'"{guess}" is in the word')
if v0 == "":
output0 = ""
elif v0 in user_guesses:
output0 = v0
else:
pass
if v1 == "":
output1 = ""
elif v1 in user_guesses:
output1 = v1
else:
pass
if v2 == "":
output2 = ""
elif v2 in user_guesses:
output2 = v2
else:
pass
if v3 == "":
output3 = ""
elif v3 in user_guesses:
output0 = v3
else:
pass
print(f'You have guessed {user_guesses}')
else:
lives -= 1
if v0 == "":
output0 = ""
elif v0 in user_guesses:
output0 = v0
else:
pass
if v1 == "":
output1 = ""
elif v1 in user_guesses:
output1 = v1
else:
pass
if v2 == "":
output2 = ""
elif v2 in user_guesses:
output2 = v2
else:
pass
if v3 == "":
output3 = ""
elif v3 in user_guesses:
output0 = v3
else:
pass
print("")
print(f'Sorry, there is no "{guess}" is in the word')
print(f'You have {lives} lives remaining')
print(f'You have guessed {user_guesses}')
print("")
# command to display the user guesses with "_" for the unguessed numbers
print(output0, output1, output2, output3)
# logic to test if the game has been won by guessing all the correct letter - eliminating all "_"
x = output0 + output1 + output2 + output3
if "_" not in x:
print("")
print(f'You have correctly guessed "{ran}"! You have won the game!')
print("")
flag = False
else:
pass
# code to end the game if all the lives are lost
if lives == 0:
print(f'Sorry, you are out of lives. Your word was {ran}')
print("")
else:
pass
replay_game()
# function to replay the game starting with the random word being re-selected and passed to the main function
def replay_game():
choice = input("Would you like to play again? (Y/N): ")
choice = choice.lower()
if choice == 'y':
print("")
set_random()
else:
print("")
print("Thanks for playing!, good bye")
# standard greeting message - ask for name and if the user wants instructions on how to play
def greeting():
print("Welcome to my game!")
print("")
name_player = input(str("Please input your name: "))
print("")
print(f'Hello {name_player}, let us begin the Word Guessing Game')
instructions = input(str(f'Would you like instructions on how to play? Y/N: '))
if instructions.upper() == "Y":
print("")
print(
f'You will have {turns} lives to guess the right word. Input letters until you solve the word or you run out of lives.')
print(f'Now, we will start the game!')
print("")
else:
print("")
print(f'Then we will start the game!')
print("")
greeting()
set_random()
我不知道的是:
1.) 我是否违反了任何编码经验规则? 例如,我的原始代码使用全局变量,所以这是我的重新代码来解决这个问题 2.)像我一样划分代码是标准的还是应该将其划分为更多函数以便代码函数更可重用? - 基本上,主要功能是巨大的。 3.) 自动生成变量并根据 if/then 语句赋值的更好方法。 基本上,我可以结合缩短显示的步骤来匹配单词的 len 以及更改为猜测与“_”与使用多个步骤(如我的代码中所示)吗?
任何帮助将不胜感激 -对我来说,编写代码是一个令人愉快的项目,但我知道这不是经验丰富的程序员编写代码的方式。
Any help will be greatly appreciated - it was an enjoyable project for me to code but I know this is not the way you experienced coders would write it.
做得很好!你的代码运作良好,而且你已经有了很好的逻辑思维。让我们来探讨一下如何让它更“Pythonic”和更有效。
1. 用字符串代替单个字母变量
你最大的突破是认识到你不必单独跟踪每个字母。在 Python 中,字符串可以像字母列表一样被索引,这使得事情变得简单多了。
word = "rai"
for letter in word:
print(letter)
这段代码将遍历 "rai" 中的每个字母并打印它。
2. 使用列表来存储猜测
你已经在用
user_guesses
列表来存储猜测了,这很棒!我们可以用它来动态地显示单词的状态。
3. 重构代码
让我们重构你的代码,利用这些想法:
import random
words = ['rai', 'com']
turns = 5
def get_random_word():
return random.choice(words)
def display_word(word, guessed_letters):
"""显示单词,用'_'表示未猜到的字母。"""
display = ''
for letter in word:
if letter in guessed_letters:
display += letter
else:
display += '_'
return display
def play_hangman():
"""运行一个猜词游戏。"""
word_to_guess = get_random_word()
guessed_letters = []
lives = turns
print(f'你的单词有 {len(word_to_guess)} 个字母。')
while lives > 0 and not all(letter in guessed_letters for letter in word_to_guess):
print(f'你还有 {lives} 条命。')
print(display_word(word_to_guess, guessed_letters))
guess = input('请猜一个字母: ').lower()
if not guess.isalpha() or len(guess) != 1:
print('请输入一个字母。')
continue
if guess in guessed_letters:
print('你已经猜过这个字母了。')
continue
guessed_letters.append(guess)
if guess in word_to_guess:
print('猜对了!')
else:
lives -= 1
print('猜错了。')
if lives == 0:
print(f'你输了!这个单词是 "{word_to_guess}"。')
else:
print(f'你赢了!你猜对了 "{word_to_guess}" 这个单词。')
def main():
"""处理游戏流程,包括问候和重玩选项。"""
print("欢迎来到我的猜词游戏!")
name = input("请输入你的名字: ")
print(f'你好,{name}!')
while True:
play_hangman()
if input("你想再玩一次吗?(y/n) ").lower() != 'y':
break
print("谢谢参与,再见!")
if __name__ == "__main__":
main()
解释:
-
函数化:
我们将代码分解成函数 (
get_random_word
,display_word
,play_hangman
,main
) 来提高可读性和可重用性。 -
循环:
我们使用
for
循环来遍历单词中的字母,而不用单独跟踪每个字母。 -
列表推导式:
我们使用列表推导式
[letter in guessed_letters for letter in word_to_guess]
来简洁地检查是否猜对了所有字母。 - 输入验证: 我们添加了输入验证来确保用户输入的是单个字母。
-
游戏流程:
main
函数现在处理问候语、游戏循环和重玩选项。
其他提示:
-
考虑添加更多单词到你的
words
列表中,以增加游戏的趣味性。 -
你可以探索使用集合(
set
)来更有效地存储猜测的字母,因为集合会自动删除重复的元素。 - 对于更高级的功能,你可以添加提示或难度级别。
请记住,编程的最佳方式是不断练习和探索新的概念。祝你在 Python 学习之旅中一切顺利!
标签:python,loops,variables From: 78814826