结构
times.ttf 是一个ttf字体文件,用宋体什么也行。 如下在linux 下创建项目:
mkdir 质数方阵
cd 质数方阵
touch maths-number-game.py
mkdir image
cd image
touch temp.gif
如下在windows 下创建项目:
mkdir 质数方阵
cd 质数方阵
cd.> maths-number-game.py
mkdir image
cd image
cd.> temp.gif
下包
pip install PySimpleGui
pip install pillow
pip install PyCkin3
代码
import random
import time
import PySimpleGUI as sg
from PyCkin3.tycount3 import TyIsPrime, TyFunctionSquare, TyIsNumber, \
TyFlatten
from PIL.Image import new
from PIL.ImageDraw import ImageDraw
from PIL.ImageFont import truetype
from tkinter.messagebox import showinfo, showerror, showwarning
gamewidth = 6
square = TyFunctionSquare(random.randint, width=gamewidth, height=gamewidth,
a=2, b=100)
numbers = []
for row, i in enumerate(square):
for column, j in enumerate(i):
if TyIsPrime(j):
numbers.append(j)
font = truetype('times.ttf', 25)
color = '#0000ff'
text = '\n'.join(' '.join(str(j) for j in i) for i in square)
image = new(mode='RGB', size=(gamewidth * 55, gamewidth * 40), color=(255, 255, 255))
pen = ImageDraw(image)
pen.text((0, 0), text, font=font, fill=color, direction=None)
image.save('image/temp.gif')
inputs = []
layout = [
[sg.Image('image/temp.gif')],
[sg.Text('输入一个数:'), sg.InputText(key='-number-'),
sg.Button('提交', key='-add-'), sg.Button('删除', key='-del-')],
[sg.Text('数字:')],
[sg.Listbox(inputs, key='-numbers-', size=(60, 18))],
[sg.Submit('提交', key='-submit-')]
]
window = sg.Window('质数方阵', layout)
while True:
event, values = window.read()
if event is None:
break
elif event == '-add-':
value = values['-number-']
if (not TyIsNumber(value)) or ('.' in value):
showwarning('警告', '输入不是数字')
continue
value = int(value)
if value not in TyFlatten(square):
showwarning('警告', '输入不在方阵中')
continue
inputs.append(value)
window.find_element('-numbers-').update(inputs)
window.find_element('-number-').update('')
elif event == '-del-':
value = values['-number-']
if (not TyIsNumber(value)) or ('.' in value):
showwarning('警告', '输入不是数字')
continue
value = int(value)
if (value not in TyFlatten(square)) or (value not in inputs):
showwarning('警告', '输入不在方阵中')
continue
inputs.remove(value)
window.find_element('-numbers-').update(inputs)
window.find_element('-number-').update('')
elif event == '-submit-':
print(inputs, numbers)
if sorted(inputs) == sorted(numbers):
showinfo('答案正确', '挑战成功')
break
else:
showerror('答案错误', '罚时5秒')
time.sleep(5.0)
showinfo('提示', '罚时结束')
window.close()
效果
|