Richard,
I wrote a melodic dictation script for an ear training exerercise. I
took your advice to use solfege instead of the fixed note name system.
I tried to add this to the menu but I could not make a directory by
right clicking in the menu. I want it to go into
actions/menus/MainMenu/Educational/AuralTraining/Dictation/. I forgot
what the process was for doing this. I remember if I try to do this in
a text editor it breaks things. I have a rhythmic dictation script I
am working on now. It will also go in this directory.

Best,
Jeremiah
;; ═══════════════════════════════════════════════════════════════════════════
;; Melodic Dictation — levels, keys and movable-do solfege
;; ═══════════════════════════════════════════════════════════════════════════

;; ── Course tables (edit these to change the course) ───────────────────────
;; Buttons are labelled with movable-do solfege and stand for scale DEGREES
;; (0 = Do ... 7 = high Do), not for fixed note names. The key decides which
;; real pitches the degrees sound, so no button is ever labelled fis/cis.
(define MelodicDictation::Solfege
  '("Do" "Re" "Mi" "Fa" "Sol" "La" "Ti" "Do'"))

;; Each level lists the scale degrees that may appear in its melodies.
(define MelodicDictation::Levels
  '(("Level 1" . (2 4))                  ; Mi Sol
    ("Level 2" . (2 4 5))                ; Mi Sol La
    ("Level 3" . (0 2 4 5))              ; Do Mi Sol La
    ("Level 4" . (0 1 2 4 5))            ; Do Re Mi Sol La
    ("Level 5" . (0 1 2 4 5 7))          ; Do Re Mi Sol La Do'
    ("Level 6" . (0 1 2 3 4 5 7))        ; Do Re Mi Fa Sol La Do'
    ("Level 7" . (0 1 2 3 4 5 6 7))))    ; the full major scale

;; Each key lists its 8 major-scale notes (low Do to high Do) as LilyPond
;; names. Flats are spelled ees/aes/bes/des so lilyname->midikey reads them.
(define MelodicDictation::Keys
  '(("C"  . "c' d' e' f' g' a' b' c''")
    ("G"  . "g' a' b' c'' d'' e'' fis'' g''")
    ("D"  . "d' e' fis' g' a' b' cis'' d''")
    ("A"  . "a' b' cis'' d'' e'' fis'' gis'' a''")
    ("F"  . "f' g' a' bes' c'' d'' e'' f''")
    ("Bb" . "bes' c'' d'' ees'' f'' g'' a'' bes''")
    ("Eb" . "ees' f' g' aes' bes' c'' d'' ees''")))

;; How many correctly answered melodies move the player up a level.
;; (Counts melodies right at the current level, not "in a row".)
(define MelodicDictation::AdvanceAfter 10)

