-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMath_On_Path_not_use.py
More file actions
513 lines (440 loc) · 21.5 KB
/
Math_On_Path_not_use.py
File metadata and controls
513 lines (440 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
# ---------------- Enhanced MazeMath Export with Path Highlight ----------------
import tkinter as tk
from tkinter import messagebox, filedialog
import random
import operator
import ttkbootstrap as tb
from ttkbootstrap.constants import *
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from PIL import Image, ImageDraw, ImageFont
from pathlib import Path
class MazeMath:
APP_NAME = "MazeMath"
APP_VERSION = "2.1"
OPERATORS = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.floordiv}
def __init__(self):
self.root = tk.Tk()
tb.Style(theme="darkly")
self.root.title(f"{self.APP_NAME} v{self.APP_VERSION}")
self.root.geometry("1300x700")
self.difficulty_var = tk.StringVar(value="Easy")
self.num_puzzles_var = tk.IntVar(value=1)
self.grid_numbers = []
self.grid_ops = []
self.solution_path = []
self.target_number = None
self.rows = self.cols = 0
self.grid_frame = None
self.solution_text = None
self._build_ui()
# ---------- UI ----------
def _build_ui(self):
tb.Label(self.root, text=self.APP_NAME, font=("Segoe UI", 22, "bold")).pack(pady=(10,2))
tb.Label(self.root, text="Solve your way through numbers — follow the maze, reach the target!", font=("Segoe UI", 10, "italic"), foreground="#9ca3af").pack(pady=(0,10))
opts = tb.Labelframe(self.root, text="Options", padding=10)
opts.pack(fill="x", padx=10, pady=6)
tb.Label(opts, text="Difficulty:").pack(side="left", padx=10)
tb.Combobox(opts, values=["Easy","Medium","Hard"], textvariable=self.difficulty_var, width=10).pack(side="left", padx=5)
tb.Label(opts, text="Number of Puzzles:").pack(side="left", padx=10)
tb.Spinbox(opts, from_=1, to=20, textvariable=self.num_puzzles_var, width=5).pack(side="left", padx=5)
ctrl = tb.Frame(self.root)
ctrl.pack(fill="x", padx=10, pady=10)
tb.Button(ctrl, text="🧩 Generate Single Puzzle", bootstyle="success", command=self.generate_single_puzzle).pack(side="left", padx=6)
tb.Button(ctrl, text="📄 Multiple Puzzles (Combined PDF)", bootstyle="warning", command=self.generate_multiple_combined_pdf).pack(side="left", padx=6)
tb.Button(ctrl, text="📂 Multiple Puzzles (Separate PDFs)", bootstyle="info", command=self.generate_multiple_separate_pdfs).pack(side="left", padx=6)
tb.Button(ctrl, text="🖼 Multiple Puzzles (Separate JPGs)", bootstyle="secondary", command=self.generate_multiple_jpgs).pack(side="left", padx=6)
tb.Button(ctrl, text="🖼 Multiple Puzzles (Combined JPG)", bootstyle="dark", command=self.generate_combined_jpg).pack(side="left", padx=6)
tb.Button(ctrl, text="🧹 Clear", bootstyle="secondary", command=self.clear_all).pack(side="left", padx=6)
tb.Button(ctrl, text="ℹ About", bootstyle="info-outline", command=self.show_about).pack(side="right", padx=4)
self.grid_frame = tb.Labelframe(self.root, text="Puzzle Grid", padding=10)
self.grid_frame.pack(fill="x", padx=10, pady=6)
sol_frame = tb.Labelframe(self.root, text="Solution", padding=10)
sol_frame.pack(fill="both", expand=True, padx=10, pady=6)
self.solution_text = tk.Text(sol_frame, height=10, font=("Consolas", 12))
self.solution_text.pack(fill="both", expand=True)
# ---------- Maze Generation ----------
def generate_maze(self, rows, cols):
maze = [[1]*cols for _ in range(rows)]
visited = [[False]*cols for _ in range(rows)]
path = []
def dfs(r,c):
visited[r][c]=True
maze[r][c]=0
dirs=[(0,1),(1,0),(0,-1),(-1,0)]
random.shuffle(dirs)
for dr,dc in dirs:
nr,nc=r+dr,c+dc
if 0<=nr<rows and 0<=nc<cols and not visited[nr][nc]:
dfs(nr,nc)
path.append((r,c))
dfs(0,0)
return maze, path[::-1]
# ---------- Puzzle Data ----------
def create_puzzle_data(self):
diff=self.difficulty_var.get()
self.rows,self.cols=(3,3) if diff=="Easy" else (4,4) if diff=="Medium" else (5,5)
maze,path=self.generate_maze(self.rows,self.cols)
self.solution_path=path
numbers=[[0]*self.cols for _ in range(self.rows)]
ops=[[None]*self.cols for _ in range(self.rows)]
current=random.randint(1,9)
numbers[path[0][0]][path[0][1]]=current
steps=[f"Start: {current}"]
for r,c in path[1:]:
valid=False
while not valid:
op=random.choice(list(self.OPERATORS.keys()))
num=random.randint(1,9)
try:
if op=="/" and current%num!=0: continue
if op=="-" and current-num<=0: continue
next_val=self.OPERATORS[op](current,num)
valid=True
except: continue
ops[r][c]=op
numbers[r][c]=num
steps.append(f"{current} {op} {num} = {next_val}")
current=next_val
self.grid_numbers=numbers
self.grid_ops=ops
self.target_number=current
return numbers,ops,path,steps
def create_puzzle(self):
self.create_puzzle_data()
# ---------- Display ----------
def display_grid(self):
for w in self.grid_frame.winfo_children(): w.destroy()
for r in range(self.rows):
for c in range(self.cols):
n=self.grid_numbers[r][c]
op=self.grid_ops[r][c]
text=str(n) if op is None else f"{op}{n}"
bg="#4caf50" if (r,c) in self.solution_path else "#222222"
if (r,c)==self.solution_path[0]: text="▶ "+text
if (r,c)==self.solution_path[-1]: text=text+" ⬇"
lbl=tb.Label(self.grid_frame,text=text,font=("Segoe UI",16,"bold"),width=5,relief="ridge",anchor="center",background=bg,foreground="white")
lbl.grid(row=r,column=c,padx=3,pady=3)
target_lbl=tb.Label(self.grid_frame,text=f"Target: {self.target_number}",font=("Segoe UI",16,"bold"),foreground="#f9c74f")
target_lbl.grid(row=self.rows,column=0,columnspan=self.cols,pady=10)
def show_solution(self):
self.solution_text.delete("1.0", tk.END)
if not self.grid_numbers:
self.create_puzzle() # Generate if empty
# Use existing puzzle data
numbers = self.grid_numbers
ops = self.grid_ops
path = self.solution_path
steps = []
current = numbers[path[0][0]][path[0][1]]
steps.append(f"Start: {current}")
for r, c in path[1:]:
op = ops[r][c]
num = numbers[r][c]
next_val = MazeMath.OPERATORS[op](current, num)
steps.append(f"{current} {op} {num} = {next_val}")
current = next_val
self.solution_text.insert(tk.END, "\n".join(steps))
def clear_all(self):
for w in self.grid_frame.winfo_children(): w.destroy()
self.solution_text.delete("1.0",tk.END)
self.grid_numbers=[]
self.grid_ops=[]
self.solution_path=[]
self.target_number=None
self.rows=self.cols=0
# ---------- PDF/JPG Export Helper ----------
def _draw_grid_pdf(self, c, numbers, ops, path_cells, start_cell, end_cell, y_start=700, cell_size=40):
x_start=50
y=y_start
for r in range(self.rows):
x=x_start
for c_idx in range(self.cols):
text=str(numbers[r][c_idx]) if ops[r][c_idx] is None else f"{ops[r][c_idx]}{numbers[r][c_idx]}"
# Highlight path
if (r,c_idx) in path_cells:
c.setFillColorRGB(0.3,0.8,0.3) # green
c.rect(x,y-cell_size,cell_size,cell_size,fill=True,stroke=True)
else:
c.setFillColorRGB(1,1,1)
c.rect(x,y-cell_size,cell_size,cell_size,fill=False,stroke=True)
c.setFillColorRGB(0,0,0)
# Draw arrows
if (r,c_idx)==start_cell: text="▶ "+text
if (r,c_idx)==end_cell: text=text+" ⬇"
c.drawCentredString(x+cell_size/2,y-cell_size/2,text)
x+=cell_size+5
y-=cell_size+5
return y
def _draw_grid_jpg(self, draw, numbers, ops, path_cells, start_cell, end_cell, y_start=20, cell_size=50):
x_start = 20
y = y_start
font_path = "arial.ttf"
try:
font_nums = ImageFont.truetype(font_path, 24)
except:
font_nums = ImageFont.load_default()
for r in range(self.rows):
x = x_start
for c_idx in range(self.cols):
text = str(numbers[r][c_idx]) if ops[r][c_idx] is None else f"{ops[r][c_idx]}{numbers[r][c_idx]}"
# Background
if (r, c_idx) in path_cells:
draw.rectangle([x, y, x + cell_size, y + cell_size], fill=(76, 175, 80))
else:
draw.rectangle([x, y, x + cell_size, y + cell_size], outline="white", width=2)
# Arrows
if (r, c_idx) == start_cell: text = "▶ " + text
if (r, c_idx) == end_cell: text = text + " ⬇"
# Text size using getbbox
bbox = font_nums.getbbox(text)
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
draw.text((x + (cell_size - w) / 2, y + (cell_size - h) / 2), text, fill="white", font=font_nums)
x += cell_size + 10
y += cell_size + 10
return y
def generate_multiple_separate_pdfs(self):
n = self.num_puzzles_var.get()
if n < 1:
return
folder = filedialog.askdirectory()
if not folder:
return
folder = Path(folder)
width, height = A4
for idx in range(1, n + 1):
numbers, ops, path_cells, steps = self.create_puzzle_data()
c = canvas.Canvas(str(folder / f"Puzzle_{idx}.pdf"), pagesize=A4)
y_start = height - 50
# Title & Difficulty
c.setFont("Helvetica-Bold", 20)
c.drawString(50, y_start, f"{self.APP_NAME} Puzzle {idx}")
y_start -= 40
c.setFont("Helvetica", 16)
c.drawString(50, y_start, f"Difficulty: {self.difficulty_var.get()}")
y_start -= 30
# Draw grid with path highlighting and arrows
y_start = self._draw_grid_pdf(c, numbers, ops, path_cells, path_cells[0], path_cells[-1], y_start=y_start, cell_size=40)
y_start -= 10
# Target
c.setFont("Helvetica-Bold", 16)
c.drawString(50, y_start, f"Target: {self.target_number}")
y_start -= 30
# Solution steps
c.setFont("Helvetica", 14)
c.drawString(50, y_start, "Solution:")
y_start -= 20
for step in steps:
c.drawString(60, y_start, step)
y_start -= 18
if y_start < 50:
c.showPage()
y_start = height - 50
c.showPage()
c.save()
messagebox.showinfo("Export PDFs", f"{n} separate PDFs exported to {folder}")
# ---------- Export PDF ----------
def generate_multiple_combined_pdf(self):
n=self.num_puzzles_var.get()
if n<1: return
path=filedialog.asksaveasfilename(defaultextension=".pdf",filetypes=[("PDF files","*.pdf")])
if not path: return
c=canvas.Canvas(path,pagesize=A4)
width,height=A4
for idx in range(1,n+1):
numbers,ops,path_cells,steps=self.create_puzzle_data()
y=height-50
c.setFont("Helvetica-Bold",20)
c.drawString(50,y,f"{self.APP_NAME} Puzzle {idx}")
y-=40
c.setFont("Helvetica",16)
c.drawString(50,y,f"Difficulty: {self.difficulty_var.get()}")
y-=30
y=self._draw_grid_pdf(c,numbers,ops,path_cells,path_cells[0],path_cells[-1],y_start=y,cell_size=40)
y-=10
c.setFont("Helvetica-Bold",16)
c.drawString(50,y,f"Target: {self.target_number}")
y-=30
c.setFont("Helvetica",14)
c.drawString(50,y,"Solution:")
y-=20
for step in steps:
c.drawString(60,y,step)
y-=18
if y<50: c.showPage(); y=height-50
c.showPage()
c.save()
messagebox.showinfo("Export PDF", f"Combined PDF exported to {path}")
def generate_combined_jpg(self):
n = self.num_puzzles_var.get()
if n < 1:
return
path = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG", "*.jpg")])
if not path:
return
font_path = "arial.ttf"
try:
font_title = ImageFont.truetype(font_path, 28)
font_step = ImageFont.truetype(font_path, 18)
except:
font_title = font_step = ImageFont.load_default()
cell_size = 60
line_height = 24
spacing_between_puzzles = 50
margin = 20 # margin around content
img_width = 900
# Collect puzzle data
puzzles_data = []
total_height = margin
for _ in range(n):
numbers, ops, path_cells, steps = self.create_puzzle_data()
grid_height = self.rows * (cell_size + 10)
steps_height = len(steps) * line_height
puzzle_height = 45 + 50 + grid_height + 10 + 50 + line_height + steps_height + spacing_between_puzzles
total_height += puzzle_height
puzzles_data.append((numbers, ops, path_cells, steps))
img = Image.new("RGB", (img_width, total_height), (34, 34, 34))
draw = ImageDraw.Draw(img)
y = margin
for idx, (numbers, ops, path_cells, steps) in enumerate(puzzles_data, 1):
# Title & Difficulty
draw.text((margin, y), f"{self.APP_NAME} Puzzle {idx}", fill="white", font=font_title)
y += 45
draw.text((margin, y), f"Difficulty: {self.difficulty_var.get()}", fill="white", font=font_title)
y += 50
# Draw grid centered horizontally
grid_width = self.cols * (cell_size + 15) - 15
x_start = (img_width - grid_width) // 2
for r in range(self.rows):
x = x_start
for c_idx in range(self.cols):
text = str(numbers[r][c_idx]) if ops[r][c_idx] is None else f"{ops[r][c_idx]}{numbers[r][c_idx]}"
if (r, c_idx) in path_cells:
draw.rectangle([x, y, x + cell_size, y + cell_size], fill=(76, 175, 80))
else:
draw.rectangle([x, y, x + cell_size, y + cell_size], outline="white", width=2)
if (r, c_idx) == path_cells[0]:
text = "▶ " + text
if (r, c_idx) == path_cells[-1]:
text = text + " ⬇"
bbox = font_title.getbbox(text)
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
draw.text((x + (cell_size - w) / 2, y + (cell_size - h) / 2), text, fill="white", font=font_title)
x += cell_size + 15
y += cell_size + 15
# Target
y += 10
draw.text((margin, y), f"Target: {self.target_number}", fill=(249, 199, 79), font=font_title)
y += 50
# Solution steps
draw.text((margin, y), "Solution:", fill="white", font=font_title)
y += line_height + 10
# Wrap long steps
max_chars = 40
for step in steps:
while len(step) > max_chars:
split_at = step.rfind(" ", 0, max_chars)
if split_at == -1:
split_at = max_chars
draw.text((margin + 20, y), step[:split_at], fill="white", font=font_step)
step = step[split_at:].strip()
y += line_height
if step:
draw.text((margin + 20, y), step, fill="white", font=font_step)
y += line_height
y += spacing_between_puzzles
img.save(path)
messagebox.showinfo("Export Combined JPG", f"Combined JPG exported to {path}")
def generate_multiple_jpgs(self):
n = self.num_puzzles_var.get()
if n < 1:
return
folder = filedialog.askdirectory()
if not folder:
return
folder = Path(folder)
font_path = "arial.ttf"
cell_size = 60
line_height = 24
spacing_between_sections = 40
margin = 20
img_width = 900
for idx in range(1, n + 1):
numbers, ops, path_cells, steps = self.create_puzzle_data()
# Dynamically calculate image height
grid_height = self.rows * (cell_size + 10)
steps_height = len(steps) * line_height
img_height = 45 + 50 + grid_height + 10 + 50 + line_height + steps_height + spacing_between_sections + margin*2
img = Image.new("RGB", (img_width, img_height), (34, 34, 34))
draw = ImageDraw.Draw(img)
try:
font_title = ImageFont.truetype(font_path, 28)
font_step = ImageFont.truetype(font_path, 18)
except:
font_title = font_step = ImageFont.load_default()
y = margin
draw.text((margin, y), f"{self.APP_NAME} Puzzle {idx}", fill="white", font=font_title)
y += 45
draw.text((margin, y), f"Difficulty: {self.difficulty_var.get()}", fill="white", font=font_title)
y += 50
grid_width = self.cols * (cell_size + 15) - 15
x_start = (img_width - grid_width) // 2
self._draw_grid_jpg(draw, numbers, ops, path_cells, path_cells[0], path_cells[-1], y_start=y)
y += grid_height + 10
draw.text((margin, y), f"Target: {self.target_number}", fill=(249, 199, 79), font=font_title)
y += spacing_between_sections
draw.text((margin, y), "Solution:", fill="white", font=font_title)
y += line_height + 10
for step in steps:
while len(step) > 40:
split_at = step.rfind(" ", 0, 40)
if split_at == -1:
split_at = 40
draw.text((margin + 20, y), step[:split_at], fill="white", font=font_step)
step = step[split_at:].strip()
y += line_height
if step:
draw.text((margin + 20, y), step, fill="white", font=font_step)
y += line_height
img.save(folder / f"Puzzle_{idx}.jpg")
messagebox.showinfo("Export JPGs", f"{n} separate JPGs exported to {folder}")
def generate_single_puzzle(self):
self.clear_all()
self.create_puzzle()
self.display_grid()
self.show_solution()
# ---------------- INFO ----------------
def show_about(self):
messagebox.showinfo(
f"About {self.APP_NAME}",
f"{self.APP_NAME} v{self.APP_VERSION}\n\n"
f"{self.APP_NAME} is an educational puzzle generator designed to help students "
"practice arithmetic, logic, and problem-solving skills. It creates step-by-step "
"solvable puzzles, supports multiple difficulty levels, and produces print-ready PDFs and JPGs.\n\n"
"Key Features:\n"
"• Automatically generate puzzles with 4, 6, or 9 numbers\n"
"• Step-by-step recursive solutions for every puzzle\n"
"• Visual number grid display (2x2, 2x3, 3x3) for clarity\n"
"• Generate single puzzles or multiple puzzles in one PDF or combined JPG\n"
"• Export options: PDF, JPG, separate or combined worksheets\n"
"• Adjustable grid spacing and borders for better printing\n"
"• Dark-themed, modern GUI with live preview\n\n"
"Use Cases:\n"
"• Classroom exercises and worksheets for students\n"
"• Homework or extra practice sessions\n"
"• Math clubs, enrichment programs, or tutoring\n"
"• Developing logic and arithmetic skills\n\n"
"Tips:\n"
"1. Choose difficulty: Easy (4 numbers), Medium (6 numbers), Hard (9 numbers)\n"
"2. Set the number of puzzles to generate\n"
"3. Preview the puzzle grid and solution before exporting\n"
"4. Export puzzles to PDF or JPG for printing or sharing\n"
"5. Combine multiple puzzles into one worksheet for convenience\n\n"
f"{self.APP_NAME} – Make arithmetic practice fun, visual, and organized.\n"
"Mate Technologies / Website: https://matetools.gumroad.com"
)
def run(self): self.root.mainloop()
if __name__=="__main__":
MazeMath().run()