【发布时间】:2020-02-19 01:59:42
【问题描述】:
以下是我正在尝试构建的概要:
- 从用户那里获取关于字长的输入
- 根据用户输入的字长从文本文件中获取字
- 从用户输入中获取尝试次数
- 将单词显示为 *
- 获取提示信输入 用户
-
运行游戏
- 首先显示 * 中的单词
- 显示剩余尝试次数
- 提示输入下一个字母
- 如果输入与单词匹配
- 打印“你猜对了”
- 在适当的空格处替换字母中单词中的 * 并打印
- 打印剩余尝试次数
- 打印猜出的字母
- 提示输入下一个字母 *这个过程一直持续到该单词的所有正确字母都被猜到为止
- 打印“你赢了”
- 如果输入与单词不匹配
- 打印“你猜错了”
- 打印 * 中的单词
- 打印剩余尝试次数
- 打印猜出的字母
- 提示输入下一个字母 *这一直持续到剩余的 attepmt 为 0
- 打印“你输了”
- 如果尝试次数为 0
- 打印“没有剩余尝试”
- 打印正确的单词
- 如果输入与单词匹配
代码只有在输入的字母不变的情况下才有效。
假设游戏词是“Rain”,代码只有在用户输入:“R”、“A”、“I”、“N”时才会起作用。
如果输入的字母乱码,如“A”、“R”、“I”、“N”,代码将不起作用。
我相信它可以通过使用枚举的迭代来实现,但我不确定如何。
这是我的代码:
import random
WORDS = "wordlist.txt"
"""Getting Length input from user and selecting random word from textfile"""
def get_word_length_attempt():
max_word_length = int(input("Provide max length of word [4-16]: "))
current_word = 0
word_processed = 0
with open(WORDS, 'r') as f:
for word in f:
if '(' in word or ')' in word:
continue
word = word.strip().lower()
if len(word) > max_word_length:
continue
if len(word) < 4:
continue
word_processed += 1
if random.randint(1, word_processed) == 1:
current_word = word
return current_word
"""Getting input of number of attempts player wants to have"""
def get_num_attepmts():
num_attempt = int(input("Provide number of attempts you want: "))
return num_attempt
"""Displaying word in *"""
def display_word_as_secret():
display_word = '*' * len(get_word_length_attempt())
print(display_word)
"""Getting hint letter from user input"""
def get_user_letter():
user_letter = input("Enter letter: ").lower()
if len(user_letter) != 1:
print("Please Enter single letter")
else:
return user_letter
"""Starting Game"""
def start_game():
game_word = get_word_length_attempt()
attempts_remaining = get_num_attepmts()
print('Your Game Word: ' + game_word)
print('Your Game Word: ' + '*'*len(game_word))
print('Attempts Remaining: ' + str(attempts_remaining))
guessed_word = []
while attempts_remaining > 0:
next_letter = get_user_letter()
if next_letter in game_word:
print('You guessed correct')
guessed_word.append(next_letter)
print('Your Game Word: ' + game_word)
print('Your Game Word: ' + '*' * len(game_word))
print('Attempts Remaining: ' + str(attempts_remaining))
correct_word = "".join(guessed_word)
print(guessed_word)
if correct_word == game_word:
print('you won')
break
else:
print('The letter in not in the game word')
attempts_remaining -= 1
print('Your Game Word: ' + game_word)
print('Your Game Word: ' + '*' * len(game_word))
print('Attempts Remaining: ' + str(attempts_remaining))
else:
print('no attempts left')
print('You Lost')
print('The Word is: ' + game_word)
start_game()
【问题讨论】:
-
这篇文章很棒。您已经清楚地展示了您在尝试解决问题时开发的伪代码以及在实现它时生成的代码。不过,这需要其他人为您调试很多代码。我认为您可以将问题分解为更简单的描述。与其描述当您键入单词的所有字母时会发生什么,不如只查看用户键入的第一个字母。因此,在您的示例中,要猜测的单词是“RAIN”。当用户输入“R”作为第一个字母时会发生什么?您的程序是否正确显示
R***? -
如果用户输入“A”作为第一个字母怎么办?您的程序是否正确显示
*A***?如果不是,它会显示什么? -
感谢@Code-Apprentice!!!我仍在学习如何正确提出问题。我还不能按照你的建议去做。这是因为我没有完全掌握 Python 的迭代部分。老实说,我试过了,但我做不到。我仍在修改代码,希望明天能够做到。到目前为止,我的查询已解决:-)
标签: python python-3.x