《Python游戏编程快速上手》第十一章猜数字,推理游戏Bagels

《Python游戏编程快速上手》的第十一章的小游戏也非常简单,话不多少,简单介绍下:

  • 系统随机生成几个数字,由玩家来猜,若有一个数字猜对但位置不对,输出一个Pico;若一个数字即猜对了位置也对,输出一个Fermi;如没有数字猜对,则输出Bagels。

接下来,上代码:

import random

NUMCOUNT = 3
GAUSSCOUNT = 10

def getNum():
    numList = list(range(10))
    random.shuffle(numList)
    gaussNum = ''
    for i in range(NUMCOUNT):
        gaussNum += str(numList[i])
    return gaussNum

def compareNum(gaussNum, inputNum):
    if len(inputNum) != NUMCOUNT:
        print("The count is wrong!You need input "+str(NUMCOUNT)+" numbers.")
        return 0

    f = 0
    p = 0
    b = 0

    for i in range(NUMCOUNT):
        if inputNum[i] in gaussNum:
            if inputNum[i] == gaussNum[i]:
                f += 1
            else:
                p += 1
        else:
            b += 1

    if f == NUMCOUNT:
        print("You got it!")
        return 1
    elif b == NUMCOUNT:
        print("Bagels")
        return 0
    else:
        print("Fermi "*f + "Pico "*p)
        return 0

def Main():
    print("I am thinking of "+str(NUMCOUNT)+"-digit number.Try to gauss what it is.")
    print("The clues I give are...")
    print("When I say:\tThat means:")
    print("  Bagels\tNone of the digits is correct.")
    print("  Pico\tOne digit is correct but in the wrong position.")
    print("  Fermi\tOne digit is correct and in the right position.")
    print("I have thought up a number.You have "+str(GAUSSCOUNT)+" gausses to get it.")
    MyNum = getNum()
    for i in range(GAUSSCOUNT):
        print("Gauss #"+str(i+1)+":")
        YourNum = input()
        res = compareNum(MyNum, YourNum)
        if res == 1: break

if __name__ == "__main__":
    while True:
        Main()
        print("Do you want try again?(y or n)")
        if input() == 'n':
            break



唯一一个需要说一下的是random.shuffle() 函数,这个函数的作用是随机打乱输入的列表顺序。其余都就没什么可说的了。

-*************************************************************************************************************
加油吧,少年!

你可能感兴趣的:(python游戏)