#coding=UTF-8 import tkinter as tk from random import randint from itertools import permutations #4个数字和2个运算符可能组成的表达式形式 exps = ('((%s %s %s) %s %s) %s %s', '(%s %s %s) %s (%s %s %s)', '(%s %s (%s %s %s)) %s %s', '%s %s ((%s %s %s) %s %s)', '%s %s (%s %s (%s %s %s))') ops = r'+-*/' window = tk.Tk() window.title('24 Game') window.geometry('620x600') def test24(v): result = [] #Python允许函数的嵌套定义 #这个函数对字符串表达式求值并验证是否等于24 def check(exp): try: #有可能会出现除0异常,所以放到异常处理结构中 return int(eval(exp)) == 24 except: return False #全排列,枚举4个数的所有可能顺序 for a in permutations(v): #查找4个数的当前排列能实现24的表达式 t = [exp % (a[0], op1, a[1], op2, a[2], op3, a[3]) for op1 in ops for op2 in ops for op3 in ops for exp in exps if check(exp %(a[0], op1, a[1], op2, a[2], op3, a[3]))] if t: result.append(t) return result def clr(): e1.delete('0', 'end') e2.delete('0', 'end') e3.delete('0', 'end') e4.delete('0', 'end') t.delete(1.0, tk.END) def Cal_clr(): t.delete(1.0, tk.END) def Cal(): Cal_clr() lst=[] a1=int(e1.get()) a2=int(e2.get()) a3=int(e3.get()) a4=int(e4.get()) lst.append(a1) lst.append(a2) lst.append(a3) lst.append(a4) # print(lst) r = test24(lst) cnt=0 if r: for i in range(len(r)): print(r[i]) for j in range(len(r[i])): print(r[i][j]) t.insert('insert', r[i][j]+' ') cnt+=1 if(cnt==4): cnt=0 t.insert('insert', '\n') else: print('No answer for ', lst) t.insert('insert', 'No answer for ') t.insert('insert', lst) # 标签 w = tk.Canvas(window, width=620, height=600) w.pack() w.create_rectangle(470, 0, 470+150, 0+55, fill='skyblue') l_title = tk.Label(window, text=' 24 点', bg='skyblue', font='黑体 -30', fg='red') l_title.place(x=490, y=10) # 提示语句 var = tk.StringVar() l = tk.Label(window, text="请输入四个数字:", font=('NewTimesRoman', 16), width=15, height=2) l.place(x=100, y=50, anchor='center') # 四个输入 e1=tk.Entry(window, show='', font = 'NewTimesRoman -20 bold', width=5) e1.place(x=80, y=100, anchor='center') e2=tk.Entry(window, show='', font = 'NewTimesRoman -20 bold', width=5) e2.place(x=200, y=100, anchor='center') e3=tk.Entry(window, show='', font = 'NewTimesRoman -20 bold', width=5) e3.place(x=320, y=100, anchor='center') e4=tk.Entry(window, show='', font = 'NewTimesRoman -20 bold', width=5) e4.place(x=440, y=100, anchor='center') # 结果输出提示 l = tk.Label(window, text="24点运算结果为:", font=('NewTimesRoman', 16), width=15, height=2) l.place(x=100, y=200, anchor='center') # 结果显示 t = tk.Text(window, width=160, height=50, font=('NewTimesRoman', 11)) t.place(y=240, anchor='nw') # 计算按钮 b = tk.Button(window, text='计算', command=Cal, width=8) b.place(x=200, y=150, anchor='center') # 清空按钮 b_clr = tk.Button(window, text='清空', width=8, command=clr) b_clr.place(x=320, y=150, anchor='center') window.mainloop()
从扑克中每次取出4张牌。使用加减乘除,第一个能得出24者为赢。(其中,J代表11,Q代表12,K代表13,A代表1),按照要求编程解决24点游戏。 基本要求: 随机生成4个代表扑克牌牌面的数字字母,
猜你喜欢
转载自blog.csdn.net/qq_39621439/article/details/82949674
今日推荐
周排行