由于学Python也有一段时间了。想试着写个猜游戏的小程序;
效果图如下:
实现的代码如下:
import random #随机生出数模块
import sys ##用到的方法sys.exit
import prettytable ##快速生成表格
from datetime import datetime ##time库的扩展库。主要用来生成当前时间
name = str(input("请输入你的姓名:"))
s = random.randint(0,10) ##生成1-10以内的随机数
count = 0
first_guess = ""
second_guess = ""
third_guess = ""
the_prize = ""
print ("你一共有3次机会.")
while True:
x = prettytable.PrettyTable(["时间","名字","第一次","第二次","第三次","是否猜对"]) ##表格列名
while count <3:
count+=1
r = int(input("\n请输入你的数:"))
if r>s:
print ("你输入的大于中奖数,请继续")
the_prize = "no"
elif r<s:
print ("你输入的数小于中奖数,请继续")
the_prize = "no"
else:
print ("恭喜你猜对了")
the_prize = "yes"
if count == 1:
first_guess = r
elif count == 2:
second_guess = r
else:
third_guess = r
break
if count == 1:
print ("你还有俩次机会")
first_guess = r
elif count == 2:
print ("你还有一次机会,请谨慎")
second_guess = r
else:
print ("你没有机会了,请再接再厉,即将退出本次游戏")
third_guess = r
##把值添加到表格中
x.add_row([datetime.now().strftime("%Y-%m-%d %H:%M:%S"),name,first_guess,second_guess,third_guess,the_prize])
print (x)
##判断用户是否还想继续玩
e = str(input("输入'q'退出游戏,输入任意键继续游戏"))
if e == 'q':
print ("即将退出游戏")
sys.exit(0)
else:
count = 0
写的不好,请各位纠正。