;; ── State ──────────────────────────────────────────────────────────────────
(define MelodicDictation::LevelNum 0)         ; index into Levels
(define MelodicDictation::KeyNum 0)           ; index into Keys
(define MelodicDictation::LevelCorrect 0)     ; melodies right at this level
(define MelodicDictation::scalenotes '())     ; the 8 LilyPond names of the key
(define MelodicDictation::activedegrees '())  ; degrees used by this level
(define MelodicDictation::notelist '())       ; LilyPond names used by this level
(define MelodicDictation::ArpTimer 0)
(define MelodicDictation::score 0)
(define MelodicDictation::CurrentNote "")
(define MelodicDictation::CurrentNoteNum 0)

;; Round state
(define MelodicDictation::SequenceLength 0)   ; how many notes in this round
(define MelodicDictation::SequenceNums  '())  ; scale degrees of the melody
(define MelodicDictation::SequenceNotes '())  ; corresponding lily names
(define MelodicDictation::InputBuffer   '())  ; degrees the user has entered so far
(define MelodicDictation::Accepting #f)       ; #t while a round awaits answers
(define MelodicDictation::DrawnCount 0)       ; notes currently drawn on the staff
(define MelodicDictation::Generation 0)       ; bumped on restart so stale timers do nothing

(let ((time (gettimeofday)))
  (set! *random-state*
    (seed->random-state (+ (car time) (cdr time)))))

(define (MelodicDictation::gotoEnd)
  (d-CursorRight)
  (if (d-NextObject)
    (MelodicDictation::gotoEnd)
    (d-CursorRight)))

;; Mirror of gotoEnd: walk back to the very first note-entry position
;; on the current staff.
(define (MelodicDictation::gotoStart)
  (d-MoveCursorLeft)
  (d-CursorLeft)
  (if (d-PrevObject)
    (MelodicDictation::gotoStart)
    (d-CursorRight)))

(define (MelodicDictation::lilyname->midikey lilyname)
  (let ((naturual_notenum '(0 2 4 5 7 9 11))
        (accidental 0)
        (octave 48)
        (notename 0)
        (notenum 0)
        (loop 0))
    (set! notename
      (lambda (char)
        (modulo (- (char->integer char) 99) 7)))
    (set! loop
      (lambda (x)
        (if (< x (string-length lilyname))
          (begin
            (if (= x 0) (set! notename (notename (string-ref lilyname x))))
            (if (> x 0)
              (begin
                (if (equal? #\i (string-ref lilyname x))
                  (set! accidental (+ accidental 1)))
                (if (equal? #\e (string-ref lilyname x))
                  (set! accidental (- accidental 1)))
                (if (equal? #\' (string-ref lilyname x))
                  (set! octave (+ octave 12)))
                (if (equal? #\, (string-ref lilyname x))
                  (set! octave (- octave 12)))))
            (loop (+ 1 x))))))
    (loop 0)
    (set! notenum (list-ref naturual_notenum notename))
    (+ (+ octave notenum) accidental)))

;; ── Level / key setup ─────────────────────────────────────────────────────
(define (MelodicDictation::ButtonTag degree)
  (string-append "MelodicDictation::Degree" (number->string degree)))

;; Blue = available at this level, gray = not used yet. Gray buttons stay on
;; screen (so the layout never jumps) but clicks on them are ignored.
(define (MelodicDictation::RefreshButtons)
  (let loop ((degree 0))
    (if (< degree 8)
      (begin
        (d-DirectivePut-score-display (MelodicDictation::ButtonTag degree)
          (string-append " <span font_desc=\"22\" foreground=\""
            (if (memv degree MelodicDictation::activedegrees) "blue" "gray")
            "\">" (list-ref MelodicDictation::Solfege degree) "</span>"))
        (loop (+ degree 1))))))

(define (MelodicDictation::ShowLevel)
  (d-DirectivePut-score-display "MelodicDictation::Level"
    (string-append "<b>"
      (car (list-ref MelodicDictation::Levels MelodicDictation::LevelNum))
      "</b> ("
      (number->string MelodicDictation::LevelCorrect) "/"
      (number->string MelodicDictation::AdvanceAfter) ")"))
  (d-DirectivePut-score-display "MelodicDictation::Key"
    (string-append "<b>Key: </b>"
      (car (list-ref MelodicDictation::Keys MelodicDictation::KeyNum)))))

;; Rebuild everything that depends on the current level and key.
(define (MelodicDictation::SetupLevel)
  (let ((degrees (cdr (list-ref MelodicDictation::Levels MelodicDictation::LevelNum)))
        (keynotes (cdr (list-ref MelodicDictation::Keys MelodicDictation::KeyNum))))
    (set! MelodicDictation::scalenotes (string-split keynotes #\space))
    (set! MelodicDictation::activedegrees degrees)
    (set! MelodicDictation::notelist
      (map (lambda (d) (list-ref MelodicDictation::scalenotes d)) degrees))
    (MelodicDictation::RefreshButtons)
    (MelodicDictation::ShowLevel)))

(define (MelodicDictation::ShouldLevelUp)
  (and (>= MelodicDictation::LevelCorrect MelodicDictation::AdvanceAfter)
       (< MelodicDictation::LevelNum (- (length MelodicDictation::Levels) 1))))

;; ── Score display ──────────────────────────────────────────────────────────
(define (MelodicDictation::showscore)
  (d-DirectivePut-score-display "MelodicDictation::GameScore"
    (string-append "<b>Score: </b>" (number->string MelodicDictation::score))))

(define (MelodicDictation::Flash extra)
  (d-DirectivePut-score-display "MelodicDictation::Feedback"
    (string-append "<span font_desc=\"72\" foreground=\"yellow\">👍</span>" extra)))

(define (MelodicDictation::ClearFlash)
  (d-DirectivePut-score-display "MelodicDictation::Feedback"
    "<span font_desc=\"24\"></span>"))

;; ── Playback helpers ───────────────────────────────────────────────────────
(define (MelodicDictation::PlayScaleNote note)
  (let ((newnote (number->string (MelodicDictation::lilyname->midikey note))))
    (d-OneShotTimer MelodicDictation::ArpTimer
      (string-append "(PlayNote \"" newnote "\" 1000)"))
    (set! MelodicDictation::ArpTimer (+ MelodicDictation::ArpTimer 1000))))

(define (MelodicDictation::PlayScaleNoteNow note)
  (let ((newnote (number->string (MelodicDictation::lilyname->midikey note))))
    (d-OneShotTimer 0
      (string-append "(PlayNote \"" newnote "\" 1000)"))))

(define (MelodicDictation::PlayScale)
  (set! MelodicDictation::ArpTimer 0)
  (map MelodicDictation::PlayScaleNote MelodicDictation::notelist))

;; Play the current sequence (used by Play Melody)
(define (MelodicDictation::PlaySequence)
  (set! MelodicDictation::ArpTimer 0)
  (map MelodicDictation::PlayScaleNote MelodicDictation::SequenceNotes))

;; ── Note drawing and erasing ───────────────────────────────────────────────
(define (MelodicDictation::DrawNote note)
  (d-CursorToNote note)
  (d-Insert2)
  (d-ChangeChordNotes note)
  (set! MelodicDictation::DrawnCount (+ MelodicDictation::DrawnCount 1)))

;; Delete exactly the notes this script has drawn, nothing else.
(define (MelodicDictation::EraseDrawn)
  (if (> MelodicDictation::DrawnCount 0)
    (begin
      (MelodicDictation::gotoEnd)
      (let loop ((n MelodicDictation::DrawnCount))
        (if (> n 0)
          (begin
            (d-DeletePreviousObject)
            (loop (- n 1)))))
      (MelodicDictation::gotoStart)
      (d-DeleteEmptyMeasures)
      (set! MelodicDictation::DrawnCount 0))))

(define (MelodicDictation::PlaceAnswerStatus gfx)
  (d-DirectivePut-note-minpixels "MelodicDictation::tick" 30)
  (d-DirectivePut-note-gx "MelodicDictation::tick" -10)
  (d-DirectivePut-note-gy "MelodicDictation::tick" 40)
  (d-DirectivePut-note-graphic "MelodicDictation::tick" gfx))

;; ── Status label (shows how many notes entered vs expected) ───────────────
(define (MelodicDictation::UpdatePrompt)
  (let ((entered (length MelodicDictation::InputBuffer))
        (total   MelodicDictation::SequenceLength))
    (d-DirectivePut-score-display "MelodicDictation::Prompt"
      (string-append "<b>Enter note </b>"
        (number->string (+ entered 1))
        "<b> of </b>"
        (number->string total)))))

;; ── Build a new random sequence of 3–6 notes from this level's degrees ────
(define (MelodicDictation::NewSequence)
  (set! MelodicDictation::SequenceLength (+ 3 (random 4)))  ; 3..6
  (set! MelodicDictation::SequenceNums
    (let loop ((n MelodicDictation::SequenceLength) (acc '()))
      (if (= n 0)
        acc
        (loop (- n 1)
              (cons (list-ref MelodicDictation::activedegrees
                              (random (length MelodicDictation::activedegrees)))
                    acc)))))
  (set! MelodicDictation::SequenceNotes
    (map (lambda (d) (list-ref MelodicDictation::scalenotes d))
         MelodicDictation::SequenceNums))
  (set! MelodicDictation::InputBuffer '())
  (set! MelodicDictation::Accepting #t))

;; Timer callbacks carry the generation they were scheduled in, so a timer
;; left over from before a level/key change or restart quietly does nothing.
(define (MelodicDictation::ScheduleNext delay)
  (d-OneShotTimer delay
    (string-append "(MelodicDictation::OfferChord "
                   (number->string MelodicDictation::Generation) ")")))

;; ── Offer a new round ─────────────────────────────────────────────────────
(define (MelodicDictation::OfferChord gen)
  (if (= gen MelodicDictation::Generation)
    (begin
      (MelodicDictation::showscore)
      (MelodicDictation::ClearFlash)
      ;; Erase the melody that was just shown (right or wrong answer) so
      ;; the one dedicated staff goes back to blank before the next round.
      (MelodicDictation::EraseDrawn)
      (MelodicDictation::gotoStart)
      (MelodicDictation::NewSequence)
      (set! MelodicDictation::ArpTimer 0)
      (MelodicDictation::PlaySequence)
      (d-OneShotTimer
        (* MelodicDictation::SequenceLength 1100)
        "(MelodicDictation::UpdatePrompt)"))))

;; ── Initial start (wait for user to play scale, then sequence) ────────────
(define (MelodicDictation::Go)
  (set! MelodicDictation::Generation (+ MelodicDictation::Generation 1))
  (MelodicDictation::showscore)
  (MelodicDictation::EraseDrawn)
  (MelodicDictation::gotoStart)
  (MelodicDictation::NewSequence)
  ; schedule sequence playback after scale finishes
  (set! MelodicDictation::ArpTimer
    (+ MelodicDictation::ArpTimer 1000))
  (d-OneShotTimer
    (* (+ (length MelodicDictation::notelist)
          MelodicDictation::SequenceLength) 1100)
    "(MelodicDictation::UpdatePrompt)"))

;; ── Level and key selectors (each click moves to the next one) ────────────
;; Changing either one wipes this round's notes and returns to "Click to
;; start", so the next melody is built from the new level/key.
(define (MelodicDictation::ResetRound)
  (set! MelodicDictation::Generation (+ MelodicDictation::Generation 1))
  (set! MelodicDictation::Accepting #f)
  (MelodicDictation::EraseDrawn)
  (MelodicDictation::SetupLevel)
  (MelodicDictation::ClearFlash)
  (d-DirectivePut-score-display "MelodicDictation::Prompt"
    "<span font_desc=\"18\"></span>")
  (d-DirectivePut-score-display "MelodicDictation::GameScore"
    "<span font_desc=\"22\">Click to start</span>"))

(define (MelodicDictation::CycleLevel)
  (set! MelodicDictation::LevelNum
    (modulo (+ MelodicDictation::LevelNum 1) (length MelodicDictation::Levels)))
  (set! MelodicDictation::LevelCorrect 0)
  (MelodicDictation::ResetRound))

(define (MelodicDictation::CycleKey)
  (set! MelodicDictation::KeyNum
    (modulo (+ MelodicDictation::KeyNum 1) (length MelodicDictation::Keys)))
  (MelodicDictation::ResetRound))

;; ── Called when user clicks a note button ─────────────────────────────────
;; The argument is the button's scale degree, as a string.
(define (MelodicDictation::notechosen DegreeString)
  (let ((chosen (string->number DegreeString)))
    ;; Ignore clicks on gray (unused) buttons and clicks between rounds.
    (if (and MelodicDictation::Accepting
             (memv chosen MelodicDictation::activedegrees))
      (MelodicDictation::judge chosen))))

(define (MelodicDictation::judge chosen)
  (let* ((position (length MelodicDictation::InputBuffer))  ; 0-based index into sequence
         (expected (list-ref MelodicDictation::SequenceNums position))
         (note     (list-ref MelodicDictation::SequenceNotes position)))

    ;; Draw the correct note for this position (the mark below says whether
    ;; the user got it right).
    (MelodicDictation::DrawNote note)
    (MelodicDictation::gotoEnd)

    ;; Append choice to buffer
    (set! MelodicDictation::InputBuffer
      (append MelodicDictation::InputBuffer (list chosen)))

    (if (= chosen expected)
      ;; Correct note for this position
      (begin
        (MelodicDictation::PlaceAnswerStatus "CheckMark")
        (if (= (length MelodicDictation::InputBuffer)
               MelodicDictation::SequenceLength)
          ;; Completed the whole sequence correctly
          (begin
            (set! MelodicDictation::Accepting #f)
            (set! MelodicDictation::score (+ MelodicDictation::score 1))
            (set! MelodicDictation::LevelCorrect (+ MelodicDictation::LevelCorrect 1))
            (MelodicDictation::showscore)
            (if (MelodicDictation::ShouldLevelUp)
              (begin
                (set! MelodicDictation::LevelNum (+ MelodicDictation::LevelNum 1))
                (set! MelodicDictation::LevelCorrect 0)
                (MelodicDictation::SetupLevel)
                (MelodicDictation::Flash
                  (string-append " <span font_desc=\"36\" foreground=\"yellow\">"
                    (car (list-ref MelodicDictation::Levels MelodicDictation::LevelNum))
                    "!</span>"))
                (MelodicDictation::ScheduleNext 2500))
              (begin
                (MelodicDictation::ShowLevel)
                (MelodicDictation::Flash "")
                (MelodicDictation::ScheduleNext 1200))))
          ;; More notes to go — update prompt
          (MelodicDictation::UpdatePrompt)))
      ;; Wrong note — draw an X to show where we got off, then keep
      ;; drawing the correct remaining notes of the melody so the user
      ;; can see how the rest of it should have looked, then move on.
      (begin
        (set! MelodicDictation::Accepting #f)
        (MelodicDictation::PlaceAnswerStatus "CrossSign")
        (let* ((remaining (list-tail MelodicDictation::SequenceNotes (+ position 1)))
               (remaining-count (length remaining)))
          (let loop ((notes remaining))
            (if (not (null? notes))
              (begin
                (MelodicDictation::DrawNote (car notes))
                (MelodicDictation::gotoEnd)
                (loop (cdr notes)))))
          (MelodicDictation::showscore)
          ;; give a bit more time to view longer remaining melodies
          (MelodicDictation::ScheduleNext (+ 1200 (* remaining-count 300))))))))

;; ── Button factory (one button per scale degree) ──────────────────────────
(define (MelodicDictation::createbutton degree)
  (CreateButton
    (MelodicDictation::ButtonTag degree)
    (string-append " <span font_desc=\"22\" foreground=\"blue\">"
                   (list-ref MelodicDictation::Solfege degree) "</span>"))
  (d-SetDirectiveTagActionScript
    (MelodicDictation::ButtonTag degree)
    (string-append "(MelodicDictation::notechosen \""
                   (number->string degree) "\")")))

;; ── Help ──────────────────────────────────────────────────────────────────
(define (MelodicDictation::help)
  (d-InfoDialog
    "Click Play Scale to hear the notes for this level, then Play Melody for a sequence of 3 to 6 notes. Click the solfege buttons in order to identify each note. A fully correct melody scores +1; a wrong note gets an x, and the rest of the correct melody is shown before the next one starts. After 10 correct melodies you move up a level. Click the Level or Key button to choose a different one."))

;; ── Main entry point ──────────────────────────────────────────────────────
(define (MelodicDictation::MelodicDictations)
  (CreateButton "MelodicDictation::GameScore" "<span font_desc=\"22\">Click to start</span>")
  (d-SetDirectiveTagActionScript "MelodicDictation::GameScore" "(MelodicDictation::Go)")

  ;; Prompt label (starts blank)
  (CreateButton "MelodicDictation::Prompt" "<span font_desc=\"18\"></span>")

  ;; Big feedback flash (starts blank, shown briefly on a correct answer)
  (CreateButton "MelodicDictation::Feedback" "<span font_desc=\"24\"></span>")

  ;; One button for each of the 8 scale degrees
  (let loop ((degree 0))
    (if (< degree 8)
      (begin
        (MelodicDictation::createbutton degree)
        (loop (+ degree 1)))))

  (CreateButton "MelodicDictation::PlayMelody" "<span font_desc=\"22\">Play Melody</span>")
  (d-SetDirectiveTagActionScript "MelodicDictation::PlayMelody"
    "(MelodicDictation::PlaySequence)")

  (CreateButton "MelodicDictation::play_scale" "<span font_desc=\"22\">Play Scale</span>")
  (d-SetDirectiveTagActionScript "MelodicDictation::play_scale"
    "(MelodicDictation::PlayScale)")

  ;; Level and key selectors (click to move to the next one)
  (CreateButton "MelodicDictation::Level" "<b>Level</b>")
  (d-SetDirectiveTagActionScript "MelodicDictation::Level" "(MelodicDictation::CycleLevel)")
  (CreateButton "MelodicDictation::Key" "<b>Key</b>")
  (d-SetDirectiveTagActionScript "MelodicDictation::Key" "(MelodicDictation::CycleKey)")

  (CreateButton "MelodicDictation::GameHelp" "<b>Help</b>")
  (d-SetDirectiveTagActionScript "MelodicDictation::GameHelp" "(MelodicDictation::help)")

  ;; Fill in the buttons and labels for the starting level and key
  (MelodicDictation::SetupLevel))

(MelodicDictation::MelodicDictations)

Reply via email to