我是QBasic和一般编码的新手,我正在做一个猜游戏,但它不起作用。我必须制作一个不使用GOTO
或Do
语句的猜谜游戏,并给用户5次机会。这是代码:
chances%=1
dim guess as integer
dim answer as string
randomize timer
rndnum=INT(RND*100+1)
'makinng a title
color 5
locate 12,32
print "welcome to My guessing game."
Print "think of a number between 1 and 100."
color 12
Input "enter you guess: ",guess
while chances%<4
if guess >rndnum then
print "wrong, too high"
elseif guess <rndnum then
print "wrong, too low"
elseif guess=rndnum then
print "your guessed the number!"
end if
wend
chances%=chances%+1
color 14
Print "you took "; chances%;"to guess the number"
color 3
Input would you like to play again (yes/no)?", answer
wend
if answer = "yes" then
?
else
print "have a good day"
end if
end
您要求输入一次,然后您有一个闭环,检查答案,直到尝试次数超过四次,但尝试次数不会增加,因为Wend命令告诉它在不再次提问或根本不增加计数器的情况下重新开始循环。这就是所谓的"无休止循环",因为循环内的条件不会改变。我就到此为止,看看你是否能想出如何纠正这两个问题——注意,只解决其中一个问题并不能阻止它成为一个"无休止的循环"——你必须同时解决这两个。
您可以使用WHILE...WEND
运行循环,直到机会变为0
....(rest of code)
chances = 5
WHILE chances > 0
....
if guess > rndnum then
print "wrong, too high"
chances = chances - 1
elseif guess < rndnum then
print "wrong, too low"
chances = chances -1
....
WEND
你的猜测必须在while-wind循环中,当给出正确答案时,几率%必须设置为4,否则你会得到一个永恒的循环。也有必要在第一次猜测后直接增加机会%。请参阅稍微更改的代码。还请查看猜测并更改您的行,表示您将x猜测从机会%改为猜测
chances%=0
while chances% < 4
Input "enter your guess: ",guess
chances% = chances% + 1
if guess > rndnum then
print "wrong, too high"
elseif guess < rndnum then
print "wrong, too low"
elseif guess = rndnum then
print "your guessed the number!"
guesses = Chances%
chances% = 4
end if
wend
如果你仍然有问题,我在这里发现:
Input would you like to play again (yes/no)?", answer
if answer = "yes"
您必须将answer更改为answer$,因为您无法将字符串保存在数值中。
这个片段演示了QB64:中的数字猜测游戏
REM guessing game.
Tries = 5
DO
PRINT "Guess a number between 1 and 100 in"; Tries; "guesses."
Number = INT(RND * 100 + 1)
Count = 1
DO
PRINT "Enter guess number"; Count; " ";
INPUT Guess
IF Guess = Number THEN
PRINT "Correct! You guessed it in"; Count; "tries."
EXIT DO
END IF
IF Guess > Number THEN
PRINT "Wrong. Too high."
ELSE
PRINT "Wrong. Too low."
END IF
Count = Count + 1
IF Count > Tries THEN
PRINT "The number was"; Number
PRINT "You didn't guess it in"; Tries; "tries."
EXIT DO
END IF
LOOP
DO
PRINT "Play again(yes/no)";
INPUT Answer$
IF LCASE$(Answer$) = "no" THEN
END
END IF
IF LCASE$(Answer$) = "yes" THEN
EXIT DO
END IF
LOOP
LOOP
END