创建一个类实现一个打字小游戏(利用time.time()计算参赛者的打字时间,进而利用时间计算速率,利用random实现随机抽取)

# 打字小游戏  面向过程,面向对象
# 游戏类 ==》 属性、行为
#
# 1.外部传入一些数据,数据   单词列表  [movies,add,open]
# 2.随机的抽取这个单词列表中的一个单词,作为本局游戏的单词!
# 3.游戏开始,游戏的展示 ,游戏的结束 ,游戏时间,游戏的正确率等
import  random #随机给出列表里的一个单词
import time #计算游戏时间
class PlayWord:
    def __init__(self,words): # words是一个列表类型的数据
        self.words = words
        self.spend_time = 0
        self.play_word = ''
        self.user_word = ''

    def show(self):
        #展示当前游戏的单词,本局游戏的单词
        #游戏开始的提示
        #随机抽取一个列表中的单词
        self.play_word = random.choice(self.words)
        print("游戏开始本局游戏单词:",self.play_word)

    # 游戏正式开始方法
    def play(self):
        #记录游戏开始的时间,以及用户输入单词的内容,用户输入单词结束的时间
        # print(time.time()) # 返回一个时间戳
        star_time = int(time.time())
        self.user_word = input("请输入单词:")
        stop_time = int(time.time())
        self.spend_time = stop_time - star_time #记录用户打字的时间
        #结束的时候再记录一个时间戳    两个时间戳相减就得到游戏花费的总时间
        #调用
        # eval
        self.eval()

    # 方法
    def eval(self):
        #校验游戏数据
        #处理用户的正确率、打字的速度
        #正确率
        # 游戏单词:address    用户输入的单词:addreaa
        true_num = 0
        for i in range(len(self.user_word)):
            if i < len(self.play_word):  #只看输入的单词与题目给出单词相同长度的部分
                if self.user_word[i] == self.play_word[i]:
                    true_num += 1
            else:
                break # 强行的跳出循环
        #打字速度
        # 一定时间内 打字的数量 就是打字速度
        # 打字数量 / 打字的时间(游戏的花费时间)
        self.speed = round(len(self.user_word) / self.spend_time,2)
        #计算正确率  round内置函数 四舍五入 保留两位小数
        self.acc = round(true_num / len(self.play_word),2)

    # 游戏结束的方法
    def over(self):
        #看一些信息
        print(f"游戏花费{self.spend_time}秒")
        print(f"用户正确率:{self.acc}")
        print(f"用户打字速度:{self.speed}/秒")
play1 = PlayWord(["movies","address","superstar"])
play1.show()
play1.play()
play1.over()

下面是两次游戏结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值