krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

DayByDay/Quiz/Trace.swift

122 lines · 5339 bytes

7 symbols in this file
  1//
  2//  Trace.swift
  3//  DayByDay
  4//
  5
  6import CoreGraphics
  7import CoreText
  8import UIKit
  9
 10/// The area a child traces over, in a `size`×`size` canvas: a letter's filled
 11/// shape, or a shape's thick outline.
 12nonisolated enum TraceGuide {
 13    static func region(for item: QuizItem, size: CGFloat) -> CGPath {
 14        if let letter = item.value(LearnLetter.self) {
 15            return fitted(glyph(letter.character), size: size)
 16        }
 17        let outline = fitted(shapeOutline(item.value(LearnShape.self)!), size: size)
 18        // normalized() removes the stroke's self-overlaps at corners.
 19        return outline.copy(strokingWithWidth: size * 0.12, lineCap: .round, lineJoin: .round, miterLimit: 10)
 20            .normalized()
 21    }
 22
 23    /// Scales and centers `path` into the middle 80% of the canvas.
 24    private static func fitted(_ path: CGPath, size: CGFloat) -> CGPath {
 25        let box = path.boundingBoxOfPath
 26        let scale = size * 0.8 / max(box.width, box.height)
 27        var t = CGAffineTransform(translationX: size / 2, y: size / 2)
 28            .scaledBy(x: scale, y: scale)
 29            .translatedBy(x: -box.midX, y: -box.midY)
 30        return path.copy(using: &t) ?? path
 31    }
 32
 33    /// The uppercase letter in the system rounded heavy font, y pointing down.
 34    private static func glyph(_ character: String) -> CGPath {
 35        let base = UIFont.systemFont(ofSize: 200, weight: .heavy)
 36        let descriptor = base.fontDescriptor.withDesign(.rounded) ?? base.fontDescriptor
 37        let font = CTFontCreateWithFontDescriptor(descriptor as CTFontDescriptor, 200, nil)
 38        var chars = Array(character.utf16)
 39        var glyphs = [CGGlyph](repeating: 0, count: chars.count)
 40        CTFontGetGlyphsForCharacters(font, &chars, &glyphs, chars.count)
 41        var flip = CGAffineTransform(scaleX: 1, y: -1)
 42        return CTFontCreatePathForGlyph(font, glyphs[0], &flip) ?? CGPath(rect: .zero, transform: nil)
 43    }
 44
 45    /// Outlines in a unit square, y pointing down.
 46    private static func shapeOutline(_ shape: LearnShape) -> CGPath {
 47        let p = CGMutablePath()
 48        switch shape {
 49        case .circle:
 50            p.addEllipse(in: CGRect(x: 0, y: 0, width: 1, height: 1))
 51        case .square:
 52            p.addRect(CGRect(x: 0, y: 0, width: 1, height: 1))
 53        case .triangle:
 54            p.addLines(between: [CGPoint(x: 0.5, y: 0), CGPoint(x: 1, y: 0.9), CGPoint(x: 0, y: 0.9)])
 55            p.closeSubpath()
 56        case .star:
 57            let points = (0..<10).map { i -> CGPoint in
 58                let r = i.isMultiple(of: 2) ? 0.5 : 0.22
 59                let a = -Double.pi / 2 + Double(i) * .pi / 5
 60                return CGPoint(x: 0.5 + r * cos(a), y: 0.5 + r * sin(a))
 61            }
 62            p.addLines(between: points)
 63            p.closeSubpath()
 64        case .heart:
 65            p.move(to: CGPoint(x: 0.5, y: 0.95))
 66            p.addCurve(to: CGPoint(x: 0, y: 0.3), control1: CGPoint(x: 0.2, y: 0.75), control2: CGPoint(x: 0, y: 0.55))
 67            p.addCurve(to: CGPoint(x: 0.5, y: 0.2), control1: CGPoint(x: 0, y: 0), control2: CGPoint(x: 0.4, y: -0.05))
 68            p.addCurve(to: CGPoint(x: 1, y: 0.3), control1: CGPoint(x: 0.6, y: -0.05), control2: CGPoint(x: 1, y: 0))
 69            p.addCurve(to: CGPoint(x: 0.5, y: 0.95), control1: CGPoint(x: 1, y: 0.55), control2: CGPoint(x: 0.8, y: 0.75))
 70            p.closeSubpath()
 71        case .oval:
 72            p.addEllipse(in: CGRect(x: 0, y: 0, width: 1, height: 0.65))
 73        case .diamond:
 74            p.addLines(between: [CGPoint(x: 0.5, y: 0), CGPoint(x: 1, y: 0.5), CGPoint(x: 0.5, y: 1), CGPoint(x: 0, y: 0.5)])
 75            p.closeSubpath()
 76        case .rectangle:
 77            p.addRect(CGRect(x: 0, y: 0, width: 1, height: 0.6))
 78        }
 79        return p
 80    }
 81}
 82
 83/// Scores a finger trace against a guide region.
 84nonisolated struct TraceChecker {
 85    /// Points inside the region, on a grid.
 86    let samples: [CGPoint]
 87    private let region: CGPath
 88    private let tolerance: CGFloat
 89
 90    init(region: CGPath, size: CGFloat) {
 91        self.region = region
 92        tolerance = size * 0.07
 93        let step = size / 30
 94        var samples: [CGPoint] = []
 95        for row in 0...30 {
 96            for col in 0...30 {
 97                let point = CGPoint(x: CGFloat(col) * step, y: CGFloat(row) * step)
 98                if region.contains(point) { samples.append(point) }
 99            }
100        }
101        self.samples = samples
102    }
103
104    /// Coverage: share of the region the finger passed near. Accuracy: share
105    /// of the finger's points on or near the region.
106    func score(_ drawn: [CGPoint]) -> (coverage: Double, accuracy: Double) {
107        guard !drawn.isEmpty, !samples.isEmpty else { return (0, 0) }
108        let t2 = tolerance * tolerance
109        func near(_ a: CGPoint, _ b: CGPoint) -> Bool {
110            let dx = a.x - b.x, dy = a.y - b.y
111            return dx * dx + dy * dy <= t2
112        }
113        let covered = samples.filter { s in drawn.contains { near($0, s) } }.count
114        let onTarget = drawn.filter { d in region.contains(d) || samples.contains { near($0, d) } }.count
115        return (Double(covered) / Double(samples.count), Double(onTarget) / Double(drawn.count))
116    }
117
118    func passes(_ drawn: [CGPoint]) -> Bool {
119        let s = score(drawn)
120        return s.coverage >= 0.75 && s.accuracy >= 0.75
121    }
122}