-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpascal.html
More file actions
638 lines (588 loc) · 30.9 KB
/
Copy pathpascal.html
File metadata and controls
638 lines (588 loc) · 30.9 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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Треугольник Паскаля — Фрактал Серпинского</title>
<style>
:root{--bg:#0f172a;--bg2:#1e293b;--card:#1e293b;--border:#334155;--border2:#1e293b;--text:#e2e8f0;--muted:#94a3b8;--subtle:#64748b;--track:#334155;--btn2:#334155;--btn2-text:#94a3b8;--acc:#06b6d4;--acc2:#0891b2;--acc-glow:rgba(6,182,212,.4);}
html.light{--bg:#f8fafc;--bg2:#f1f5f9;--card:#fff;--border:#94a3b8;--border2:#cbd5e1;--text:#0f172a;--muted:#374151;--subtle:#334155;--track:#94a3b8;--btn2:#e2e8f0;--btn2-text:#1e293b;--acc:#0891b2;--acc2:#0e7490;--acc-glow:rgba(8,145,178,.3);}
*{margin:0;padding:0;box-sizing:border-box;}
html,body{font-family:'Segoe UI',system-ui,sans-serif;background:var(--bg);color:var(--text);height:100vh;overflow:hidden;transition:background .2s,color .2s;}
.app{display:grid;grid-template-rows:auto 1fr auto;height:100vh;}
.top-bar{display:flex;align-items:center;gap:16px;padding:10px 20px;background:linear-gradient(135deg,var(--bg2),var(--bg));border-bottom:1px solid var(--border2);flex-wrap:wrap;}
.top-bar h1{font-size:1.2em;font-weight:700;background:linear-gradient(135deg,var(--acc),var(--acc2));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;white-space:nowrap;}
.back-link{text-decoration:none;color:var(--muted);font-size:.85em;padding:4px 10px;border-radius:6px;border:1px solid var(--border);transition:color .15s,border-color .15s;white-space:nowrap;}
.back-link:hover{color:var(--text);border-color:var(--muted);}
.top-controls{display:flex;align-items:center;gap:14px;flex:1;flex-wrap:wrap;}
.slider-group{display:flex;align-items:center;gap:6px;}
.slider-group label{font-size:.8em;color:var(--muted);text-transform:uppercase;letter-spacing:.4px;font-weight:600;}
.slider-group .val{font-size:1.3em;font-weight:700;color:var(--acc);min-width:36px;text-align:center;}
input[type=range]{-webkit-appearance:none;width:110px;height:6px;border-radius:3px;background:var(--track);outline:none;}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border-radius:50%;background:var(--acc);cursor:pointer;box-shadow:0 0 8px var(--acc-glow);}
.btn{padding:8px 16px;border:none;border-radius:8px;font-size:.85em;font-weight:600;cursor:pointer;transition:all .2s;}
.btn-play{background:linear-gradient(135deg,var(--acc),var(--acc2));color:#fff;}
.btn-reset{background:var(--btn2);color:var(--btn2-text);}
.btn-speed{background:var(--btn2);color:var(--btn2-text);padding:8px 12px;font-size:.8em;}
.btn-speed.active{background:var(--acc);color:#fff;}
.btn-mode{background:var(--btn2);color:var(--btn2-text);padding:8px 14px;font-size:.82em;border:1px solid var(--border);}
.btn-mode.active{background:rgba(6,182,212,.2);color:var(--acc);border-color:var(--acc);}
html.light .btn-mode.active{background:rgba(8,145,178,.15);}
.btn-theme{background:var(--btn2);color:var(--btn2-text);padding:8px 14px;font-size:.85em;margin-left:auto;border:1px solid var(--border);}
.main-grid{display:grid;grid-template-columns:1fr 1fr;min-height:0;overflow:hidden;}
.scene-cell{display:flex;flex-direction:column;border-right:1px solid var(--border2);min-height:0;overflow:hidden;}
.cell-title{font-size:.8em;color:var(--subtle);text-transform:uppercase;letter-spacing:1px;font-weight:600;padding:8px 14px 4px;}
.scene-wrap{flex:1;min-height:0;position:relative;}
canvas{display:block;}
.formulas-cell{display:flex;flex-direction:column;gap:10px;padding:14px 20px;overflow-y:auto;min-height:0;}
.formulas-cell::-webkit-scrollbar{width:4px;}
.formulas-cell::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px;}
.formula-card{background:var(--card);border-radius:12px;padding:14px 20px;border:1px solid var(--border);}
.formula-card .card-title{font-size:.85em;color:var(--subtle);text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px;font-weight:600;}
.formula-card .formula{font-size:1.15em;color:#67e8f9;font-family:'Courier New',monospace;margin-bottom:4px;}
html.light .formula-card .formula{color:#0e7490;}
.formula-card .calculation{font-size:1em;color:var(--text);font-weight:600;line-height:1.6;}
.hl-y{color:#fbbf24;}html.light .hl-y{color:#d97706;}
.hl-b{color:#60a5fa;}html.light .hl-b{color:#1d4ed8;}
.hl-c{color:#67e8f9;}html.light .hl-c{color:#0e7490;}
.note-card{background:rgba(6,182,212,.08);border:1px solid rgba(6,182,212,.25);border-radius:12px;padding:12px 18px;font-size:.88em;color:var(--muted);line-height:1.55;}
html.light .note-card{background:rgba(8,145,178,.06);}
.bottom-bar{display:flex;align-items:stretch;border-top:1px solid var(--border2);background:var(--bg2);}
.status-items{display:flex;gap:18px;padding:8px 20px;align-items:center;}
.status-item{display:flex;flex-direction:column;align-items:center;}
.status-item .label{font-size:.7em;color:var(--subtle);text-transform:uppercase;letter-spacing:.3px;}
.status-item .value{font-size:1.3em;font-weight:700;}
.sv-a{color:var(--acc);}
.sv-y{color:#fbbf24;}html.light .sv-y{color:#d97706;}
.sv-g{color:#4ade80;}html.light .sv-g{color:#15803d;}
.insight-item{padding:8px 20px;font-size:.88em;color:#67e8f9;display:none;align-items:center;border-left:1px solid var(--border);max-width:400px;line-height:1.4;}
html.light .insight-item{color:#0891b2;}
.insight-item.visible{display:flex;}
@media(max-width:700px){
html,body{height:auto;overflow-y:auto;}
.app{height:auto;min-height:100svh;grid-template-rows:auto auto auto;}
.top-bar{padding:8px 12px;gap:8px;}.top-bar h1{font-size:1em;}
.top-controls{gap:8px;}.slider-group .val{font-size:1.1em;}
input[type=range]{width:76px;}.btn-theme{margin-left:0;}
.main-grid{grid-template-columns:1fr;overflow:visible;}
.scene-cell{height:56vw;min-height:220px;max-height:340px;border-right:none;border-bottom:1px solid var(--border2);}
.formulas-cell{overflow:visible;height:auto;padding:12px 14px;gap:8px;}
.bottom-bar{flex-wrap:wrap;}.status-items{flex-wrap:wrap;gap:10px;padding:8px 12px;}}
/* ── Info Modal ── */
.btn-info{background:var(--btn2);color:var(--btn2-text);padding:8px 14px;font-size:.85em;border:1px solid var(--border);}
.btn-info:hover{color:var(--text);border-color:var(--muted);}
.info-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.65);backdrop-filter:blur(5px);-webkit-backdrop-filter:blur(5px);z-index:999;align-items:flex-start;justify-content:center;padding:24px 16px;overflow-y:auto;}
.info-overlay.open{display:flex;}
.info-modal{background:var(--card);border:1px solid var(--border);border-radius:16px;max-width:660px;width:100%;padding:28px 30px 24px;position:relative;margin:auto;}
.info-modal h2{font-size:1.15em;font-weight:700;background:linear-gradient(135deg,var(--acc),var(--acc2));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;margin-bottom:18px;padding-right:32px;line-height:1.35;}
.info-close{position:absolute;top:14px;right:14px;background:var(--btn2);color:var(--btn2-text);border:none;border-radius:6px;cursor:pointer;padding:5px 11px;font-size:1em;transition:all .15s;}
.info-close:hover{color:var(--text);}
.info-sec{margin-bottom:16px;}
.info-sec h3{font-size:.78em;text-transform:uppercase;letter-spacing:.6px;color:var(--subtle);margin-bottom:6px;font-weight:600;border-bottom:1px solid var(--border2);padding-bottom:4px;}
.info-sec p,.info-sec ul{font-size:.9em;color:var(--muted);line-height:1.7;}
.info-sec ul{padding-left:18px;}.info-sec li{margin-bottom:5px;}
.info-sec strong{color:var(--text);}
.info-hl{background:var(--bg2);border-left:3px solid var(--acc);padding:9px 14px;border-radius:0 8px 8px 0;font-family:'Courier New',monospace;font-size:.88em;color:var(--text);margin:8px 0;line-height:1.7;white-space:pre-wrap;}
</style>
</head>
<body>
<div class="app">
<div class="top-bar">
<a href="index.html" class="back-link">← Назад</a>
<h1>🔺 Треугольник Паскаля</h1>
<div class="top-controls">
<div class="slider-group">
<label>Строки N</label>
<input type="range" id="slN" min="2" max="20" value="8">
<span class="val" id="valN">8</span>
</div>
<button class="btn btn-play" id="btnPlay">▶ Старт</button>
<button class="btn btn-reset" id="btnReset">↺ Сброс</button>
<button class="btn btn-speed" id="btn1x">1×</button>
<button class="btn btn-speed active" id="btn2x">2×</button>
<button class="btn btn-mode active" id="btnNums">🔢 Числа</button>
<button class="btn btn-mode" id="btnColor">🎨 Цвет</button>
<button class="btn btn-mode" id="btnFib">🌀 Фибоначчи</button>
<button class="btn btn-info" id="btnInfo">📖 О модели</button>
<button class="btn btn-theme" id="btnTheme">☀</button>
</div>
</div>
<div class="main-grid">
<div class="scene-cell">
<div class="cell-title">Визуализация</div>
<div class="scene-wrap">
<canvas id="cv"></canvas>
</div>
</div>
<div class="formulas-cell" id="panel"></div>
</div>
<div class="bottom-bar">
<div class="status-items">
<div class="status-item">
<span class="label">Строк</span>
<span class="value sv-a" id="stRows">0</span>
</div>
<div class="status-item">
<span class="label">Сумма строки</span>
<span class="value sv-y" id="stSum">—</span>
</div>
<div class="status-item">
<span class="label">Всего чисел</span>
<span class="value sv-g" id="stTotal">0</span>
</div>
</div>
<div class="insight-item" id="insight">✨ Нечётные числа образуют треугольник Серпинского!</div>
</div>
</div>
<script>
// Compute Pascal's triangle up to n rows
function buildPascal(n) {
const tri = [];
for (let r = 0; r < n; r++) {
const row = [];
for (let k = 0; k <= r; k++) {
if (k === 0 || k === r) row.push(1);
else row.push(tri[r-1][k-1] + tri[r-1][k]);
}
tri.push(row);
}
return tri;
}
// ─── Canvas ───
const cv = document.getElementById('cv');
const ctx = cv.getContext('2d');
function resizeCanvas() {
const rect = cv.parentElement.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
cv.width = rect.width * dpr;
cv.height = rect.height * dpr;
cv.style.width = rect.width + 'px';
cv.style.height = rect.height + 'px';
ctx.scale(dpr, dpr);
}
window.addEventListener('resize', () => { resizeCanvas(); render(); });
// ─── State ───
let N = 8;
let animTime = 0;
let isPlaying = false;
let speed = 2;
let colorMode = false; // false=numbers, true=odd/even coloring
let fibMode = false; // Fibonacci diagonal highlighting
let rafId = null;
let lastTs = null;
// Diagonal d = row+col — sum of its cells = Fibonacci number F(d+1)
const FIBS_P = [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765];
const DIAG_COLORS = [
'#f43f5e','#f97316','#eab308','#22c55e','#06b6d4',
'#6366f1','#a855f7','#ec4899','#14b8a6','#10b981',
'#f43f5e','#f97316','#eab308','#22c55e','#06b6d4',
'#6366f1','#a855f7','#ec4899','#14b8a6','#10b981',
];
// ─── Controls ───
const slN = document.getElementById('slN');
const valN = document.getElementById('valN');
const btnPlay = document.getElementById('btnPlay');
const btnReset = document.getElementById('btnReset');
const btn1x = document.getElementById('btn1x');
const btn2x = document.getElementById('btn2x');
const btnNums = document.getElementById('btnNums');
const btnColor = document.getElementById('btnColor');
const btnFib = document.getElementById('btnFib');
const btnTheme = document.getElementById('btnTheme');
slN.addEventListener('input', () => {
N = +slN.value;
valN.textContent = N;
animTime = Math.min(animTime, N);
updatePanel();
render();
});
btnPlay.addEventListener('click', () => {
if (isPlaying) { pause(); }
else { if (animTime >= N) animTime = 0; play(); }
});
btnReset.addEventListener('click', () => { pause(); animTime = 0; updatePanel(); render(); });
btn1x.addEventListener('click', () => { speed=1; btn1x.classList.add('active'); btn2x.classList.remove('active'); });
btn2x.addEventListener('click', () => { speed=2; btn2x.classList.add('active'); btn1x.classList.remove('active'); });
function setMode(nums, color, fib) {
colorMode = color; fibMode = fib;
btnNums.classList.toggle('active', nums);
btnColor.classList.toggle('active', color);
btnFib.classList.toggle('active', fib);
updatePanel(); render();
}
btnNums.addEventListener('click', () => setMode(true, false, false));
btnColor.addEventListener('click', () => setMode(false, true, false));
btnFib.addEventListener('click', () => setMode(false, false, true));
btnTheme.addEventListener('click', () => { document.documentElement.classList.toggle('light'); render(); });
function play() {
isPlaying = true;
btnPlay.textContent = '⏸ Пауза';
lastTs = null;
rafId = requestAnimationFrame(animate);
}
function pause() {
isPlaying = false;
btnPlay.textContent = '▶ Старт';
if (rafId) { cancelAnimationFrame(rafId); rafId = null; }
}
function animate(ts) {
if (!isPlaying) return;
if (lastTs === null) lastTs = ts;
const dt = (ts - lastTs) / 1000;
lastTs = ts;
animTime = Math.min(animTime + dt * speed * 0.9, N);
updatePanel();
render();
if (animTime >= N) { pause(); return; }
rafId = requestAnimationFrame(animate);
}
// ─── Render ───
function isLight() { return document.documentElement.classList.contains('light'); }
// Color for a value in color mode
function cellColor(val, light) {
if (val === 0) return 'transparent';
const odd = val % 2 === 1;
if (odd) return light ? 'rgba(6,182,212,0.85)' : 'rgba(6,182,212,0.9)';
return light ? 'rgba(100,116,139,0.15)' : 'rgba(30,41,59,0.5)';
}
function render() {
const dpr = window.devicePixelRatio || 1;
const W = cv.width / dpr, H = cv.height / dpr;
const light = isLight();
ctx.clearRect(0, 0, W, H);
const rows = Math.floor(animTime); // fully shown rows
const frac = animTime - rows; // partial row progress
if (animTime < 0.01) {
ctx.fillStyle = light ? 'rgba(8,145,178,0.08)' : 'rgba(6,182,212,0.12)';
ctx.beginPath(); ctx.arc(W/2, H/2, 55, 0, 2*Math.PI); ctx.fill();
ctx.fillStyle = light ? '#0891b2' : '#67e8f9';
ctx.font = 'bold 28px Segoe UI'; ctx.textAlign='center'; ctx.textBaseline='middle';
ctx.fillText('▶', W/2, H/2);
updateStatus(0);
return;
}
const tri = buildPascal(Math.min(rows + 1, N));
const displayRows = Math.min(rows + 1, N);
// Cell sizing
const pad = 0.05;
const cellW = Math.min((W * (1-2*pad)) / displayRows, (H * (1-2*pad)) / displayRows * 1.15);
const cellH = cellW * 0.88;
const totalW = displayRows * cellW;
const totalH = displayRows * cellH;
const startX = (W - totalW) / 2;
const startY = (H - totalH) / 2;
for (let r = 0; r < displayRows; r++) {
if (!tri[r]) continue;
const rowAlpha = (r < rows) ? 1 : frac; // partial last row
const rowY = startY + r * cellH;
const rowStartX = startX + (displayRows - 1 - r) * cellW / 2;
for (let k = 0; k <= r; k++) {
const val = tri[r][k];
const cx = rowStartX + k * cellW + cellW / 2;
const cy = rowY + cellH / 2;
if (fibMode) {
// Fibonacci diagonal mode: color by diagonal d = row + col
const d = r + k;
const diagCol = DIAG_COLORS[d % DIAG_COLORS.length];
const hw = cellW * 0.42, hh = cellH * 0.42;
ctx.globalAlpha = rowAlpha * 0.88;
ctx.fillStyle = diagCol;
roundRect(ctx, cx-hw, cy-hh, hw*2, hh*2, 5);
ctx.fill();
ctx.globalAlpha = rowAlpha;
ctx.strokeStyle = light ? 'rgba(255,255,255,0.5)' : 'rgba(0,0,0,0.35)';
ctx.lineWidth = 1;
roundRect(ctx, cx-hw, cy-hh, hw*2, hh*2, 5);
ctx.stroke();
ctx.globalAlpha = 1;
if (cellW > 18) {
ctx.globalAlpha = rowAlpha;
ctx.fillStyle = '#fff';
const fs = Math.max(8, Math.min(cellW * 0.28, 16));
ctx.font = `bold ${fs}px 'Courier New',monospace`;
ctx.textAlign='center'; ctx.textBaseline='middle';
ctx.fillText(val > 9999 ? '…' : String(val), cx, cy);
ctx.globalAlpha = 1;
}
} else if (colorMode) {
// Color mode: odd=teal, even=dark
const odd = val % 2 === 1;
if (odd) {
ctx.fillStyle = light
? `rgba(6,182,212,${0.8 * rowAlpha})`
: `rgba(6,182,212,${0.85 * rowAlpha})`;
const sz = cellW * 0.44;
ctx.beginPath();
ctx.moveTo(cx, cy - sz);
ctx.lineTo(cx + sz * 0.866, cy + sz * 0.5);
ctx.lineTo(cx - sz * 0.866, cy + sz * 0.5);
ctx.closePath();
ctx.fill();
} else {
ctx.fillStyle = light
? `rgba(148,163,184,${0.15 * rowAlpha})`
: `rgba(30,41,59,${0.7 * rowAlpha})`;
const sz = cellW * 0.38;
ctx.fillRect(cx - sz/2, cy - sz/2, sz, sz);
}
} else {
// Number mode
const isBorder = (k === 0 || k === r);
const bg = isBorder
? (light ? 'rgba(6,182,212,0.2)' : 'rgba(6,182,212,0.18)')
: (light ? 'rgba(99,102,241,0.12)' : 'rgba(99,102,241,0.14)');
const border = isBorder
? (light ? 'rgba(6,182,212,0.6)' : 'rgba(6,182,212,0.5)')
: (light ? 'rgba(99,102,241,0.4)' : 'rgba(99,102,241,0.35)');
const textCol = isBorder
? (light ? '#0891b2' : '#67e8f9')
: (light ? '#4f46e5' : '#a78bfa');
const hw = cellW * 0.43, hh = cellH * 0.43;
const rx = 4;
ctx.globalAlpha = rowAlpha;
ctx.fillStyle = bg;
roundRect(ctx, cx-hw, cy-hh, hw*2, hh*2, rx);
ctx.fill();
ctx.strokeStyle = border;
ctx.lineWidth = 1;
roundRect(ctx, cx-hw, cy-hh, hw*2, hh*2, rx);
ctx.stroke();
ctx.globalAlpha = 1;
if (cellW > 24) {
ctx.globalAlpha = rowAlpha;
ctx.fillStyle = textCol;
const fs = Math.max(9, Math.min(cellW * 0.3, 18));
ctx.font = `bold ${fs}px 'Courier New',monospace`;
ctx.textAlign='center'; ctx.textBaseline='middle';
ctx.fillText(val > 999 ? '…' : String(val), cx, cy);
ctx.globalAlpha = 1;
}
}
}
}
// ── Fibonacci diagonal lines + sum labels ──
if (fibMode) {
const labelFs = Math.max(9, Math.min(cellW * 0.28, 14));
ctx.font = `bold ${labelFs}px 'Courier New',monospace`;
for (let d = 0; d < 2 * displayRows - 1; d++) {
const col = DIAG_COLORS[d % DIAG_COLORS.length];
// Collect cells of this diagonal (r+k=d, k<=r, r<displayRows)
const pts = [];
for (let k = 0; k <= Math.floor(d / 2); k++) {
const r2 = d - k;
if (r2 >= displayRows) continue;
const rowStartX2 = startX + (displayRows - 1 - r2) * cellW / 2;
pts.push({ cx: rowStartX2 + k * cellW + cellW / 2, cy: startY + r2 * cellH + cellH / 2 });
}
if (pts.length < 2) continue;
// Draw dashed diagonal line connecting centres
ctx.save();
ctx.setLineDash([3, 4]);
ctx.strokeStyle = col;
ctx.lineWidth = 1.5;
ctx.globalAlpha = 0.6;
ctx.beginPath();
ctx.moveTo(pts[0].cx, pts[0].cy);
for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].cx, pts[i].cy);
ctx.stroke();
ctx.restore();
// Sum label to the right of the topmost cell
if (d < FIBS_P.length) {
const top = pts[0]; // topmost-rightmost (lowest r = highest k)
const labelX = top.cx + cellW * 0.62;
const labelY = top.cy;
if (labelX + cellW * 1.5 < W) {
ctx.globalAlpha = 0.9;
ctx.fillStyle = col;
ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
ctx.fillText(`= ${FIBS_P[d]}`, labelX, labelY);
ctx.globalAlpha = 1;
}
}
}
}
updateStatus(rows);
}
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x+r, y);
ctx.lineTo(x+w-r, y);
ctx.quadraticCurveTo(x+w, y, x+w, y+r);
ctx.lineTo(x+w, y+h-r);
ctx.quadraticCurveTo(x+w, y+h, x+w-r, y+h);
ctx.lineTo(x+r, y+h);
ctx.quadraticCurveTo(x, y+h, x, y+h-r);
ctx.lineTo(x, y+r);
ctx.quadraticCurveTo(x, y, x+r, y);
ctx.closePath();
}
// ─── Panel ───
function updatePanel() {
const rows = Math.min(Math.floor(animTime) + 1, N);
const panel = document.getElementById('panel');
const tri = buildPascal(rows);
if (fibMode) {
// Build diagonal sums table
let diagRows = '';
for (let d = 0; d < rows; d++) {
const cells = [];
for (let k = 0; k <= Math.floor(d / 2); k++) {
const r2 = d - k;
if (r2 < rows && tri[r2] && tri[r2][k] !== undefined) cells.push(tri[r2][k]);
}
if (cells.length === 0) continue;
const sum = cells.reduce((a, b) => a + b, 0);
const fibOk = sum === FIBS_P[d];
const col = DIAG_COLORS[d % DIAG_COLORS.length];
const cellsStr = cells.length <= 5
? cells.join(' + ')
: cells.slice(0, 4).join(' + ') + ' + …';
diagRows += `<div class="ratio-row">
<span class="ratio-label" style="color:${col};font-family:'Courier New',monospace;font-weight:700">
d=${d}: </span>
<span style="color:var(--muted);font-size:.82em;flex:1">${cellsStr}</span>
<span class="ratio-val${fibOk ? ' converged' : ''}">${sum}</span>
</div>`;
}
panel.innerHTML = `
<div class="formula-card" style="border-left:4px solid #6366f1">
<div class="card-title">🌀 Числа Фибоначчи в треугольнике Паскаля</div>
<p style="font-size:.88em;color:var(--muted);line-height:1.55;margin-top:4px">
Проведём <strong>пологие диагонали</strong> (↗): все клетки с одинаковым
<code style="color:#a78bfa">строка + столбец = d</code> закрашены одним цветом.
Сложи числа по каждой диагонали — получишь <strong>число Фибоначчи</strong>!
</p>
</div>
<div class="formula-card">
<div class="card-title">📐 Формула</div>
<div class="formula">F(d+1) = Σ C(d−k, k)</div>
<div class="calculation" style="font-size:.88em">
<span class="hl-b">k = 0, 1, 2, …, ⌊d/2⌋</span>
</div>
</div>
<div class="formula-card">
<div class="card-title">🔢 Диагонали → Фибоначчи (первые ${rows})</div>
${diagRows}
</div>`;
return;
}
const lastRow = tri[rows-1] || [];
const sumRow = lastRow.reduce((a,b)=>a+b, 0);
const lastRowStr = lastRow.length <= 10
? lastRow.join(' + ')
: lastRow.slice(0,5).join(' + ') + ' + … + ' + lastRow.slice(-2).join(' + ');
panel.innerHTML = `
<div class="formula-card" style="border-left:4px solid #06b6d4">
<div class="card-title">📝 Описание</div>
<p style="font-size:.88em;color:var(--muted);line-height:1.55;margin-top:4px">
Каждое число равно сумме двух чисел над ним. Нажмите <strong>🎨 Цвет</strong> —
нечётные числа выделятся, и проявится <strong>треугольник Серпинского</strong> — фрактал!
Нажмите <strong>🌀 Фибоначчи</strong>, чтобы увидеть скрытые числа Фибоначчи.
</p>
</div>
<div class="formula-card">
<div class="card-title">📐 Правило построения</div>
<div class="formula">C(n,k) = C(n−1,k−1) + C(n−1,k)</div>
<div class="calculation"><span class="hl-b">C(n,0) = C(n,n) = 1</span></div>
</div>
<div class="formula-card">
<div class="card-title">🔢 Строка ${rows} (0-индексация: строка ${rows-1})</div>
<div class="calculation" style="font-size:.9em;word-break:break-all;line-height:1.6">
<span class="hl-c">${lastRowStr}</span>
</div>
</div>
<div class="formula-card">
<div class="card-title">✨ Сумма строки ${rows}</div>
<div class="formula">Σ = 2<sup>${rows-1}</sup></div>
<div class="calculation">Σ = <span class="hl-y">${sumRow}</span></div>
</div>
<div class="note-card">
💡 В строках треугольника Паскаля спрятаны числа Фибоначчи (по диагоналям),
степени числа 11 и коэффициенты бинома Ньютона (a+b)ⁿ.
</div>`;
}
function updateStatus(rows) {
document.getElementById('stRows').textContent = rows;
const insight = document.getElementById('insight');
if (rows > 0) {
const tri = buildPascal(rows);
const last = tri[rows-1] || [];
const sum = last.reduce((a,b)=>a+b, 0);
document.getElementById('stSum').textContent = sum;
document.getElementById('stTotal').textContent = rows*(rows+1)/2;
insight.classList.toggle('visible', colorMode && rows >= 4);
} else {
document.getElementById('stSum').textContent = '—';
document.getElementById('stTotal').textContent = 0;
insight.classList.remove('visible');
}
}
// Init
updatePanel();
resizeCanvas();
render();
// ── Info Modal (defer until full DOM is parsed) ──
document.addEventListener('DOMContentLoaded', () => {
const btnInfo = document.getElementById('btnInfo');
const infoOverlay = document.getElementById('infoOverlay');
const infoClose = document.getElementById('infoClose');
btnInfo.addEventListener('click', () => infoOverlay.classList.add('open'));
infoClose.addEventListener('click', () => infoOverlay.classList.remove('open'));
infoOverlay.addEventListener('click', e => { if (e.target === infoOverlay) infoOverlay.classList.remove('open'); });
document.addEventListener('keydown', e => { if (e.key === 'Escape') infoOverlay.classList.remove('open'); });
});
</script>
<div class="info-overlay" id="infoOverlay">
<div class="info-modal">
<button class="info-close" id="infoClose">✕</button>
<h2>🔺 Треугольник Паскаля — сокровищница математики</h2>
<div class="info-sec">
<h3>Кратко</h3>
<p>Простейшее правило построения — каждое число равно сумме двух над ним — порождает треугольник, в котором зашифрованы биномиальные коэффициенты, числа Фибоначчи, степени числа 11 и даже фракталы. Не зря математики говорят: в этом треугольнике можно прожить всю научную жизнь и не исчерпать его.</p>
</div>
<div class="info-sec">
<h3>История</h3>
<p>Этот треугольник знали задолго до Паскаля. Персидский математик <strong>аль-Карраджи</strong> описал его в XI веке. В Китае он называется «треугольником Янь Хуэй» (XIII в.), в Иране — «треугольником Хайяма», в Италии — «треугольником Тартальи» (XVI в.). <strong>Блез Паскаль</strong> в 1653 году написал систематический трактат о его свойствах — с тех пор имя закрепилось в европейской традиции.</p>
</div>
<div class="info-sec">
<h3>Правило построения</h3>
<div class="info-hl">C(n, k) = C(n−1, k−1) + C(n−1, k)
Граница: C(n, 0) = C(n, n) = 1</div>
<p>Элемент C(n, k) — число способов выбрать k объектов из n (биномиальный коэффициент). Именно поэтому строки треугольника — коэффициенты бинома Ньютона <strong>(a+b)ⁿ</strong>.</p>
</div>
<div class="info-sec">
<h3>Скрытые закономерности</h3>
<ul>
<li>📊 <strong>Бином Ньютона:</strong> строка n — коэффициенты раскрытия (a+b)ⁿ</li>
<li>➕ <strong>Суммы строк:</strong> 1, 2, 4, 8, 16… = 2⁰, 2¹, 2², 2³…</li>
<li>🔢 <strong>Степени числа 11:</strong> 11⁰=1, 11¹=11, 11²=121, 11³=1331, 11⁴=14641</li>
<li>🌀 <strong>Числа Фибоначчи:</strong> суммы по «пологим» диагоналям ↗ (кнопка 🌀 Фибоначчи)</li>
<li>🔺 <strong>Треугольник Серпинского:</strong> нечётные числа — фрактал (кнопка 🎨 Цвет)</li>
<li>🏒 <strong>«Хоккейная клюшка»:</strong> сумма чисел вдоль диагонали равна числу в следующей строке</li>
<li>🔵 <strong>Треугольные числа:</strong> 1, 3, 6, 10, 15… — 2-я диагональ слева</li>
<li>🔷 <strong>Тетраэдрические числа:</strong> 1, 4, 10, 20, 35… — 3-я диагональ</li>
</ul>
</div>
<div class="info-sec">
<h3>Треугольник Серпинского</h3>
<p>Включи режим <strong>🎨 Цвет</strong> и поставь N = 20. Нечётные числа образуют самоподобный фрактал — <strong>треугольник Серпинского</strong>. Он строится бесконечным вырезанием средних треугольников. Его размерность Хаусдорфа = log₂3 ≈ 1,585 — это число «между» линией (1) и плоскостью (2)!</p>
</div>
<div class="info-sec">
<h3>Числа Фибоначчи по диагоналям</h3>
<p>«Пологие» диагонали — клетки с одинаковой суммой строка + столбец — дают числа Фибоначчи:</p>
<div class="info-hl">F(d+1) = Σ C(d−k, k), k = 0, 1, …, ⌊d/2⌋
d=4: C(4,0)+C(3,1)+C(2,2) = 1+3+1 = 5 = F(5)</div>
</div>
<div class="info-sec">
<h3>Применение</h3>
<ul>
<li><strong>Комбинаторика и вероятность:</strong> подсчёт числа исходов, биномиальное распределение</li>
<li><strong>Алгебра:</strong> быстрое раскрытие (a+b)ⁿ без длинного умножения</li>
<li><strong>Теория чисел:</strong> строка p простая ⟺ все внутренние числа делятся на p</li>
<li><strong>Информатика:</strong> динамическое программирование, задачи на подсчёт путей</li>
</ul>
</div>
</div>
</div>
</body>
</html>