python 猜单词游戏 代码

NUM_DIGITS = 3
MAX_GUESS = 10


def getSecrectNum():
    '''
     随机获取三个数字
    :return: 
    '''
    numbers = list(range(10))
    random.shuffle(numbers)
    secrectNum = ''
    for i in range(NUM_DIGITS):
        secrectNum += str(numbers[i])
    return secrectNum


def getClues(guess, secretNum):
    '''
    用户输入的数字和,系统产生的秘密数字进行比对
    :param guess: 
    :param secretNum: 
    :return: 
    '''
    if guess == secretNum:
        print('Oh my god , You go it!')
    clues = []
    for i in range(len(guess)):
        if guess[i] == secretNum[i]:
            clues.append('Fermi')
        elif guess[i] in secretNum:
            clues.append('Pico')
        if len(clues) == 0:
            return 'Bagels'
    clues.sort()
    return ' '.join(clues)


def isOnlyDigits(num):
    '''
    判断是否位数字
    :param num: 
    :return: 
    '''
    if num == '':
        return False
    for i in num:
        if i not in  '0 1 2 3 4 5 6 7 8 9'.split():
            return False
    return True


print('I am thinking of a {0}-digit-number. Try to guess what it is .'.format(NUM_DIGITS))
print('The clues i give are...')
time.sleep(1)
print('When i say:     That means:')
time.sleep(1)
print('Bagels     None of the digits is correct.')
time.sleep(1)
print('Pico       None digits is correct but in the wront position.')
time.sleep(1)
print('Fermi      None digits is correct and in the right position.')
while True:
    secretNum = getSecrectNum()
    print('I have thought up a number. you have {0} guesses to get it.'.format(MAX_GUESS))
    guessesTaken = 1
    while guessesTaken < MAX_GUESS:
        guess = ''
        while len(guess) != NUM_DIGITS or not isOnlyDigits(guess):
            print('Guess #{0}'.format(guessesTaken))
            guess = input()
            if len(guess) !=NUM_DIGITS:
                print('please input three number!')
        print(getClues(guess, secretNum))
        guessesTaken += 1
        if guess == secretNum:
            break
        if guessesTaken > MAX_GUESS:
            print('You ran out or guesses .The answer was {0}.'.format(secretNum))
    print('Do yoy want to play again ? ( yes or no)')
    if not input().lower().startswith('y'):
        break

猜你喜欢

转载自blog.csdn.net/TianPingXian/article/details/80430586