计算机在定义的范围内猜测用户选择的号码

时间:2016-07-23 13:00:35

标签: python list indexing

这是我的游戏代码,其中计算机必须猜测给定范围内的用户定义数字。这是初学者课程/书中的挑战。

我想提请你注意'computerGuess()'函数。我认为必须有一种更有说服力的方法才能达到同样的效果?我看起来像一个拙劣的工作!

该函数的目的是返回列表中的中间项(因此计算机选择的数字范围中的中间数)。我添加了'index'变量等式中的0.5,因为否则会发生从float-int的转换,数字会向下舍入。

感谢。

代码:

# Computer Number Guesser
# By Dave
# The user must pick a number (1-100) and the computer attempts to guess
# it in as few attempts as possible


print("Welcome to the guessing game, where I, the computer, must guess your\
 number!\n")
print("You must select a number between 1 and 100.")

number = 0
while number not in range(1, 101):
    number = int(input("\nChoose your number: "))

computerNumber = 0
computerGuesses = 0
higherOrLower = ""
lowerNumber = 1
higherNumber = 101

def computerGuess(lowerNumber, higherNumber):
    numberList = []
    for i in range(lowerNumber, higherNumber):
        numberList.append(i)
    index = int((len(numberList)/2 + 0.5) -1)
    middleValue = numberList[index]
    return middleValue


while higherOrLower != "c":
    if computerGuesses == 0:
        computerNumber = computerGuess(lowerNumber, higherNumber)
    elif higherOrLower == "l":
        higherNumber = computerNumber
        computerNumber = computerGuess(lowerNumber, higherNumber)
    elif higherOrLower == "h":
        lowerNumber = computerNumber + 1
        computerNumber = computerGuess(lowerNumber, higherNumber)


    print("\nThankyou. My guess is {}.".format(computerNumber))
    computerGuesses += 1
    higherOrLower = input("\nHow did I do? If this is correct, enter\
 'c'. If your number is higher, enter 'h'. If it is lower, enter 'l': ")

print("\nHaha! I got it in {} attempt(s)! How great am I?".format\
      (computerGuesses))

input("\n\nPress the enter key to exit.")

1 个答案:

答案 0 :(得分:0)

喜欢这个?

import math

def computerGuess(lowerNumber, higherNumber):
    return int((lowerNumber+higherNumber)/2)