key_value_set.py 1.6 KB
Newer Older
F
feilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# -*- coding: UTF-8 -*-
# 作者:幻灰龙
# 标题:Python 类的基本使用(1)
# 描述:编写一个kv容器类,支持 set/get/exist/keys/count 接口

class KeyValueSet:
    def __init__(self) -> None:
        self.dict = {}

    def set(self, key, value):
        self.dict[key] = value

    def get(self, key):
        return self.dict.get(key)

    def exist(self, key):
        return self.dict.get(key) is not None

    def keys(self):
        return self.dict.keys()


F
feilong 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
class GuessSentenceGame:
    def __init__(self):
        self.kv = KeyValueSet()
        self.score = 0

    def setup(self, sentences):
        for sentence in sentences:
            self.append(sentence)

    def append(self, sentence):
        cut_pos = sentence.find(' ')
        first_word, rest = sentence[0:cut_pos], sentence[cut_pos+1:].strip()
        self.kv.set(first_word, rest)

    def run(self):
        self.score = 0
        for first_word in self.kv.keys():
            ret = input("猜一猜下半句是什么? {} -> :".format(first_word))
            value = self.kv.get(first_word)
            if ret == value:
                print('你太厉害了,这都能猜得到!+10分!')
                self.score += 10
            else:
                self.score -= 2
                print('哈哈,肯定猜不到得啦:{}->{},扣除2分!'.format(first_word, value))
        print('游戏结束,你本次游戏得分:', self.score)
F
feilong 已提交
49 50


F
feilong 已提交
51
if __name__ == '__main__':
F
feilong 已提交
52

F
feilong 已提交
53 54 55 56 57 58
    sentences = [
        "hello world",
        'monkey king',
        'tomorrow is another day',
        "good bye!"
    ]
F
feilong 已提交
59

F
feilong 已提交
60 61 62
    game = GuessSentenceGame()
    game.setup(sentences)
    game.run()