【发布时间】:2016-05-28 05:32:13
【问题描述】:
我正在尝试仅使用 while 循环创建一个刽子手游戏:
我正在尝试显示一个秘密单词的破折号,或者如果该字母已被猜到并且是可变的正确字母,则在正确的位置显示正确的字母,其余的将是破折号 - 全部使用 while 循环。
但是,如果字符串正确的字母为空,因为它将在游戏开始时显示破折号。
我不允许使用 for 循环或 in,只能使用 while 循环,目前遇到以下错误:
tmp_letter = p_correct_letters[count]
IndexError: string index out of range
我的代码:
from hangman_lib import HANGMAN
import hangman_lib
import random
words = ["ant","baboon","zebra"]
def main():
game_over = False
correct_letters = ""
incorrect_letters = ""
secret_word = get_word()
print("Welcome to Hangman!")
print(secret_word) # For testing purposes only
while not game_over:
display_board(secret_word, correct_letters, incorrect_letters)
guess = get_guess(correct_letters + incorrect_letters)
if found_letter(guess, secret_word):
correct_letters = correct_letters + guess
else:
incorrect_letters = incorrect_letters + guess
game_over = has_won(secret_word, correct_letters)
if not game_over:
game_over = has_lost(incorrect_letters)
if game_over:
display_board(secret_word, correct_letters, incorrect_letters)
''' Non temlate Code starts here '''
# Function returns random word from list of words
def get_word():
return random.choice(words)
def display_board(p_secret_word, p_correct_letters, p_incorrect_letters):
print(HANGMAN[len(p_incorrect_letters)])
print("\n")
print ("Guess a letter... ")
word_length = len(p_secret_word)
underscore = "_ "
to_display = ""
display_underscore = underscore * word_length
print(display_underscore)
print("\n")
print("Incorrect letters:", p_incorrect_letters)
index = 0
current_letter =""
tmp_letter =""
correct_length = len(p_correct_letters)
while index < word_length:
current_letter = p_secret_word[index]
count = 0
while count < correct_length:
tmp_letter = p_correct_letters[count]
if current_letter == tmp_letter:
to_display = to_display[count] + current_letter + " "
else:
to_display = underscore + " "
count = count + 1
index = index + 1
print(to_display, end = "")
# return current print statement
main()
【问题讨论】:
-
你的。缩进。已。走了。 野生.
-
更重要的是,您不能“返回当前打印语句”。
-
我会编写我自己的函数来模拟
for在while方面,然后使用它。真的,禁止for对任何事情都毫无用处,但会让您意识到for的用处。 -
您可以使用 for 循环编写解决方案,然后用 while 循环机械地替换每个 for 循环
标签: python python-3.5