python实现猜数字游戏(无重复数字)示例分享
importtime,random
classGuessNum:
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))
foriinrange(0,4):
a=str(random.choice(seq_zton)) #选出一个数字
self._num+=a
seq_zton.remove(int(a)) #注意a的类型
self.sec=time.clock() #开始计时
defcheck_answer(self):
returnself._num
defcheck_input(self):
num_pos,num_value=0,0 #位置对和数值对的分别的个数
tmp=input("Pleaseinputthenumberyouguess(Norepetition),or"c"tochecktheanswer:")
iftmp=="c":
print(self.check_answer())
tof=self.check_input()
returntof
elifnottmp.isalnumornotlen(tmp)==4:
print("Wrongformat!")
tof=self.check_input() #需要优化
returntof
self.input_num=list(tmp)
lst_temp=list(self._num)
ifself.input_num==lst_temp: #猜对
self.prt_vic()
returnTrue
foriinlst_temp:
ifiinself.input_num:
iflst_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
returnFalse
defprt_state(self,num_pos,num_value):
print("You"vegot%dnumberswiththerightpositionand%dnumberswiththerightvalueonly"%(num_pos,num_value))
defprt_vic(self):
t=time.clock()
self.sec=t-self.sec
print("Congratulations!Youhavesuccessfullygottherightnumber!")
print("%dtimesand%.2fsecintotaltogettherightanswer"%(self.count,self.sec))
gn=GuessNum()
whileTrue:
ss=gn.check_input()
ifss:
b=input("Continue?y/n:")
ifb=="n":
break
else:
gn=GuessNum()
continue
相关文章
- python求逆矩阵的方法,Python 如何求矩阵的逆「建议收藏」
- pycharm打包python项目_Python怎么打包
- mt4 python_一个使用Python自动化交易外汇MT4脚本实现「建议收藏」
- python解压bz2文件命令,在Python中解压缩.bz2文件
- python中dtype什么意思_NumPy Python中的数据类型对象(dtype)
- python最好的开发工具_Python编译器
- python表情代码_Python实现表情包的代码实例[通俗易懂]
- Python:利用python代码编程实现将视频的avi格式转换为MP4格式
- python lambda表达式举例_Python中lambda表达式[通俗易懂]
- 数据结构与算法Python_数据结构与算法python语言实现
- python定义函数求和_Python定义函数实现累计求和操作
- Python+ChatGPT制作了一个AI百宝箱,太实用了!!
- Python 三维姿态估计+Unity3d 实现 3D 虚拟现实交互游戏
- Python tuple元组详解
- 用Python实现一个简单的算术游戏详解编程语言
- python删除源文件中的注释并编译详解编程语言
- Python输出函数print()总结(python print())详解编程语言
- 利用python实现微信小程序游戏跳一跳详细教程详解编程语言
- Python项目实战之猜数字游戏(含实现代码)
- Python结合MySQL实现信息交互(python与mysql交互)
- Python操作Redis实现数据持久化(python操作redis)
- Python实现快速连接Redis数据库(python连接redis)
- 使你的 Python 游戏玩家能够向前和向后跑
- Python实现Oracle数据库连接(python连接oracle数据库)
- 使用Python连接MySQL数据库,实现高效数据交互(python连接mysql)
- Python连接MySQL数据库:初学者指南(python入mysql)
- 从 Python 连接到 MySQL:实现更多强大的数据库应用(python和mysql)
- 在Linux系统中使用Python编程语言(linux中python)
- Python入门篇之条件、循环