24点游戏,顾名思义,就是一种得数为24的数学游戏。
随机出现4个整数,把4个整数(一般是正整数)通过加减乘除以及括号运算,使最后的计算结果是24的一个数学游戏,24点可以考验人的智力和数学敏感性,它能在游戏中提高人们的心算能力。
正宗的24点计算通常是使用扑克牌来进行游戏的,一副牌中抽去大小王后还剩下52张(如果初练也可只用1~10这40张牌),任意抽取4张牌(称为牌组),用加、减、乘、除(可加括号)把牌面上的数算成24。
24点游戏中每张牌必须只能用一次,如抽出的牌是3、8、8、9,那么算式为(9-8)×8×3或3×8÷(9-8)或(9-8÷8)×3等。
如果做成GUI效果,是这样的。
这里最难的就是判断4个数字,能否通过加减乘除得到24结果。
如果4个数字根本就不存在组合成24的情况,程序要能够判断出来;如果存在组合成24的情况,而玩家没有想出答案,要能够提供查看答案选项。
所以这里的问题就转换成了,任意的1-13中的4个数字,使用加减乘除计算,有多少种可以得出24的组合。
解决这个问题,可分为3步;
第一步:计算4个数字存在多少种组合
使用排列组合的方法,数量不多,直接4重循环遍历即可,索引不相同(不同的数字)符合我们的组合要求。
# 数字列表
b = [2,3, 12, 13]
# 结果列表
l = []
for i in range(4):
for j in range(4):
for m in range(4):
for n in range(4):
a=b.copy()
if i!=j and i!=m and i!=n and j!=m and j!=n and m!=n:
l.append([a[i], a[j], a[m], a[n]])
print(l)
[[2, 3, 12, 13], [2, 3, 13, 12], [2, 12, 3, 13],
[2, 12, 13, 3], [2, 13, 3, 12], [2, 13, 12, 3],
[3, 2, 12, 13], [3, 2, 13, 12], [3, 12, 2, 13],
[3, 12, 13, 2], [3, 13, 2, 12], [3, 13, 12, 2],
[12, 2, 3, 13], [12, 2, 13, 3], [12, 3, 2, 13],
[12, 3, 13, 2], [12, 13, 2, 3], [12, 13, 3, 2],
[13, 2, 3, 12], [13, 2, 12, 3], [13, 3, 2, 12],
[13, 3, 12, 2], [13, 12, 2, 3], [13, 12, 3, 2]]
第二步:每个组合通过加减乘除符合的有多少种情况
这里假设分为两类(实际还有其它的分类情况)
# 随意拿一个组合
item = [2,3, 12, 13]
# 操作符列表
operators = ["+","-","*","/"]
# 遍历所有符号可能的情况
for i in operators:
for j in operators:
for m in operators:
# 从左到右的组合
result1 = eval(f"{item[0]}{i}{item[1]}")
result2 = eval(f"{result1}{j}{item[2]}")
result3 = eval(f"{result2}{m}{item[3]}")
if result3 ==24:
print(f"{item[0]}{i}{item[1]}{j}{item[2]}{m}{item[3]}")
# 两两组合
result4 = eval(f"{item[0]}{i}{item[1]}")
result5 = eval(f"{item[2]}{m}{item[3]}")
if result5==0 and j=="/":
continue
else:
result6 = eval(f"{result4}{j}{result5}")
if result6==24 and result5:
print(f"({item[0]}{i}{item[1]}){j}({item[2]}{m}{item[3]})")
2-3+12+13
(2-3)+(12+13)
第三步:判断每种情况的结果值;
# 数字列表
b = [2,3, 12, 13]
# 结果列表
l = []
for i in range(4):
for j in range(4):
for m in range(4):
for n in range(4):
a=b.copy()
if i!=j and i!=m and i!=n and j!=m and j!=n and m!=n:
l.append([a[i], a[j], a[m], a[n]])
print(l)
# 操作符列表
operators = ["+","-","*","/"]
# 遍历所有符号可能的情况
for item in l:
for i in operators:
for j in operators:
for m in operators:
# 从左到右的组合
result1 = eval(f"{item[0]}{i}{item[1]}")
result2 = eval(f"{result1}{j}{item[2]}")
result3 = eval(f"{result2}{m}{item[3]}")
if result3 ==24:
print(f"{item[0]}{i}{item[1]}{j}{item[2]}{m}{item[3]}")
# 两两组合
result4 = eval(f"{item[0]}{i}{item[1]}")
result5 = eval(f"{item[2]}{m}{item[3]}")
if result5==0 and j=="/":
continue
else:
result6 = eval(f"{result4}{j}{result5}")
if result6==24 and result5:
print(f"({item[0]}{i}{item[1]}){j}({item[2]}{m}{item[3]})")
核心问题已经解决了,剩余的界面功能就比较简单了,下次实现。
(全文完)
欢迎转载,转载请注明出处!