读心术的小游戏代码实践

作者: shaneZhang 分类: 机器学习的实践 发布时间: 2019-02-02 16:09

本示例代码是用python3来编写的,在运行本demo的时候需要使用python3来运行即可。

#coding=utf-8
import random
import getopt
import sys

def human_guess():
    num = random.randint(0,1000)
    i = 0
    while 1:
        try:
            guess = int(input("请输入数字0~10000:"))
        except ValueError:
            print ("请输入正确的数字")
            continue
        i += 1

        if guess > num:
            print ("猜大了:",guess)
        elif guess < num:
            print ("猜小了",guess)
        else:
            print ("你猜对了,共猜了",i,"次")
            sys.exit(0)




def computer_guess():
    print ("请在心里想一个数字0~1000范围内的数字")
    small = 0
    big = 1000
    guess = 500

    i = 0
    while 1:
        guess = int((big + small) / 2)
        i+= 1
        print ("是这个数吗:" + str(guess) + "(B:大了,S:小了,C:正确)")
        char = input()
        if char == 'B':
            big = guess
        elif char == "S":
            small = guess
        elif char == "C":
            print ("共猜了{0}次,得到的结果为{1}".format(i,guess))
            sys.exit()
        else:
            print ("请输入正确回答:(B:大了,S:小了,C:正确)")



def main():
    who_guess = input("请决定谁来猜数(C:电脑,H:玩家)")
    if who_guess in "Hh":
        human_guess()
    elif who_guess in "Cc":
        computer_guess()


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print ()

如果觉得我的文章对您有用,请随意打赏。如果有其他问题请联系博主QQ(909491009)或者下方留言!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注