python - 学习 Python - 数字游戏
问题描述
我是 Python 新手。我正在尝试编写一个小游戏,要求最终用户从 1 到 1000 中选择一个数字并将其保留在他们的脑海中(该数字未提供给程序)。该程序应该能够在 10 次猜测中找到数字。像往常一样,我走错了路。我的程序大部分时间都在工作,但有时它在 10 次以下的猜测中找不到数字。这是我的代码:
# script to guess a user's number between 1 and 1000 within 10 guesses
# import random so we can use it to generate random numbers
from random import randint
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
failed = False
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# if the lower and upper bounds match we've found the number
if lowerBound == upperBound:
print(f"\nYour number is {str(lowerBound)}. It took me '{str(numGuesses)} guesses!")
break
print(f"\nIs the number {str(myGuess)}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
# uncomment for var output
# print(f"\nGuesses = {str(numGuesses)}\nLower bound = {str(lowerBound)}\nUpper bound = {str(upperBound)}")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{str(numGuesses)} was too high")
if numGuesses == 10:
failed = True
break
upperBound = myGuess - 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'LOW':
print(f"\nGuess #{str(numGuesses)} was too low")
if numGuesses == 10:
failed = True
break
lowerBound = myGuess + 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'CORRECT':
print(f"\nYour number is {str(myGuess)}! It took me {str(numGuesses)} guesses!")
break
numGuesses += 1
if failed:
print(f"\nMy final guess of {str(myGuess)} was not correct. I wasn't able to guess your number in 10 tries.")
(现在)似乎很清楚,我削减数字的方式行不通。本来想问是不是500,低了就问是不是250,再低就问是不是125,以此类推。如果更高,请询问是否是 750、875 等。这是正确的方法吗?
我一直在考虑这个太久,我相信我已经煮熟了我的大脑。谢谢!
解决方案
myGuess = int(math.ceil((myGuess) / 2))
是不正确的。
如果您已将范围缩小到6
and8
并且您正在猜测7
,则您之前的代码将调用4
而不是在您的搜索范围之外。
if userFeedback == 'HIGH':
print(f"\nGuess #{numGuesses} was too high")
upperBound = myGuess - 1
elif userFeedback == 'LOW':
print(f"\nGuess #{numGuesses} was too low")
lowerBound = myGuess + 1
myGuess = int(lowerBound + ((upperBound - lowerBound) / 2))
推荐阅读
- c# - 如何将 2 种不同类型传递给 c# 中的函数参数?
- rust - Rust Borrow Checker 的详细和/或调试输出
- java - 更改 JTable 的选择行为以仅选择行或列中可变数量的单元格
- css - 我怎样才能让我的圈子只用 CSS 响应?
- forms - 将带有宏的 MS word 格式转换为 PDF
- python - Plotly ISO 周开始日
- node.js - 在创建承诺后添加 finally 处理程序会导致未捕获的承诺拒绝?
- eclipse - 如何在 Eclipse 类型搜索中搜索关键字
- javascript - 使用 Ajax 提交表单数组字段
- reactjs - `Uncaught ReferenceError: FB is not defined` 在 React