忽略 if 语句设置的边界但仍能识别它们的条件问题



我一直在做一个简单的程序,你被分配10个随机数字,并被要求猜测下一个数字是高还是低。

我的程序在检测答案错误时遇到了问题,因为它只是让不正确的猜测过去。我直到最近才遇到这个问题,当时我不得不修复一个游戏无法在随机时间继续的bug。

我不知道该怎么解决它,因为我已经用尽了我的选择。如有任何帮助,不胜感激。

from random import randint
print("1. This game is for a single player.")
print()
print("2. At the start, the program randomly generates a list of 10 numbers to"
"represent playing cards of a single suit.")
print()
print("3. The first card is flipped, and the player is asked to guess whether"
"the next card is higher or lower than the known flipped card.")
print()
print("4. If the player guesses correctly, they guess the next card in the"
"sequence.")
print()
print("5. If the player’s guess is incorrect at any point along the sequence, "
"they lose the game.")
print()
print("6. If the player correctly guesses all cards, they win the game.")
print()
#Number Generation--------------------------------------------------------------
numblist = []
while len(numblist) < 10:
numb = randint(1, 10)
if numb not in numblist:
numblist.append(numb)
#Board--------------------------------------------------------------------------
turn = 0 
boardline = []
numblist.append(0)
boardline.append(numblist[turn])
print(boardline)
#Game---------------------------------------------------------------------------
# Prints out list to check for H or L
print(numblist)
# Variable Setup
turn = 1
selectedch = 0
gamenotbroken = True
guesswrong = False
choicevalid = False
gameactive = True
print("Will the next value be Higher (H) or Lower (L)? ")
while gameactive == True:
if len(boardline) > 9:
print("You have won!!")
gameactive = False
choicevalid = False

elif guesswrong == True:
print("You lost try again")
gameactive = False
choicevalid = False

if gamenotbroken == True:
choice = input("Guess: ")
if choice.lower() not in ['h', 'higher', 'l', 'lower']:
print("Not a valid option")
else:
choicevalid = True

if choicevalid == True:
if choice in ['h', 'higher'] and  selectedch == 0:
if numblist[turn] > numblist[turn + 1]:
print("It was higher")
choicevalid = False
gameactive = True
selectedch = 1

if numblist[turn] < numblist[turn + 1] and selectedch == 1:
guesswrong = True

if choice in ['l', 'lower'] and selectedch == 0:
if numblist[turn] < numblist[turn + 1]:
print("It was lower")
choicevalid = False
gameactive = True
selectedch = 2

if numblist[turn] > numblist[turn + 1] and selectedch == 2:
guesswrong = True


print("Will the next value be Higher (H) or Lower (L)? ")
boardline.append(numblist[turn])
print(boardline)
turn = turn + 1
print("Turn", turn)
selectedch = 0 

#Debug
#print("GMATV: ", gameactive)
#print("CHVLD: ", choicevalid)
#print("GUWRN: ", guesswrong)

似乎代码的主要问题是boardline(检查猜测是否正确)有第一个可猜测的数字(您只添加了第一个),但不是其余的(+1只是使它循环回到相同的数字),所以要么切换

boardline.append(numblist[turn])boardline = numblist

或将底部的boardline.append(numblist[turn])移动到循环的顶部。而且turn应该等于0(列表中的第一个元素是第0个元素)

你似乎也有很多浮动变量(你不需要猜测错误和选择有效的变量),所以你可能想要清理。

最后避免空的print语句(它不是很糟糕,但它会使事情变得混乱),要添加新行,你可以在字符串的末尾添加n,例如print("textn")

最新更新