|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
哎,我想做一个算术游戏,可是咋也做不好。谁来帮我看看是咋么回事并改进?代码如下:
- #由于需要使用到random函数,所以先导入进来-_-
- import random
- def main1(num1,num2,a,b):
- """定义第一个主要部分
- num1和num2是随机数的两个对应的随机数
- a是加减乘除的类型序号,b是是否多位数的类型序号"""
- if b == 1:
- le = 3
- else:
- le = 5
- li = []
- if a == 1:
- h1 = 1
- h2 = 2
- elif a == 2:
- h1 = 3
- h2 = 4
- else:
- h1 = 1
- h2 = 4
- for i in range(le-b):
- li.append(random.randint(num1,num2))
- li.append("|")
- for i in range(b):
- li.append(random.randint(h1,h2))
- li.append("|")
- if le == 3:
- li.append(input("{0}{1}{2}=".format(li[0],li[3],li[1])))
- else:
- li.append(input("{0}{1}{2}{3}{4}".format(li[0],li[4],li[1],li[5],li[2])))
- li.append("|")
- li.append(le)
- def main2(num1,num2,typed):
- """定义第二个主要部分
- num1和num2是随机数的两个对应的随机数
- typed则是类型,a是加减,b是乘除,c是加减乘除,此外,如果再加上一个'd',那就不是两个数一个符号,而是三个数两个符号"""
- if typed.find("a") != -1:
- if typed == "ad":
- return main1(num1,num2,1,2)
- else:
- return main1(num1,num2,1,1)
- if typed.find("b") != -1:
- if typed == "bd":
- return main1(num1,num2,2,2)
- else:
- return main1(num1,num2,2,1)
- if typed.find("c") != -1:
- if typed == "cd":
- return main1(num1,num2,3,2)
- else:
- return main1(num1,num2,3,1)
- def check(*num,result):
- """定义检查部分"""
- true_result = 0
- that_result = 0
- if len(num) == 3:
- for i in range(1):
- h = [num[i],num[i+1]]
- if num[-i] == 1:
- that_result = h[0] + h[1]
- if num[-i] == 2:
- that_result = h[0] - h[1]
- if num[-i] == 3:
- that_result = h[0] * h[1]
- if num[-i] == 4:
- that_result = h[0] / h[1]
- true_result = true_result + that_result
- else:
- for i in range(2):
- h = [num[i],num[i+1]]
- if num[-i] == 1:
- that_result = h[0] + h[1]
- if num[-i] == 2:
- that_result = h[0] - h[1]
- if num[-i] == 3:
- that_result = h[0] * h[1]
- if num[-i] == 4:
- that_result = h[0] / h[1]
- true_result = true_result + that_result
- if true_result == result:
- print("做对啦!")
- return 1
- else:
- print("不对哦。")
- return 0
- def others(*_list):
- """定义一个能帮助下面的doing函数的函数"""
- #两个数一个符号的li列表的实例:["1","1","|","+","|","2","|","3"]
- #三个数两个符号的li列表的实例:["1","1","1","|","+","-","|","3","|","5"]
- if _list[-1] == 3:
- return check(num=(_list[0],_list[1],_list[3]),result=_list[5])
- else:
- return check(num=(_list[0],_list[1],_list[2],_list[4],_list[5]),result=_list[7])
- def doing():
- """定义一个可以给用户体验的一个函数"""
- print("这是一个可以考验你的计算能力的程序。你准备好了吗?")
- l1 = [1,1,20,30,30,100,215,400]
- l2 = [10,9,50,100,100,300,500,1000]
- l3 = ["a","bd","a","c","cd","b","cd","c"]
- score = 20
- for i in range(8):
- while score < 30 or score > 0:
- if others(main2(l1[i],l2[i],l3[i])) == 1:
- score += 1
- else:
- score -= 2
- if score >= 30:
- if i == 7:
- print("您已挑战成功!您的计算能力已经很强了。")
- break
- else:
- print("您已通关!")
- else:
- print("您已挑战失败。您在第%s关被终止。" % str(i+1))
- break
- doing()
复制代码
eval是python内置函数,,可以随便用,,示例如下:
>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
很方便,,把你代码换个思路,,让用户输入一个字符串,,你把得到的字符串eval一下就行了,哈哈
|
|