通过变量来检查它是否不包含字符串
def main():
#word = input("Word to guess for player 2:")
word = ['h','e','l','l','o']
word2 = "hello"
#make a list of _ the same length as the word
display =[]
for i in range (0,len(word)):
display.append("_")
chances = int(input("Number of chances to guess word:"))
if len(word)== 11:
print ("Your word is too long. It has to be 10 charecters or less")
else:
word = word
if chances < len(word):
answer = input("Your word is {0} letters long , are you sure you don't want more chances? Yes or no?". format (len(word)))
if answer == "no":
chances= int(input("Number of chances:"))
else:
chances = chances
("Ok then lets continue with the game")
print ("Player 2, you have {0} chances to guess the word.". format (chances))
won = False
underscore = False
while chances > 0 and won == False and underscore == False:
guess = input("Enter your guess: ")
gC=False
for i in range (0,len(word)):
if guess == word[i]:
gC=True
display[i]=guess
if not gC:
chances = chances - 1
display2 = ""
for i in display:
display2 = display2 + i + " "
由于某些原因,当我声明我的while循环时,代码不起作用,因为游戏继续进行,直到用户用完猜测' 。有没有人有任何建议,我该如何解决这个问题?通过变量来检查它是否不包含字符串
当用户通过猜测所有字母赢得游戏时,您从未将won
设置为True。
也强调从未设置为真,不知道是什么。 – VoronoiPotato 2013-05-08 16:58:41
我忘了在我的程序中包含这段代码:对于我在显示中: 如果“_”不在显示中: 下划线=真 如果不是下划线: won = True – thatcoolkid 2013-05-08 17:10:59
这不是你原来的问题的答案,而是更多的代码审查,但也许你会发现它很有用。
word = list('hello') # replaces manual splitting of string into letters
display = [ '_' ] * len(word) # replaces build-up using for-loop
chances = input("Number ... ") # already returns int if the user enters an int
# but will evaluate any valid python expression the
# user enters; this is a security risk as what
# ever is done this way will be done using your
# permissions
chances = int(raw_input("Number ...")) # probably what you wanted
...
else:
word = word # does nothing. remove this line and the "else:" above
chances -= 1 # replaces 'chances = chances - 1' and does the same
display2 = ' '.join(display) # replaces the for-loop to build display2
此外,我建议使用更好的名称。在这种情况下,诸如display2
或gC
等变量没有多大帮助。在专业编程中,你必须记住,你正在编写你的代码(也是,甚至主要)为下一个必须维护它的开发者。因此,使其可读性和可理解性。改为选择名称,如displayString
或guessedCorrectly
。
使用'while while chances> 0而不是赢得和不下划线;测试是否永远不需要布尔型“== False”或“== True”。 – 2013-05-08 17:02:23