Guest User

Observation Practice

a guest
May 4th, 2026
100
0
Never
6
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 34.62 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Observation Practice</title>
  6. <style>
  7. :root { color-scheme: light; }
  8. body { font-family: system-ui, -apple-system, "Segoe UI", sans-serif; margin: 0; padding: 16px; background: #f4f4f5; color: #18181b; }
  9. h1 { margin: 0 0 12px 0; font-size: 20px; }
  10. .tabs { display: flex; gap: 4px; margin-bottom: 16px; border-bottom: 1px solid #e4e4e7; }
  11. .tab { padding: 8px 16px; font-size: 14px; background: none; border: none; border-bottom: 2px solid transparent; cursor: pointer; color: #71717a; font-family: inherit; margin-bottom: -1px; }
  12. .tab:hover { color: #18181b; }
  13. .tab.active { color: #18181b; border-bottom-color: #3b82f6; font-weight: 500; }
  14. .controls { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
  15. .controls label { font-size: 14px; display: inline-flex; align-items: center; gap: 4px; }
  16. select, input, button { padding: 6px 10px; font-size: 14px; border-radius: 6px; border: 1px solid #d4d4d8; background: white; font-family: inherit; }
  17. input[type=number] { width: 60px; }
  18. button { cursor: pointer; }
  19. button:hover:not(:disabled) { background: #f4f4f5; }
  20. button:disabled { opacity: 0.5; cursor: not-allowed; }
  21. button.primary { background: #3b82f6; color: white; border-color: #3b82f6; }
  22. button.primary:hover:not(:disabled) { background: #2563eb; }
  23. button.danger { color: #b91c1c; border-color: #fecaca; }
  24. button.danger:hover:not(:disabled) { background: #fef2f2; }
  25. .canvases { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
  26. .panel { background: white; border-radius: 8px; padding: 12px; }
  27. .panel h3 { margin: 0 0 8px 0; font-size: 12px; color: #71717a; text-transform: uppercase; letter-spacing: 0.5px; font-weight: 600; }
  28. canvas { display: block; border: 1px solid #e4e4e7; border-radius: 4px; background: white; touch-action: none; max-width: 100%; }
  29. canvas.editable { cursor: crosshair; }
  30. .tool-row { margin-top: 8px; display: flex; gap: 6px; flex-wrap: wrap; }
  31. .tool-row button.active { background: #18181b; color: white; border-color: #18181b; }
  32. .hint { font-size: 12px; color: #71717a; margin-top: 6px; min-height: 16px; }
  33. .score { margin-top: 16px; background: white; border-radius: 8px; padding: 16px; }
  34. .score-overall { font-size: 28px; font-weight: 600; }
  35. .score-overall .label { font-size: 14px; color: #71717a; font-weight: 400; margin-right: 8px; }
  36. .score-detail { margin-top: 12px; font-size: 13px; }
  37. .score-detail table { border-collapse: collapse; width: 100%; }
  38. .score-detail th, .score-detail td { text-align: left; padding: 6px 10px; border-bottom: 1px solid #f4f4f5; }
  39. .score-detail th { color: #71717a; font-weight: 500; font-size: 12px; text-transform: uppercase; letter-spacing: 0.3px; }
  40. .score-detail .sub td { padding-left: 28px; font-size: 12px; color: #71717a; }
  41. .pct { font-variant-numeric: tabular-nums; }
  42. .good { color: #15803d; }
  43. .ok { color: #a16207; }
  44. .bad { color: #b91c1c; }
  45. .records-toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
  46. .records-toolbar .spacer { flex: 1; }
  47. .records-toolbar .count { font-size: 13px; color: #71717a; }
  48. .records-list { background: white; border-radius: 8px; overflow: hidden; }
  49. .records-list table { border-collapse: collapse; width: 100%; font-size: 14px; }
  50. .records-list th, .records-list td { padding: 10px 12px; text-align: left; border-bottom: 1px solid #f4f4f5; }
  51. .records-list th { color: #71717a; font-weight: 500; font-size: 12px; text-transform: uppercase; letter-spacing: 0.3px; background: #fafafa; }
  52. .records-list tbody tr { cursor: pointer; }
  53. .records-list tbody tr:hover { background: #f4f4f5; }
  54. .records-list .actions { text-align: right; }
  55. .records-list .actions button { padding: 4px 10px; font-size: 12px; }
  56. .records-empty { padding: 40px; text-align: center; color: #71717a; background: white; border-radius: 8px; }
  57. .record-detail-toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; background: white; border-radius: 8px; padding: 10px 14px; }
  58. .record-detail-toolbar .meta { flex: 1; font-size: 14px; }
  59. .record-detail-toolbar .meta b { font-weight: 600; }
  60. .record-detail-toolbar .nav-info { font-size: 12px; color: #71717a; }
  61. .kbd { display: inline-block; padding: 1px 5px; font-size: 11px; font-family: ui-monospace, monospace; background: #f4f4f5; border: 1px solid #e4e4e7; border-radius: 3px; color: #52525b; }
  62. [hidden] { display: none !important; }
  63. </style>
  64. </head>
  65. <body>
  66. <h1>Observation Practice</h1>
  67.  
  68. <div class="tabs">
  69. <button class="tab active" data-tab="practice">Practice</button>
  70. <button class="tab" data-tab="records">Records <span id="tab-records-count" class="count"></span></button>
  71. </div>
  72.  
  73. <!-- Practice view -->
  74. <div id="view-practice">
  75. <div class="controls">
  76. <label>Mode:
  77. <select id="mode">
  78. <option value="dots">Dots</option>
  79. <option value="lines">Lines</option>
  80. <option value="polygon">Polygon</option>
  81. <option value="mixed">Mixed</option>
  82. </select>
  83. </label>
  84. <label>Count: <input id="count" type="number" min="1" max="12" value="3"></label>
  85. <button class="primary" id="generate">New Puzzle</button>
  86. <button id="check">Check Accuracy</button>
  87. <button id="clear">Clear Drawing</button>
  88. <button id="reveal" disabled>Toggle Overlay</button>
  89. </div>
  90.  
  91. <div class="canvases">
  92. <div class="panel">
  93. <h3>Reference</h3>
  94. <canvas id="ref" width="500" height="500"></canvas>
  95. </div>
  96. <div class="panel">
  97. <h3>Your Drawing</h3>
  98. <canvas id="user" class="editable" width="500" height="500"></canvas>
  99. <div class="tool-row" id="tool-row">
  100. <button data-tool="dot" class="active">Dot</button>
  101. <button data-tool="line">Line</button>
  102. <button data-tool="polygon">Polygon</button>
  103. <button data-action="finishPoly">Finish Polygon</button>
  104. <button data-action="undo">Undo</button>
  105. </div>
  106. <div class="hint" id="hint">Click to place a dot.</div>
  107. </div>
  108. </div>
  109.  
  110. <div class="score" id="score" hidden>
  111. <div class="score-overall"><span class="label">Overall</span><span id="overall"></span></div>
  112. <div class="score-detail" id="detail"></div>
  113. </div>
  114. </div>
  115.  
  116. <!-- Records view -->
  117. <div id="view-records" hidden>
  118. <!-- list mode -->
  119. <div id="records-list-mode">
  120. <div class="records-toolbar">
  121. <button id="export-records">Export</button>
  122. <button id="import-records">Import</button>
  123. <input type="file" id="import-file" accept="application/json,.json" hidden>
  124. <button class="danger" id="clear-all-records">Clear All</button>
  125. <span class="spacer"></span>
  126. <span class="count" id="records-count"></span>
  127. </div>
  128. <div id="records-list-container"></div>
  129. </div>
  130.  
  131. <!-- detail mode -->
  132. <div id="records-detail-mode" hidden>
  133. <div class="record-detail-toolbar">
  134. <button id="record-back">← Back</button>
  135. <button id="record-prev">‹ Prev</button>
  136. <button id="record-next">Next ›</button>
  137. <div class="meta" id="record-meta"></div>
  138. <span class="nav-info">Use <span class="kbd">←</span> <span class="kbd">→</span></span>
  139. <button class="danger" id="record-delete">Delete</button>
  140. </div>
  141. <div class="canvases">
  142. <div class="panel">
  143. <h3>Reference</h3>
  144. <canvas id="record-ref" width="500" height="500"></canvas>
  145. </div>
  146. <div class="panel">
  147. <h3>Your Drawing</h3>
  148. <canvas id="record-user" width="500" height="500"></canvas>
  149. </div>
  150. </div>
  151. <div class="score">
  152. <div class="score-overall"><span class="label">Overall</span><span id="record-overall"></span></div>
  153. <div class="score-detail" id="record-detail"></div>
  154. </div>
  155. </div>
  156. </div>
  157.  
  158. <script>
  159. (() => {
  160. const W = 500, H = 500, PAD = 40;
  161. const STORAGE_KEY = 'copy-practice-records-v1';
  162.  
  163. // ---------- geometry helpers ----------
  164. const rand = (a, b) => Math.random() * (b - a) + a;
  165. const randPoint = () => ({ x: rand(PAD, W - PAD), y: rand(PAD, H - PAD) });
  166. const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
  167. const lineLen = l => Math.hypot(l.x2 - l.x1, l.y2 - l.y1);
  168. const lineAngleDeg = l => Math.atan2(l.y2 - l.y1, l.x2 - l.x1) * 180 / Math.PI;
  169. function angleDiffUndirected(a, b) {
  170. let d = ((a - b) % 180 + 180) % 180;
  171. if (d > 90) d = 180 - d;
  172. return d;
  173. }
  174. const pctFromDist = (d, tol = 100) => Math.max(0, 100 * (1 - d / tol));
  175. const pctFromAngle = (deg, tol = 45) => Math.max(0, 100 * (1 - Math.abs(deg) / tol));
  176. const pctFromLen = (refL, userL) => Math.max(0, 100 * (1 - Math.abs(refL - userL) / Math.max(refL, 1)));
  177.  
  178. function bestEndpointMatch(ref, user) {
  179. const a = (dist({ x: ref.x1, y: ref.y1 }, { x: user.x1, y: user.y1 }) +
  180. dist({ x: ref.x2, y: ref.y2 }, { x: user.x2, y: user.y2 })) / 2;
  181. const b = (dist({ x: ref.x1, y: ref.y1 }, { x: user.x2, y: user.y2 }) +
  182. dist({ x: ref.x2, y: ref.y2 }, { x: user.x1, y: user.y1 })) / 2;
  183. return Math.min(a, b);
  184. }
  185.  
  186. // ---------- generation ----------
  187. function genDot() { return { type: 'dot', ...randPoint() }; }
  188. function genLine() {
  189. let p1 = randPoint(), p2 = randPoint();
  190. while (dist(p1, p2) < 80) p2 = randPoint();
  191. return { type: 'line', x1: p1.x, y1: p1.y, x2: p2.x, y2: p2.y };
  192. }
  193. function genPolygon(n, cx, cy, baseR) {
  194. n = Math.max(3, n);
  195. cx = cx ?? W / 2 + rand(-40, 40);
  196. cy = cy ?? H / 2 + rand(-40, 40);
  197. baseR = baseR ?? rand(110, 180);
  198. const angles = [];
  199. for (let i = 0; i < n; i++) angles.push(rand(0, 2 * Math.PI));
  200. angles.sort((a, b) => a - b);
  201. for (let i = 1; i < n; i++) {
  202. if (angles[i] - angles[i - 1] < 0.3) angles[i] = angles[i - 1] + 0.3;
  203. }
  204. const points = angles.map(a => ({
  205. x: cx + baseR * rand(0.7, 1.1) * Math.cos(a),
  206. y: cy + baseR * rand(0.7, 1.1) * Math.sin(a),
  207. }));
  208. return { type: 'polygon', points };
  209. }
  210. function generateShapes(mode, count) {
  211. const out = [];
  212. if (mode === 'dots') {
  213. for (let i = 0; i < count; i++) out.push(genDot());
  214. } else if (mode === 'lines') {
  215. for (let i = 0; i < count; i++) out.push(genLine());
  216. } else if (mode === 'polygon') {
  217. out.push(genPolygon(count));
  218. } else {
  219. const types = ['dot', 'line', 'polygon'];
  220. for (let i = 0; i < count; i++) {
  221. const t = types[Math.floor(Math.random() * types.length)];
  222. if (t === 'dot') out.push(genDot());
  223. else if (t === 'line') out.push(genLine());
  224. else {
  225. const cx = rand(PAD + 70, W - PAD - 70);
  226. const cy = rand(PAD + 70, H - PAD - 70);
  227. out.push(genPolygon(3 + Math.floor(Math.random() * 3), cx, cy, rand(50, 100)));
  228. }
  229. }
  230. }
  231. return out;
  232. }
  233.  
  234. // ---------- drawing ----------
  235. function drawShapes(ctx, shapes, opts = {}) {
  236. ctx.save();
  237. ctx.lineWidth = opts.lineWidth ?? 2;
  238. ctx.strokeStyle = opts.color ?? '#18181b';
  239. ctx.fillStyle = opts.color ?? '#18181b';
  240. for (const s of shapes) {
  241. if (s.type === 'dot') {
  242. ctx.beginPath();
  243. ctx.arc(s.x, s.y, 5, 0, Math.PI * 2);
  244. ctx.fill();
  245. } else if (s.type === 'line') {
  246. ctx.beginPath();
  247. ctx.moveTo(s.x1, s.y1); ctx.lineTo(s.x2, s.y2);
  248. ctx.stroke();
  249. ctx.beginPath(); ctx.arc(s.x1, s.y1, 3, 0, Math.PI * 2); ctx.fill();
  250. ctx.beginPath(); ctx.arc(s.x2, s.y2, 3, 0, Math.PI * 2); ctx.fill();
  251. } else if (s.type === 'polygon') {
  252. if (!s.points || s.points.length < 2) continue;
  253. ctx.beginPath();
  254. ctx.moveTo(s.points[0].x, s.points[0].y);
  255. for (let i = 1; i < s.points.length; i++) ctx.lineTo(s.points[i].x, s.points[i].y);
  256. ctx.closePath();
  257. ctx.stroke();
  258. for (const p of s.points) {
  259. ctx.beginPath(); ctx.arc(p.x, p.y, 3, 0, Math.PI * 2); ctx.fill();
  260. }
  261. }
  262. }
  263. ctx.restore();
  264. }
  265.  
  266. // ---------- scoring ----------
  267. function scoreDot(ref, user) {
  268. const d = dist(ref, user);
  269. return { distance: d, accuracy: pctFromDist(d) };
  270. }
  271. function scoreLine(ref, user) {
  272. const endpointDist = bestEndpointMatch(ref, user);
  273. const positionPct = pctFromDist(endpointDist);
  274. const angleDiff = angleDiffUndirected(lineAngleDeg(ref), lineAngleDeg(user));
  275. const anglePct = pctFromAngle(angleDiff, 45);
  276. const lenPct = pctFromLen(lineLen(ref), lineLen(user));
  277. const overall = (positionPct + anglePct + lenPct) / 3;
  278. return { positionPct, anglePct, lenPct, angleDiff, endpointDist, overall };
  279. }
  280. function scorePolygon(ref, user) {
  281. const refPts = ref.points;
  282. const userPts = user.points;
  283. let best = null;
  284. if (refPts.length === userPts.length) {
  285. const n = refPts.length;
  286. for (const dir of [1, -1]) {
  287. for (let off = 0; off < n; off++) {
  288. const reordered = [];
  289. for (let i = 0; i < n; i++) {
  290. const idx = dir === 1 ? (off + i) % n : (((off - i) % n) + n) % n;
  291. reordered.push(userPts[idx]);
  292. }
  293. let total = 0;
  294. for (let i = 0; i < n; i++) total += dist(refPts[i], reordered[i]);
  295. if (!best || total < best.total) best = { total, points: reordered };
  296. }
  297. }
  298. } else {
  299. best = { points: userPts.slice(0, refPts.length), total: 0 };
  300. }
  301. const n = Math.min(refPts.length, best.points.length);
  302. const vertices = [];
  303. for (let i = 0; i < n; i++) {
  304. const d = dist(refPts[i], best.points[i]);
  305. vertices.push({ ref: refPts[i], user: best.points[i], distance: d, accuracy: pctFromDist(d) });
  306. }
  307. const edges = [];
  308. for (let i = 0; i < n; i++) {
  309. const j = (i + 1) % n;
  310. const refE = { x1: refPts[i].x, y1: refPts[i].y, x2: refPts[j].x, y2: refPts[j].y };
  311. const userE = { x1: best.points[i].x, y1: best.points[i].y, x2: best.points[j].x, y2: best.points[j].y };
  312. const angleDiff = angleDiffUndirected(lineAngleDeg(refE), lineAngleDeg(userE));
  313. edges.push({ angleDiff, anglePct: pctFromAngle(angleDiff, 45), lenPct: pctFromLen(lineLen(refE), lineLen(userE)) });
  314. }
  315. const avg = arr => arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0;
  316. const vertexAvg = avg(vertices.map(v => v.accuracy));
  317. const angleAvg = avg(edges.map(e => e.anglePct));
  318. const lenAvg = avg(edges.map(e => e.lenPct));
  319. let overall = (vertexAvg + angleAvg + lenAvg) / 3;
  320. let countNote = null;
  321. if (refPts.length !== userPts.length) {
  322. const penalty = Math.abs(refPts.length - userPts.length) * 15;
  323. overall = Math.max(0, overall - penalty);
  324. countNote = `${userPts.length} of ${refPts.length} vertices (−${penalty}% penalty)`;
  325. }
  326. return { vertices, edges, vertexAvg, angleAvg, lenAvg, overall, countNote };
  327. }
  328.  
  329. function matchAndScore(refShapes, userShapes) {
  330. const refByType = { dot: [], line: [], polygon: [] };
  331. const userByType = { dot: [], line: [], polygon: [] };
  332. refShapes.forEach(s => refByType[s.type].push(s));
  333. userShapes.forEach(s => userByType[s.type].push(s));
  334.  
  335. const dots = [];
  336. const usedD = new Set();
  337. for (const r of refByType.dot) {
  338. let bi = -1, bd = Infinity;
  339. for (let i = 0; i < userByType.dot.length; i++) {
  340. if (usedD.has(i)) continue;
  341. const d = dist(r, userByType.dot[i]);
  342. if (d < bd) { bd = d; bi = i; }
  343. }
  344. if (bi >= 0) { usedD.add(bi); dots.push({ ref: r, user: userByType.dot[bi], ...scoreDot(r, userByType.dot[bi]) }); }
  345. else dots.push({ ref: r, user: null, accuracy: 0, distance: null });
  346. }
  347.  
  348. const lines = [];
  349. const usedL = new Set();
  350. for (const r of refByType.line) {
  351. let bi = -1, bd = Infinity;
  352. for (let i = 0; i < userByType.line.length; i++) {
  353. if (usedL.has(i)) continue;
  354. const d = bestEndpointMatch(r, userByType.line[i]);
  355. if (d < bd) { bd = d; bi = i; }
  356. }
  357. if (bi >= 0) { usedL.add(bi); lines.push({ ref: r, user: userByType.line[bi], ...scoreLine(r, userByType.line[bi]) }); }
  358. else lines.push({ ref: r, user: null, overall: 0, positionPct: 0, anglePct: 0, lenPct: 0, angleDiff: null });
  359. }
  360.  
  361. const polys = [];
  362. const usedP = new Set();
  363. for (const r of refByType.polygon) {
  364. let bi = -1, bs = -1;
  365. for (let i = 0; i < userByType.polygon.length; i++) {
  366. if (usedP.has(i)) continue;
  367. const sc = scorePolygon(r, userByType.polygon[i]);
  368. if (sc.overall > bs) { bs = sc.overall; bi = i; }
  369. }
  370. if (bi >= 0) { usedP.add(bi); polys.push({ ref: r, user: userByType.polygon[bi], ...scorePolygon(r, userByType.polygon[bi]) }); }
  371. else polys.push({ ref: r, user: null, overall: 0, vertexAvg: 0, angleAvg: 0, lenAvg: 0, edges: [] });
  372. }
  373.  
  374. const extras = (userByType.dot.length - usedD.size) +
  375. (userByType.line.length - usedL.size) +
  376. (userByType.polygon.length - usedP.size);
  377. return { dots, lines, polys, extras };
  378. }
  379.  
  380. function overallScore(r) {
  381. const arr = [...r.dots.map(d => d.accuracy), ...r.lines.map(l => l.overall), ...r.polys.map(p => p.overall)];
  382. return arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0;
  383. }
  384.  
  385. function pctClass(p) { return p >= 85 ? 'good' : p >= 60 ? 'ok' : 'bad'; }
  386. function fmtPct(p) { return `<span class="pct ${pctClass(p)}">${p.toFixed(1)}%</span>`; }
  387.  
  388. function buildScoreHTML(r) {
  389. let html = '<table><thead><tr><th>Shape</th><th>Position</th><th>Angle</th><th>Length</th><th>Score</th></tr></thead><tbody>';
  390. let n = 0;
  391. for (const d of r.dots) {
  392. n++;
  393. const pos = d.user ? `${fmtPct(d.accuracy)} <span style="color:#71717a">(${d.distance.toFixed(1)} px off)</span>` : '<span class="bad">missing</span>';
  394. html += `<tr><td>Dot ${n}</td><td>${pos}</td><td>—</td><td>—</td><td>${fmtPct(d.accuracy)}</td></tr>`;
  395. }
  396. for (const l of r.lines) {
  397. n++;
  398. if (!l.user) { html += `<tr><td>Line ${n}</td><td colspan="3"><span class="bad">missing</span></td><td>${fmtPct(0)}</td></tr>`; continue; }
  399. const angCell = `${fmtPct(l.anglePct)} <span style="color:#71717a">(${l.angleDiff.toFixed(1)}° off)</span>`;
  400. html += `<tr><td>Line ${n}</td><td>${fmtPct(l.positionPct)}</td><td>${angCell}</td><td>${fmtPct(l.lenPct)}</td><td>${fmtPct(l.overall)}</td></tr>`;
  401. }
  402. for (const p of r.polys) {
  403. n++;
  404. if (!p.user) { html += `<tr><td>Polygon ${n}</td><td colspan="3"><span class="bad">missing</span></td><td>${fmtPct(0)}</td></tr>`; continue; }
  405. const note = p.countNote ? ` <span style="color:#a16207">(${p.countNote})</span>` : '';
  406. html += `<tr><td>Polygon ${n}${note}</td><td>${fmtPct(p.vertexAvg)}</td><td>${fmtPct(p.angleAvg)}</td><td>${fmtPct(p.lenAvg)}</td><td>${fmtPct(p.overall)}</td></tr>`;
  407. for (let i = 0; i < p.edges.length; i++) {
  408. const e = p.edges[i];
  409. html += `<tr class="sub"><td>↳ edge ${i + 1}</td><td>—</td><td>${fmtPct(e.anglePct)} <span style="color:#a1a1aa">(${e.angleDiff.toFixed(1)}° off)</span></td><td>${fmtPct(e.lenPct)}</td><td>—</td></tr>`;
  410. }
  411. }
  412. if (r.extras > 0) {
  413. html += `<tr><td colspan="5" style="color:#a16207;font-size:12px;">${r.extras} extra shape${r.extras > 1 ? 's' : ''} you drew didn't match a reference (not counted).</td></tr>`;
  414. }
  415. html += '</tbody></table>';
  416. return html;
  417. }
  418.  
  419. function renderScoreInto(scoreEl, overallEl, detailEl, scoring) {
  420. overallEl.innerHTML = fmtPct(overallScore(scoring));
  421. detailEl.innerHTML = buildScoreHTML(scoring);
  422. scoreEl.hidden = false;
  423. }
  424.  
  425. // ============================================================
  426. // PRACTICE VIEW
  427. // ============================================================
  428. const refCanvas = document.getElementById('ref');
  429. const userCanvas = document.getElementById('user');
  430. const rctx = refCanvas.getContext('2d');
  431. const uctx = userCanvas.getContext('2d');
  432.  
  433. let referenceShapes = [];
  434. let userShapes = [];
  435. let currentTool = 'dot';
  436. let pendingLine = null;
  437. let pendingPoly = null;
  438. let showOverlay = false;
  439. let savedThisPuzzle = false;
  440.  
  441. function renderRef() {
  442. rctx.clearRect(0, 0, W, H);
  443. drawShapes(rctx, referenceShapes);
  444. }
  445. function renderUser() {
  446. uctx.clearRect(0, 0, W, H);
  447. if (showOverlay) drawShapes(uctx, referenceShapes, { color: '#cbd5e1', lineWidth: 1 });
  448. drawShapes(uctx, userShapes, { color: '#2563eb' });
  449. if (pendingLine) {
  450. uctx.fillStyle = '#2563eb';
  451. uctx.beginPath(); uctx.arc(pendingLine.x, pendingLine.y, 4, 0, Math.PI * 2); uctx.fill();
  452. }
  453. if (pendingPoly && pendingPoly.points.length > 0) {
  454. uctx.strokeStyle = '#2563eb';
  455. uctx.fillStyle = '#2563eb';
  456. uctx.lineWidth = 2;
  457. if (pendingPoly.points.length >= 2) {
  458. uctx.beginPath();
  459. uctx.moveTo(pendingPoly.points[0].x, pendingPoly.points[0].y);
  460. for (let i = 1; i < pendingPoly.points.length; i++) uctx.lineTo(pendingPoly.points[i].x, pendingPoly.points[i].y);
  461. uctx.stroke();
  462. }
  463. for (const p of pendingPoly.points) {
  464. uctx.beginPath(); uctx.arc(p.x, p.y, 3, 0, Math.PI * 2); uctx.fill();
  465. }
  466. }
  467. }
  468.  
  469. function getPos(e, canvas) {
  470. const r = canvas.getBoundingClientRect();
  471. const sx = canvas.width / r.width, sy = canvas.height / r.height;
  472. return { x: (e.clientX - r.left) * sx, y: (e.clientY - r.top) * sy };
  473. }
  474.  
  475. userCanvas.addEventListener('click', e => {
  476. const p = getPos(e, userCanvas);
  477. if (currentTool === 'dot') {
  478. userShapes.push({ type: 'dot', x: p.x, y: p.y });
  479. } else if (currentTool === 'line') {
  480. if (!pendingLine) pendingLine = p;
  481. else {
  482. userShapes.push({ type: 'line', x1: pendingLine.x, y1: pendingLine.y, x2: p.x, y2: p.y });
  483. pendingLine = null;
  484. }
  485. } else if (currentTool === 'polygon') {
  486. if (!pendingPoly) pendingPoly = { points: [] };
  487. pendingPoly.points.push(p);
  488. }
  489. renderUser();
  490. });
  491.  
  492. function setTool(tool) {
  493. currentTool = tool;
  494. pendingLine = null;
  495. document.querySelectorAll('#tool-row button[data-tool]').forEach(b => {
  496. b.classList.toggle('active', b.dataset.tool === tool);
  497. });
  498. updateHint();
  499. }
  500. function commitPolygon() {
  501. if (pendingPoly && pendingPoly.points.length >= 3) {
  502. userShapes.push({ type: 'polygon', points: pendingPoly.points });
  503. }
  504. pendingPoly = null;
  505. }
  506. function updateHint() {
  507. const hints = {
  508. dot: 'Click to place a dot.',
  509. line: 'Click for line start, click again for line end.',
  510. polygon: 'Click to add vertices. Click "Finish Polygon" when done (min 3).',
  511. };
  512. document.getElementById('hint').textContent = hints[currentTool];
  513. }
  514.  
  515. document.getElementById('tool-row').addEventListener('click', e => {
  516. const tool = e.target.dataset.tool;
  517. const action = e.target.dataset.action;
  518. if (tool) { commitPolygon(); setTool(tool); renderUser(); }
  519. else if (action === 'finishPoly') { commitPolygon(); renderUser(); }
  520. else if (action === 'undo') {
  521. if (pendingPoly && pendingPoly.points.length > 0) {
  522. pendingPoly.points.pop();
  523. if (pendingPoly.points.length === 0) pendingPoly = null;
  524. } else if (pendingLine) pendingLine = null;
  525. else if (userShapes.length > 0) userShapes.pop();
  526. renderUser();
  527. }
  528. });
  529.  
  530. function newPuzzle() {
  531. const mode = document.getElementById('mode').value;
  532. const count = Math.max(1, parseInt(document.getElementById('count').value) || 1);
  533. referenceShapes = generateShapes(mode, count);
  534. userShapes = [];
  535. pendingLine = null;
  536. pendingPoly = null;
  537. showOverlay = false;
  538. savedThisPuzzle = false;
  539. document.getElementById('reveal').disabled = true;
  540. document.getElementById('score').hidden = true;
  541. renderRef();
  542. renderUser();
  543. }
  544.  
  545. const revealBtn = document.getElementById('reveal');
  546.  
  547. document.getElementById('generate').addEventListener('click', newPuzzle);
  548. document.getElementById('check').addEventListener('click', () => {
  549. commitPolygon();
  550. showOverlay = true;
  551. revealBtn.disabled = false;
  552. renderUser();
  553. const scoring = matchAndScore(referenceShapes, userShapes);
  554. renderScoreInto(document.getElementById('score'), document.getElementById('overall'), document.getElementById('detail'), scoring);
  555. if (!savedThisPuzzle) {
  556. saveRecord({
  557. id: Date.now() + '-' + Math.random().toString(36).slice(2, 8),
  558. ts: Date.now(),
  559. mode: document.getElementById('mode').value,
  560. count: parseInt(document.getElementById('count').value) || 1,
  561. reference: referenceShapes,
  562. user: userShapes,
  563. overall: overallScore(scoring),
  564. });
  565. savedThisPuzzle = true;
  566. refreshRecordsCount();
  567. }
  568. });
  569. document.getElementById('clear').addEventListener('click', () => {
  570. userShapes = [];
  571. pendingLine = null;
  572. pendingPoly = null;
  573. showOverlay = false;
  574. revealBtn.disabled = true;
  575. document.getElementById('score').hidden = true;
  576. renderUser();
  577. });
  578. revealBtn.addEventListener('click', () => { showOverlay = !showOverlay; renderUser(); });
  579. document.getElementById('mode').addEventListener('change', e => {
  580. const map = { dots: 'dot', lines: 'line', polygon: 'polygon', mixed: 'dot' };
  581. setTool(map[e.target.value]);
  582. });
  583.  
  584. // ============================================================
  585. // RECORDS STORAGE
  586. // ============================================================
  587. function loadRecords() {
  588. try {
  589. const raw = localStorage.getItem(STORAGE_KEY);
  590. if (!raw) return [];
  591. const arr = JSON.parse(raw);
  592. return Array.isArray(arr) ? arr : [];
  593. } catch { return []; }
  594. }
  595. function persistRecords(records) {
  596. localStorage.setItem(STORAGE_KEY, JSON.stringify(records));
  597. }
  598. function saveRecord(record) {
  599. const records = loadRecords();
  600. records.push(record);
  601. persistRecords(records);
  602. }
  603. function deleteRecord(id) {
  604. const records = loadRecords().filter(r => r.id !== id);
  605. persistRecords(records);
  606. }
  607. function refreshRecordsCount() {
  608. const n = loadRecords().length;
  609. document.getElementById('tab-records-count').textContent = n ? `(${n})` : '';
  610. }
  611.  
  612. // ============================================================
  613. // RECORDS VIEW
  614. // ============================================================
  615. const recordRefCanvas = document.getElementById('record-ref');
  616. const recordUserCanvas = document.getElementById('record-user');
  617. const rrctx = recordRefCanvas.getContext('2d');
  618. const ructx = recordUserCanvas.getContext('2d');
  619.  
  620. let viewingRecordIndex = -1;
  621. let cachedSorted = []; // newest first
  622.  
  623. function getSortedRecords() {
  624. return loadRecords().slice().sort((a, b) => b.ts - a.ts);
  625. }
  626.  
  627. function modeLabel(mode, count) {
  628. const m = { dots: 'Dots', lines: 'Lines', polygon: 'Polygon', mixed: 'Mixed' }[mode] || mode;
  629. return `${m} (${count})`;
  630. }
  631. function fmtDate(ts) {
  632. const d = new Date(ts);
  633. return d.toLocaleString();
  634. }
  635.  
  636. function renderRecordsList() {
  637. cachedSorted = getSortedRecords();
  638. const container = document.getElementById('records-list-container');
  639. document.getElementById('records-count').textContent = `${cachedSorted.length} record${cachedSorted.length === 1 ? '' : 's'}`;
  640. if (cachedSorted.length === 0) {
  641. container.innerHTML = '<div class="records-empty">No records yet. Complete a puzzle and click "Check Accuracy" to record it.</div>';
  642. return;
  643. }
  644. let html = '<div class="records-list"><table><thead><tr><th>#</th><th>Date</th><th>Mode</th><th>Score</th><th></th></tr></thead><tbody>';
  645. cachedSorted.forEach((r, i) => {
  646. html += `<tr data-id="${r.id}"><td>${i + 1}</td><td>${fmtDate(r.ts)}</td><td>${modeLabel(r.mode, r.count)}</td><td>${fmtPct(r.overall)}</td><td class="actions"><button class="danger" data-delete="${r.id}">Delete</button></td></tr>`;
  647. });
  648. html += '</tbody></table></div>';
  649. container.innerHTML = html;
  650. }
  651.  
  652. function showList() {
  653. document.getElementById('records-list-mode').hidden = false;
  654. document.getElementById('records-detail-mode').hidden = true;
  655. viewingRecordIndex = -1;
  656. renderRecordsList();
  657. }
  658.  
  659. function showDetail(index) {
  660. cachedSorted = getSortedRecords();
  661. if (cachedSorted.length === 0) { showList(); return; }
  662. viewingRecordIndex = Math.max(0, Math.min(index, cachedSorted.length - 1));
  663. document.getElementById('records-list-mode').hidden = true;
  664. document.getElementById('records-detail-mode').hidden = false;
  665. renderDetail();
  666. }
  667.  
  668. function renderDetail() {
  669. const r = cachedSorted[viewingRecordIndex];
  670. if (!r) { showList(); return; }
  671. rrctx.clearRect(0, 0, W, H);
  672. ructx.clearRect(0, 0, W, H);
  673. drawShapes(rrctx, r.reference || []);
  674. drawShapes(ructx, r.reference || [], { color: '#cbd5e1', lineWidth: 1 });
  675. drawShapes(ructx, r.user || [], { color: '#2563eb' });
  676.  
  677. document.getElementById('record-meta').innerHTML =
  678. `<b>${fmtDate(r.ts)}</b> · ${modeLabel(r.mode, r.count)} · Score ${fmtPct(r.overall)}` +
  679. ` <span style="color:#71717a">(${viewingRecordIndex + 1} of ${cachedSorted.length})</span>`;
  680.  
  681. const scoring = matchAndScore(r.reference || [], r.user || []);
  682. renderScoreInto(
  683. document.querySelector('#view-records .score'),
  684. document.getElementById('record-overall'),
  685. document.getElementById('record-detail'),
  686. scoring
  687. );
  688. document.getElementById('record-prev').disabled = viewingRecordIndex <= 0;
  689. document.getElementById('record-next').disabled = viewingRecordIndex >= cachedSorted.length - 1;
  690. }
  691.  
  692. document.getElementById('records-list-container').addEventListener('click', e => {
  693. const delId = e.target.dataset.delete;
  694. if (delId) {
  695. e.stopPropagation();
  696. deleteRecord(delId);
  697. refreshRecordsCount();
  698. renderRecordsList();
  699. return;
  700. }
  701. const row = e.target.closest('tr[data-id]');
  702. if (row) {
  703. const id = row.dataset.id;
  704. const idx = cachedSorted.findIndex(r => r.id === id);
  705. if (idx >= 0) showDetail(idx);
  706. }
  707. });
  708.  
  709. document.getElementById('record-back').addEventListener('click', showList);
  710. document.getElementById('record-prev').addEventListener('click', () => { if (viewingRecordIndex > 0) showDetail(viewingRecordIndex - 1); });
  711. document.getElementById('record-next').addEventListener('click', () => { if (viewingRecordIndex < cachedSorted.length - 1) showDetail(viewingRecordIndex + 1); });
  712. document.getElementById('record-delete').addEventListener('click', () => {
  713. const r = cachedSorted[viewingRecordIndex];
  714. if (!r) return;
  715. deleteRecord(r.id);
  716. refreshRecordsCount();
  717. cachedSorted = getSortedRecords();
  718. if (cachedSorted.length === 0) showList();
  719. else showDetail(Math.min(viewingRecordIndex, cachedSorted.length - 1));
  720. });
  721.  
  722. // keyboard nav (only when in records detail view)
  723. document.addEventListener('keydown', e => {
  724. if (document.getElementById('view-records').hidden) return;
  725. if (document.getElementById('records-detail-mode').hidden) return;
  726. if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
  727. if (e.key === 'ArrowLeft') {
  728. if (viewingRecordIndex > 0) { showDetail(viewingRecordIndex - 1); e.preventDefault(); }
  729. } else if (e.key === 'ArrowRight') {
  730. if (viewingRecordIndex < cachedSorted.length - 1) { showDetail(viewingRecordIndex + 1); e.preventDefault(); }
  731. } else if (e.key === 'Escape') {
  732. showList();
  733. }
  734. });
  735.  
  736. // export / import / clear all
  737. document.getElementById('export-records').addEventListener('click', () => {
  738. const records = loadRecords();
  739. if (records.length === 0) { alert('No records to export.'); return; }
  740. const blob = new Blob([JSON.stringify({ version: 1, records }, null, 2)], { type: 'application/json' });
  741. const url = URL.createObjectURL(blob);
  742. const a = document.createElement('a');
  743. const ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
  744. a.href = url;
  745. a.download = `copy-practice-records-${ts}.json`;
  746. document.body.appendChild(a);
  747. a.click();
  748. document.body.removeChild(a);
  749. URL.revokeObjectURL(url);
  750. });
  751.  
  752. const importInput = document.getElementById('import-file');
  753. document.getElementById('import-records').addEventListener('click', () => importInput.click());
  754. importInput.addEventListener('change', () => {
  755. const file = importInput.files[0];
  756. if (!file) return;
  757. const reader = new FileReader();
  758. reader.onload = () => {
  759. try {
  760. const data = JSON.parse(reader.result);
  761. const incoming = Array.isArray(data) ? data : (data.records || []);
  762. if (!Array.isArray(incoming)) throw new Error('invalid file');
  763. const existing = loadRecords();
  764. const existingIds = new Set(existing.map(r => r.id));
  765. let added = 0;
  766. for (const r of incoming) {
  767. if (r && r.id && r.reference && r.user && !existingIds.has(r.id)) {
  768. existing.push(r);
  769. existingIds.add(r.id);
  770. added++;
  771. }
  772. }
  773. persistRecords(existing);
  774. refreshRecordsCount();
  775. renderRecordsList();
  776. alert(`Imported ${added} record${added === 1 ? '' : 's'}. ${incoming.length - added} skipped (duplicates or invalid).`);
  777. } catch (err) {
  778. alert('Import failed: ' + err.message);
  779. } finally {
  780. importInput.value = '';
  781. }
  782. };
  783. reader.readAsText(file);
  784. });
  785.  
  786. document.getElementById('clear-all-records').addEventListener('click', () => {
  787. if (loadRecords().length === 0) return;
  788. if (!confirm('Delete ALL records? This cannot be undone.')) return;
  789. persistRecords([]);
  790. refreshRecordsCount();
  791. renderRecordsList();
  792. });
  793.  
  794. // ============================================================
  795. // TABS
  796. // ============================================================
  797. document.querySelectorAll('.tab').forEach(tab => {
  798. tab.addEventListener('click', () => {
  799. const target = tab.dataset.tab;
  800. document.querySelectorAll('.tab').forEach(t => t.classList.toggle('active', t === tab));
  801. document.getElementById('view-practice').hidden = target !== 'practice';
  802. document.getElementById('view-records').hidden = target !== 'records';
  803. if (target === 'records') showList();
  804. });
  805. });
  806.  
  807. // ---------- init ----------
  808. updateHint();
  809. newPuzzle();
  810. refreshRecordsCount();
  811. })();
  812. </script>
  813. </body>
  814. </html>
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment