国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現猜數字游戲(無重復數字)示例分享

2019-11-25 18:28:23
字體:
來源:轉載
供稿:網友

復制代碼 代碼如下:

import time, random

class GuessNum:
    def __init__(self):
        self._num = ''
        self.input_num = []
        self.count = 1                                      #猜對所用次數
        self.sec = 0                                           #猜對所用時間
        self._generate_num()

    def _generate_num(self):                        #產生不重復的四個數字
        seq_zton = list(range(10))
        for i in range(0, 4):
            a = str(random.choice(seq_zton))   #選出一個數字
            self._num += a
            seq_zton.remove(int(a))                 #注意a的類型

        self.sec = time.clock()                          #開始計時

    def check_answer(self):
        return self._num

    def check_input(self):
        num_pos, num_value = 0, 0               #位置對和數值對的分別的個數
        tmp = input("Please input the number you guess(No repetition),or 'c' to check the answer:")
        if tmp == 'c':
            print(self.check_answer())
            tof = self.check_input()
            return tof
        elif not tmp.isalnum or not len(tmp) == 4:
            print("Wrong format!")
            tof = self.check_input()                #需要優化
            return tof
        self.input_num = list(tmp)
        lst_temp = list(self._num)
        if self.input_num == lst_temp:          #猜對
            self.prt_vic()
            return True
        for i in lst_temp:
            if i in self.input_num:
                if lst_temp.index(i) == self.input_num.index(i):        #位置也相同
                    num_pos += 1
                    num_value += 1
                else:
                    num_value += 1

        self.prt_state(num_pos, num_value)
        self.count += 1
        return False

    def prt_state(self, num_pos, num_value):
        print("You've got %d numbers with the right position and %d numbers with the right value only" % (num_pos, num_value))

    def prt_vic(self):
        t = time.clock()
        self.sec = t - self.sec
        print("Congratulations!You have successfully got the right number!")
        print("%d times and %.2f sec in total to get the right answer" % (self.count, self.sec))

gn = GuessNum()
while True:
    ss = gn.check_input()
    if ss:
        b = input("Continue? y/n:")
        if b == 'n':
            break
        else:
            gn = GuessNum()
            continue

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 朝阳市| 珠海市| 无棣县| 北宁市| 正镶白旗| 凤凰县| 新化县| 清苑县| 柳河县| 青川县| 于田县| 奉节县| 离岛区| 抚松县| 临沧市| 乐都县| 巧家县| 上饶县| 江津市| 喀喇| 息烽县| 梁平县| 东莞市| 宽城| 绥滨县| 抚州市| 上犹县| 益阳市| 高安市| 安国市| 德格县| 周口市| 兰溪市| 龙井市| 山阳县| 依安县| 灵璧县| 昌邑市| 上杭县| 汝阳县| 大足县|