背景
之前用shell写的猜数字游戏,现在学习python就利用python重写了一个。
#!/usr/bin/python3
#Designed By HCWEI!
#2018-12-04 14:00:00
import random
import os
import time
#获取历史猜测百分比
def PER(num):
if os.path.exists("number.txt") and os.path.getsize("number.txt"):
with open("number.txt",'a+',encoding="utf-8") as f:
f.write("\n"+str(num))
else:
with open("number.txt", 'a+', encoding="utf-8") as f:
f.write(str(num))
for _COUNT, line in enumerate(open("number.txt", 'r+')):
pass
_COUNT += 1
_TIME = 0
with open("number.txt", 'r', encoding="utf-8") as f:
for i in f:
if int(i) > num:
_TIME+=1
continue
PER_NUM=_TIME/_COUNT*100
PER_NUM_2=round(PER_NUM,2)
return PER_NUM_2
#猜数字游戏主程序
def main():
print("\033[1;7;32mGuess Number 0-50.\033[0m")
_RANDOM=random.randint(0,50)
_TIMES=1
_ROLLBACK=0
_START=time.time()
while _ROLLBACK < 3:
_NUMBER = int(input("\033[30mplease input number:\033[0m"))
if _RANDOM == _NUMBER:
if _TIMES >5:
_PERSENT=PER(_TIMES)
_END = time.time()
_TIME_USED = _END - _START
print("You guessed \033[1;31m%s\033[0m times,Used \033[1;31m%d\033[0m second,Beat \033[1;31m%s%%\033[0m of the people.You are stupid !!!" %(_TIMES,_TIME_USED,_PERSENT))
break
else:
_PERSENT=PER(_TIMES)
_END = time.time()
_TIME_USED = _END - _START
print("You guessed \033[1;31m%s\033[0m times,Used \033[1;31m%d\033[0m second,Beat \033[1;31m%s%%\033[0m of the people,You are pretty !!!" %(_TIMES,_TIME_USED,_PERSENT))
break
elif _RANDOM > _NUMBER:
print("\033[1;32msmaller\033[0m")
_TIMES +=1
else:
print ("\033[1;31mbigger\033[0m")
_TIMES +=1
_ROLLBACK +=1
if _ROLLBACK == 3:
con=input("\033[33mcontinue???(y/n):\033[0m")
if con != "n":
_ROLLBACK=0
else:
print("goodbye!!!")
if __name__ == '__main__':
main()