Code Sketch


yoiiiii master
By: Mhalsakant School
Category: Programming
import javax.swing._
import java.awt._
import java.awt.event._
import java.awt.image.BufferedImage
import java.awt.datatransfer._
import javax.imageio.ImageIO
import java.io._
import scala.collection.mutable.ArrayBuffer

val passwordSecret =
  Array(
    121,97,100,110,101,115,
    104,50,48,49,51
  ).map(_.toChar).mkString

var speechProcess: Process = null
var speechPlaying = false
var stopSpeechFlag = false

var savedImage: BufferedImage = null

def makeButton(text: String): JButton = {
  val b = new JButton(text)
  b.setFont(
    new Font(
      "SansSerif",
      Font.BOLD,
      13
    )
  )
  b
}

def stopSpeech(): Unit = {
  stopSpeechFlag = true
  speechPlaying = false

  try {
    if (speechProcess != null) {
      speechProcess.destroy()
      speechProcess = null
    }
  } catch {
    case _: Throwable =>
      speechProcess = null
  }
}

def getVoices(): Array[String] = {

  val names =
    new ArrayBuffer[String]()

  try {

    val command =
      "Add-Type -AssemblyName System.Speech; " +
      "$s=New-Object System.Speech.Synthesis.SpeechSynthesizer; " +
      "$s.GetInstalledVoices() | ForEach-Object { $_.VoiceInfo.Name }"

    val p =
      new ProcessBuilder(
        "powershell.exe",
        "-NoProfile",
        "-ExecutionPolicy",
        "Bypass",
        "-Command",
        command
      ).start()

    val r =
      new BufferedReader(
        new InputStreamReader(
          p.getInputStream,
          "UTF-8"
        )
      )

    var line: String = null

    while ({
      line = r.readLine()
      line != null
    }) {
      val x = line.trim
      if (x.length > 0) {
        names += x
      }
    }

    p.waitFor()

  } catch {
    case _: Throwable =>
  }

  names.distinct.toArray
}

def speakAsync(
    text: String,
    voice: String,
    rate: Int
): Unit = {

  stopSpeech()

  stopSpeechFlag = false
  speechPlaying = true

  val safeText =
    text
      .replace("&", " and ")
      .replace("\r", " ")
      .replace("\n", " ")
      .replace("\"", "'")
      .replace("'", "''")

  val safeVoice =
    voice.replace("'", "''")

  val voicePart =
    if (voice.length > 0) {
      "$s.SelectVoice('" +
      safeVoice +
      "'); "
    } else {
      ""
    }

  val command =
    "Add-Type -AssemblyName System.Speech; " +
    "$s=New-Object System.Speech.Synthesis.SpeechSynthesizer; " +
    "$s.Rate=" + rate + "; " +
    "$s.Volume=100; " +
    voicePart +
    "$s.Speak('" +
    safeText +
    "');"

  val worker =
    new Thread(
      new Runnable {
        override def run(): Unit = {

          try {

            speechProcess =
              new ProcessBuilder(
                "powershell.exe",
                "-NoProfile",
                "-ExecutionPolicy",
                "Bypass",
                "-Command",
                command
              ).start()

            speechProcess.waitFor()

          } catch {
            case _: Throwable =>
          }

          speechPlaying = false
          speechProcess = null
        }
      }
    )

  worker.start()
}

def answerTeacherQuestion(
    question0: String
): String = {

  val q =
    question0.toLowerCase.trim

  if (
    q.contains("jframe") &&
    q.contains("jpanel")
  ) {
    "JFrame ?? ?????? application ?? ????? window ????. JPanel ?? ???? window ???? ?? components ????????? ????????????? container ????."

  } else if (
    q.contains("jframe")
  ) {
    "JFrame ?????? ?????? desktop application ?? ????? window. ????? buttons, panels, labels ??? ??? components ????? ?????."

  } else if (
    q.contains("jpanel")
  ) {
    "JPanel ?? container ???. GUI ???? components ????????? organize ?????????? ?????? ????? ????."

  } else if (
    q.contains("jbutton")
  ) {
    "JButton ?? click ???? ?????? button ???. ?????? ActionListener ????? click ???????? action ?????? ????."

  } else if (
    q.contains("jlabel")
  ) {
    "JLabel ?? ????? application ????? text ????? ???? ?????? ???????????? ???? ????."

  } else if (
    q.contains("jtextfield")
  ) {
    "JTextField ?? ????? user ???? ?? line ?? text input ?????????? ???? ????."

  } else if (
    q.contains("jtextarea")
  ) {
    "JTextArea ?? ????? ???? text ???????????? ????? user ???? ???? ????? ?????????? ???? ????."

  } else if (
    q.contains("timer")
  ) {
    "Swing Timer ?????? ??????? action ??????. Games ????? movement, animation ??? repeated updates ???? ?? ??? ?????? ???."

  } else if (
    q.contains("paintcomponent")
  ) {
    "paintComponent ???? ?????? custom graphics draw ???? ?????. Game ????? player, obstacles, background ??? HUD ???? ?????????? ?????? ????? ????."

  } else if (
    q.contains("repaint")
  ) {
    "repaint ???? component ?????? paint ???????? ?????? ???? ????. Animation ????? state ??????????? screen update ?????????? ?????? ????? ????."

  } else if (
    q.contains("collision")
  ) {
    "Collision ?????? ??? game objects ????????? touch ????? overlap ??? ???? ?? ?? ??????. Player, wall, enemy, coin ??? finish ???? ?????? ????? ????."

  } else if (
    q.contains("keyboard")
  ) {
    "Keyboard control ???? key events ?????? ?????. Arrow keys ????? W A S D ?????? player movement ???? ???? ????."

  } else if (
    q.contains("mouse")
  ) {
    "Mouse events ?????? click, movement ??? drag controls ???? ???? ?????. Mouse ???? X ??? Y coordinates ??????."

  } else if (
    q.contains("scala swing")
  ) {
    "Scala Swing ???? ?????? Scala ????? desktop graphical applications ???? ???? ?????. Java Swing ?? components ?????? windows, buttons, input ??? games ????? ?????."

  } else if (
    q.contains("chatgpt")
  ) {
    "ChatGPT ???? ?????? code ???????????? environment, project, features, controls ??? expected behavior ????????? ????. Complete runnable code ????."

  } else if (
    q.contains("error")
  ) {
    "Error ??? ?? complete compiler error copy ???. Current code ??? expected result ???? ChatGPT ?? ????. ?? complete corrected replacement code ????."

  } else if (
    q.contains("game")
  ) {
    "Scala Swing game ????? player state, controls, Timer, drawing, collision, score, levels ??? game state ????? ???? ???? ????."

  } else if (
    q.contains("score")
  ) {
    "Score system ????? coins, bonuses, level completion ????? ??? actions ???? points ???? ?????."

  } else if (
    q.contains("level")
  ) {
    "Level system ????? ???????? ???? level ????? speed, obstacles, layout ????? target ????? difficulty ?????? ????."

  } else if (
    q.contains("code")
  ) {
    "Code ??????? ???? project ?? ??? ????? ???. Environment, features, controls, screens ??? expected result ????. Complete replacement code ????."

  } else {
    "?? ?????? ?????? offline teacher knowledge ????? ?????? ????. Scala Swing ???? ????? specific keyword ?????? ?????? ?????? ??????. ?????????? JFrame, JButton, JPanel, Timer, collision ????? ChatGPT prompt."
  }
}

def createImage(
    prompt0: String
): BufferedImage = {

  val prompt =
    prompt0.trim

  val image =
    new BufferedImage(
      900,
      550,
      BufferedImage.TYPE_INT_RGB
    )

  val g =
    image.createGraphics()

  g.setRenderingHint(
    RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON
  )

  g.setColor(
    new Color(
      18,
      25,
      40
    )
  )

  g.fillRect(
    0,
    0,
    900,
    550
  )

  g.setColor(
    new Color(
      45,
      110,
      210
    )
  )

  g.fillOval(
    95,
    120,
    220,
    220
  )

  g.setColor(
    new Color(
      95,
      210,
      155
    )
  )

  g.fillOval(
    570,
    125,
    205,
    205
  )

  g.setColor(
    Color.WHITE
  )

  g.setFont(
    new Font(
      "SansSerif",
      Font.BOLD,
      40
    )
  )

  g.drawString(
    "AI IMAGE STUDIO",
    245,
    75
  )

  g.setFont(
    new Font(
      "SansSerif",
      Font.PLAIN,
      20
    )
  )

  val shown =
    if (prompt.length > 70) {
      prompt.substring(0,70) + "..."
    } else {
      prompt
    }

  g.drawString(
    shown,
    65,
    455
  )

  g.setFont(
    new Font(
      "SansSerif",
      Font.BOLD,
      22
    )
  )

  g.drawString(
    "CREATED IN THIS APP",
    300,
    505
  )

  g.dispose()

  image
}

def imagePreview(
    label: JLabel,
    image: BufferedImage
): Unit = {

  savedImage = image

  val scaled =
    image.getScaledInstance(
      650,
      400,
      Image.SCALE_SMOOTH
    )

  label.setText("")
  label.setIcon(
    new ImageIcon(
      scaled
    )
  )
}

def uploadInto(
    label: JLabel
): Unit = {

  val chooser =
    new JFileChooser()

  val result =
    chooser.showOpenDialog(null)

  if (
    result ==
    JFileChooser.APPROVE_OPTION
  ) {

    try {

      val img =
        ImageIO.read(
          chooser.getSelectedFile
        )

      if (img != null) {

        imagePreview(
          label,
          img
        )
      }

    } catch {
      case _: Throwable =>
        JOptionPane.showMessageDialog(
          null,
          "Image open failed."
        )
    }
  }
}

def pasteInto(
    label: JLabel
): Unit = {

  try {

    val clipboard =
      Toolkit
        .getDefaultToolkit
        .getSystemClipboard

    if (
      clipboard.isDataFlavorAvailable(
        DataFlavor.imageFlavor
      )
    ) {

      val raw =
        clipboard
          .getData(
            DataFlavor.imageFlavor
          )
          .asInstanceOf[Image]

      val w =
        raw.getWidth(null)

      val h =
        raw.getHeight(null)

      if (
        w > 0 &&
        h > 0
      ) {

        val img =
          new BufferedImage(
            w,
            h,
            BufferedImage.TYPE_INT_ARGB
          )

        val g =
          img.createGraphics()

        g.drawImage(
          raw,
          0,
          0,
          null
        )

        g.dispose()

        imagePreview(
          label,
          img
        )
      }

    } else {

      JOptionPane.showMessageDialog(
        null,
        "Clipboard madhye image nahi."
      )
    }

  } catch {
    case _: Throwable =>
      JOptionPane.showMessageDialog(
        null,
        "Image paste failed."
      )
  }
}

def copyCurrentImage(): Unit = {

  if (
    savedImage == null
  ) {

    JOptionPane.showMessageDialog(
      null,
      "????? image ???? ??? ????? upload ???."
    )

    return
  }

  val image =
    savedImage

  val transferable =
    new Transferable {

      override def getTransferDataFlavors()
          : Array[DataFlavor] = {
        Array(DataFlavor.imageFlavor)
      }

      override def isDataFlavorSupported(
          flavor: DataFlavor
      ): Boolean = {
        flavor == DataFlavor.imageFlavor
      }

      override def getTransferData(
          flavor: DataFlavor
      ): Object = {
        image
      }
    }

  try {

    Toolkit
      .getDefaultToolkit
      .getSystemClipboard
      .setContents(
        transferable,
        null
      )

    JOptionPane.showMessageDialog(
      null,
      "Image copied."

    )

  } catch {
    case _: Throwable =>
      JOptionPane.showMessageDialog(
        null,
        "Image copy failed."
      )
  }
}

def saveCurrentImage(): Unit = {

  if (
    savedImage == null
  ) {

    JOptionPane.showMessageDialog(
      null,
      "????? image ???? ???."
    )

    return
  }

  val chooser =
    new JFileChooser()

  val result =
    chooser.showSaveDialog(null)

  if (
    result ==
    JFileChooser.APPROVE_OPTION
  ) {

    try {

      ImageIO.write(
        savedImage,
        "png",
        chooser.getSelectedFile
      )

      JOptionPane.showMessageDialog(
        null,
        "Image saved successfully."
      )

    } catch {
      case _: Throwable =>
        JOptionPane.showMessageDialog(
          null,
          "Image save failed."
        )
    }
  }
}

def openApplication(): Unit = {

  val frame =
    new JFrame(
      "SCALA SWING AI TEACHER ULTRA LAB"
    )

  frame.setSize(
    1400,
    900
  )

  frame.setDefaultCloseOperation(
    WindowConstants.EXIT_ON_CLOSE
  )

  frame.setLocationRelativeTo(null)

  val tabs =
    new JTabbedPane()

  tabs.setFont(
    new Font(
      "SansSerif",
      Font.BOLD,
      14
    )
  )

  val voices =
    getVoices()

  val voiceNames =
    if (voices.length > 0) {
      voices.take(5)
    } else {
      Array("Default Windows Voice")
    }

  val voiceBox =
    new JComboBox[String](
      voiceNames
    )

  val speed =
    new JSlider(
      -5,
      2,
      -1
    )

  speed.setPreferredSize(
    new Dimension(
      150,
      30
    )
  )

  val teacherText =
    new JTextArea()

  teacherText.setEditable(false)
  teacherText.setLineWrap(true)
  teacherText.setWrapStyleWord(true)

  teacherText.setFont(
    new Font(
      "SansSerif",
      Font.PLAIN,
      16
    )
  )

  val blackboard =
    new JTextArea()

  blackboard.setEditable(false)
  blackboard.setLineWrap(true)
  blackboard.setWrapStyleWord(true)

  blackboard.setFont(
    new Font(
      "Monospaced",
      Font.BOLD,
      20
    )
  )

  blackboard.setForeground(
    Color.WHITE
  )

  blackboard.setBackground(
    new Color(
      25,
      42,
      33
    )
  )

  blackboard.setBorder(
    BorderFactory.createEmptyBorder(
      20,
      20,
      20,
      20
    )
  )

  val chat =
    new JTextArea()

  chat.setEditable(false)
  chat.setLineWrap(true)
  chat.setWrapStyleWord(true)

  chat.setFont(
    new Font(
      "SansSerif",
      Font.PLAIN,
      15
    )
  )

  val chatInput =
    new JTextField()

  val ask =
    makeButton(
      "ASK"
    )

  val chatBottom =
    new JPanel(
      new BorderLayout()
    )

  chatBottom.add(
    chatInput,
    BorderLayout.CENTER
  )

  chatBottom.add(
    ask,
    BorderLayout.EAST
  )

  val chatPanel =
    new JPanel(
      new BorderLayout()
    )

  val chatTitle =
    new JLabel(
      "? ChatGPT Style Assistant",
      SwingConstants.LEFT
    )

  chatTitle.setFont(
    new Font(
      "SansSerif",
      Font.BOLD,
      20
    )
  )

  chatPanel.add(
    chatTitle,
    BorderLayout.NORTH
  )

  chatPanel.add(
    new JScrollPane(
      chat
    ),
    BorderLayout.CENTER
  )

  chatPanel.add(
    chatBottom,
    BorderLayout.SOUTH
  )

  val lessons =
    Array(

      Array(
        "WELCOME",
        "WELCOME TO THE\nSCALA SWING LAB",
        "???????! ?????? ???. ?? ??? Scala Swing ??? ChatGPT ???? ?????? project ??? ???? ?????? ?? ?????? ????. ?? ???????? ?? ?? ???????, ?????? ?????? ??????? ??????.",
        "Hello! Tu maza expert Scala Swing developer ahes."
      ),

      Array(
        "OPEN CHATGPT",
        "OPEN CHATGPT\n\nNEW CHAT\n\nREADY",
        "??? ?????? ??? ChatGPT ???? ??? ???? chat ???? ???. ?????? project ?? ????? ?????? ??? ???? ??????? ????.",
        "Open ChatGPT\nStart a New Chat"
      ),

      Array(
        "PROJECT IDEA",
        "MY PROJECT\n\nGAME\nAPP\nTOOL\nQUIZ\nDRAWING",
        "??? ???????? ????? ??? ??????? ??? ?? ????. Game, calculator, quiz, drawing application ????? learning tool ?????? ?????? ????? ????.",
        "My Project:\nScala Swing Game"
      ),

      Array(
        "REQUIREMENTS",
        "FEATURES\n\nPLAYER\nCONTROLS\nSCORE\nLEVELS\nSCREENS",
        "??? project ?????? features ????. Player ??? ?????, controls ?????, score ??? ??????, ???? levels ????? ??? ????? screens ??????? ?? ?????? ?????.",
        "Features:\nPlayer\nControls\nScore\nLevels\nScreens"
      ),

      Array(
        "MASTER PROMPT",
        "CHATGPT PROMPT\n\nROLE\nENVIRONMENT\nPROJECT\nFEATURES",
        "??? master prompt ????. ChatGPT ?? ????? environment, project, features ??? ???????? output ????????? ?????.",
        "Tu maza expert Scala Swing developer ahes.\n\nMala complete runnable code dya."
      ),

      Array(
        "COMPLETE CODE",
        "COMPLETE RUNNABLE CODE\n\nNO PLACEHOLDERS\nNO MISSING METHODS",
        "ChatGPT ???? complete runnable code ????. Complete imports, complete methods ??? complete startup ?????? code ????.",
        "Complete imports dya.\nNo missing methods.\nNo undefined variables.\nNo placeholders."
      ),

      Array(
        "COPY",
        "CHATGPT CODE\n\nSELECT ALL\nCOPY",
        "ChatGPT ?? code ???????? ??????? code select ???? copy ???. ???? ????? ???? ??? ??? ???.",
        "SELECT COMPLETE CODE\nCOPY"
      ),

      Array(
        "PASTE",
        "SCALA EDITOR\n\nREMOVE OLD CODE\nPASTE NEW CODE",
        "??? Scala editor ????? ??. ???? code ???? ??? ChatGPT ???? copy ?????? ????? code paste ???.",
        "Scala Editor\nDelete Old Code\nPaste New Code"
      ),

      Array(
        "SAVE",
        "SAVE\n\nCTRL + S",
        "Code paste ???????? save ???. ??? ???? program run ?????????? ???? ???.",
        "SAVE\nCTRL + S"
      ),

      Array(
        "RUN",
        "RUN PROGRAM\n\nCHECK GUI",
        "??? Run ???. GUI window ????? ?? program ???? ????. ??? controls ??? features ?????.",
        "RUN\nCHECK GUI"
      ),

      Array(
        "ERROR",
        "ERROR?\n\nCOPY COMPLETE ERROR\n+\nCURRENT CODE",
        "?? error ??? ?? ????? ??? ???. Complete compiler error copy ???. ???????? current code ??? expected result ChatGPT ?? ????.",
        "ERROR:\n[PASTE ERROR]\n\nCURRENT CODE:\n[PASTE CODE]\n\nEXPECTED:\n[RESULT]"
      ),

      Array(
        "FIX",
        "CHATGPT ERROR FIX\n\nCOMPLETE CORRECTED CODE",
        "??? ChatGPT ?? ????? ?? ???? ?? line fix ???. Complete corrected replacement code ???? ??? ??????? working features ???? ???.",
        "Fix the problem.\nReturn complete corrected replacement code.\nDo not remove existing features."
      ),

      Array(
        "GAME",
        "GAME SYSTEM\n\nPLAYER\nTIMER\nDRAWING\nCOLLISION\nSCORE",
        "??? game ???? ?????? player, Timer, drawing, collision ??? score ???? ???? add ???.",
        "PLAYER\nMOVEMENT\nTIMER\nDRAWING\nCOLLISION"
      ),

      Array(
        "LEVELS",
        "LEVEL SYSTEM\n\nLEVEL 1\nLEVEL 2\nLEVEL 3\nLEVEL 4",
        "Project working ???????? levels ???? ???. ???????? level ????? difficulty ?????? ?????.",
        "LEVEL 1\nLEVEL 2\nLEVEL 3\nLEVEL 4"
      ),

      Array(
        "PRO FEATURES",
        "PRO MODE\n\nMENU\nPAUSE\nSETTINGS\nSAVE\nHIGH SCORE",
        "??? project ???? professional ????? ????. Main Menu, Pause, Settings, Save ??? High Score ??????? features add ???.",
        "MAIN MENU\nPAUSE\nSETTINGS\nSAVE\nHIGH SCORE"
      ),

      Array(
        "UPGRADE",
        "EXISTING PROJECT\n+\nNEW FEATURE\n=\nUPGRADE",
        "???? feature add ?????? ChatGPT ?? existing features remove ??? ??? ??? ?????. ???? feature existing project ????? integrate ?????? ?????.",
        "KEEP EXISTING FEATURES\nADD NEW FEATURE"
      ),

      Array(
        "FINISH",
        "IDEA\n?\nPROMPT\n?\nCODE\n?\nCOPY\n?\nPASTE\n?\nRUN\n?\nFIX\n?\nUPGRADE",
        "??? ???! ??? ???????? project ???? ???????? ????? ????? ????? ???. ??? ?????? ??????? ?????? ???? ???? Scala Swing projects ???? ??? ????.",
        "Congratulations!\nYou are ready to build."
      )
    )

  def refreshLesson(
      index: Int
  ): Unit = {

    blackboard.setText(
      lessons(index)(1)
    )

    teacherText.setText(
      lessons(index)(2)
    )

    chat.setText(
      "ChatGPT Style Assistant\n\n" +
      lessons(index)(3)
    )

    chatInput.setText(
      lessons(index)(3)
    )
  }

  def teach(
      index: Int
  ): Unit = {

    val voice =
      voiceBox.getSelectedItem match {
        case null => ""
        case x => x.toString
      }

    val rate =
      speed.getValue

    speakAsync(
      lessons(index)(2),
      voice,
      rate
    )
  }

  var lessonIndex =
    0

  val progress =
    new JProgressBar(
      0,
      lessons.length
    )

  progress.setValue(1)

  progress.setStringPainted(true)

  val lessonCounter =
    new JLabel(
      "Lesson 1 / " +
      lessons.length,
      SwingConstants.CENTER
    )

  lessonCounter.setFont(
    new Font(
      "SansSerif",
      Font.BOLD,
      14
    )
  )

  val automatic =
    new JCheckBox(
      "AUTO NEXT",
      true
    )

  val play =
    makeButton(
      "PLAY"
    )

  val stop =
    makeButton(
      "STOP"
    )

  val replay =
    makeButton(
      "REPLAY"
    )

  val back =
    makeButton(
      "BACK"
    )

  val next =
    makeButton(
      "NEXT"
    )

  val voiceTest =
    makeButton(
      "TEST VOICE"
    )

  def updateLessonDisplay(): Unit = {

    refreshLesson(
      lessonIndex
    )

    progress.setValue(
      lessonIndex + 1
    )

    progress.setString(
      "Lesson " +
      (lessonIndex + 1) +
      " / " +
      lessons.length
    )

    lessonCounter.setText(
      "Lesson " +
      (lessonIndex + 1) +
      " / " +
      lessons.length
    )
  }

  play.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {

        teach(
          lessonIndex
        )
      }
    }
  )

  replay.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {

        teach(
          lessonIndex
        )
      }
    }
  )

  stop.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {

        stopSpeech()
      }
    }
  )

  next.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {

        stopSpeech()

        if (
          lessonIndex <
          lessons.length - 1
        ) {

          lessonIndex += 1

          updateLessonDisplay()

          teach(
            lessonIndex
          )
        }
      }
    }
  )

  back.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {

        stopSpeech()

        if (
          lessonIndex > 0
        ) {

          lessonIndex -= 1

          updateLessonDisplay()

          teach(
            lessonIndex
          )
        }
      }
    }
  )

  voiceTest.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {

        val voice =
          voiceBox.getSelectedItem match {
            case null => ""
            case x => x.toString
          }

        speakAsync(
          "???????! ?? ????? AI Teacher ???. ???, ??? Scala Swing ??????.",
          voice,
          speed.getValue
        )
      }
    }
  )

  val autoTimer =
    new javax.swing.Timer(
      150,
      new ActionListener {

        var lastSpeaking =
          false

        var blinkCount =
          0

        override def actionPerformed(
            e: ActionEvent
        ): Unit = {

          blinkCount += 1

          if (
            speechPlaying
          ) {

            teacherTitle.setText(
              if (
                blinkCount % 2 == 0
              ) {
                "AI TEACHER ? SPEAKING"
              } else {
                "AI TEACHER ? SPEAKING..."
              }
            )

            teacherAvatar.setText(
              if (
                blinkCount % 2 == 0
              ) {
                "<html><center>" +
                "<font size='7'>AI</font><br>" +
                "<font size='5'><b>TEACHER</b></font><br>" +
                "<font color='green'><b>? SPEAKING</b></font>" +
                "</center></html>"
              } else {
                "<html><center>" +
                "<font size='7'>AI</font><br>" +
                "<font size='5'><b>TEACHER</b></font><br>" +
                "<font color='green'><b>? SPEAKING...</b></font>" +
                "</center></html>"
              }
            )

          } else {

            teacherTitle.setText(
              "AI TEACHER"
            )

            teacherAvatar.setText(
              "<html><center>" +
              "<font size='7'>AI</font><br>" +
              "<font size='5'><b>TEACHER</b></font>" +
              "</center></html>"
            )
          }

          if (
            lastSpeaking &&
            !speechPlaying &&
            automatic.isSelected
          ) {

            SwingUtilities.invokeLater(
              new Runnable {
                override def run(): Unit = {

                  if (
                    lessonIndex <
                    lessons.length - 1
                  ) {

                    lessonIndex += 1

                    updateLessonDisplay()

                    teach(
                      lessonIndex
                    )

                  }
                }
              }
            )
          }

          lastSpeaking =
            speechPlaying
        }
      }
    )

  val voiceControls =
    new JPanel(
      new FlowLayout()
    )

  voiceControls.add(
    new JLabel(
      "VOICE:"
    )
  )

  voiceControls.add(
    voiceBox
  )

  voiceControls.add(
    new JLabel(
      "SPEED:"
    )
  )

  voiceControls.add(
    speed
  )

  voiceControls.add(
    voiceTest
  )

  voiceControls.add(
    automatic
  )

  val controlPanel =
    new JPanel(
      new FlowLayout()
    )

  controlPanel.add(
    back
  )

  controlPanel.add(
    play
  )

  controlPanel.add(
    stop
  )

  controlPanel.add(
    replay
  )

  controlPanel.add(
    next
  )

  val classroomBottom =
    new JPanel(
      new BorderLayout()
    )

  classroomBottom.add(
    progress,
    BorderLayout.NORTH
  )

  classroomBottom.add(
    lessonCounter,
    BorderLayout.CENTER
  )

  classroomBottom.add(
    voiceControls,
    BorderLayout.SOUTH
  )

  val classroom =
    new JPanel(
      new BorderLayout()
    )

  classroom.add(
    new JScrollPane(
      blackboard
    ),
    BorderLayout.CENTER
  )

  teacherTitle =
    new JLabel(
      "AI TEACHER",
      SwingConstants.CENTER
    )

  teacherTitle.setFont(
    new Font(
      "SansSerif",
      Font.BOLD,
      20
    )
  )

  teacherAvatar =
    new JLabel(
      "<html><center>" +
      "<font size='7'>AI</font><br>" +
      "<font size='5'><b>TEACHER</b></font>" +
      "</center></html>",
      SwingConstants.CENTER
    )

  val teacherBox =
    new JPanel(
      new BorderLayout()
    )

  teacherBox.setBackground(
    new Color(
      238,
      241,
      246
    )
  )

  teacherBox.add(
    teacherTitle,
    BorderLayout.NORTH
  )

  teacherBox.add(
    teacherAvatar,
    BorderLayout.CENTER
  )

  teacherBox.add(
    new JScrollPane(
      teacherText
    ),
    BorderLayout.SOUTH
  )

  val classCenter =
    new JPanel(
      new GridLayout(
        1,
        2
      )
    )

  classCenter.add(
    blackboard
  )

  classCenter.add(
    teacherBox
  )

  classroom.add(
    classCenter,
    BorderLayout.CENTER
  )

  classroom.add(
    classroomBottom,
    BorderLayout.SOUTH
  )

  classroom.add(
    controlPanel,
    BorderLayout.NORTH
  )

  tabs.addTab(
    "AI CLASSROOM",
    classroom
  )

  val qa =
    new JPanel(
      new BorderLayout()
    )

  val qaOutput =
    new JTextArea()

  qaOutput.setEditable(false)

  qaOutput.setLineWrap(true)

  qaOutput.setWrapStyleWord(true)

  qaOutput.setFont(
    new Font(
      "SansSerif",
      Font.PLAIN,
      17
    )
  )

  val qaInput =
    new JTextField()

  val qaButton =
    makeButton(
      "ASK TEACHER"
    )

  val qaBottom =
    new JPanel(
      new BorderLayout()
    )

  qaBottom.add(
    qaInput,
    BorderLayout.CENTER
  )

  qaBottom.add(
    qaButton,
    BorderLayout.EAST
  )

  def askQuestion(): Unit = {

    val question =
      qaInput.getText.trim

    if (
      question.length == 0
    ) {
      return
    }

    val answer =
      answerTeacherQuestion(
        question
      )

    qaOutput.setText(
      "YOU:\n" +
      question +
      "\n\n" +
      "AI TEACHER:\n" +
      answer
    )

    val voice =
      voiceBox.getSelectedItem match {
        case null => ""
        case x => x.toString
      }

    speakAsync(
      answer,
      voice,
      speed.getValue
    )
  }

  qaButton.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {
        askQuestion()
      }
    }
  )

  qaInput.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {
        askQuestion()
      }
    }
  )

  qa.add(
    new JLabel(
      "ASK YOUR SCALA TEACHER",
      SwingConstants.CENTER
    ),
    BorderLayout.NORTH
  )

  qa.add(
    new JScrollPane(
      qaOutput
    ),
    BorderLayout.CENTER
  )

  qa.add(
    qaBottom,
    BorderLayout.SOUTH
  )

  tabs.addTab(
    "ASK TEACHER",
    qa
  )

  val imagePanel =
    new JPanel(
      new BorderLayout()
    )

  val imageTitle =
    new JLabel(
      "IMAGE STUDIO",
      SwingConstants.CENTER
    )

  imageTitle.setFont(
    new Font(
      "SansSerif",
      Font.BOLD,
      25
    )
  )

  val imageLabel =
    new JLabel(
      "Create, upload or paste an image here.",
      SwingConstants.CENTER
    )

  imageLabel.setFont(
    new Font(
      "SansSerif",
      Font.PLAIN,
      16
    )
  )

  val imagePrompt =
    new JTextField(
      "A futuristic Scala coding classroom"
    )

  val generate =
    makeButton(
      "GENERATE IMAGE"
    )

  val upload =
    makeButton(
      "UPLOAD"
    )

  val paste =
    makeButton(
      "PASTE"
    )

  val copy =
    makeButton(
      "COPY"
    )

  val save =
    makeButton(
      "SAVE"
    )

  val imageButtons =
    new JPanel(
      new FlowLayout()
    )

  imageButtons.add(
    generate
  )

  imageButtons.add(
    upload
  )

  imageButtons.add(
    paste
  )

  imageButtons.add(
    copy
  )

  imageButtons.add(
    save
  )

  val imageBottom =
    new JPanel(
      new BorderLayout()
    )

  imageBottom.add(
    imagePrompt,
    BorderLayout.NORTH
  )

  imageBottom.add(
    imageButtons,
    BorderLayout.CENTER
  )

  imagePanel.add(
    imageTitle,
    BorderLayout.NORTH
  )

  imagePanel.add(
    imageLabel,
    BorderLayout.CENTER
  )

  imagePanel.add(
    imageBottom,
    BorderLayout.SOUTH
  )

  generate.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {

        val img =
          createImage(
            imagePrompt.getText
          )

        imagePreview(
          imageLabel,
          img
        )
      }
    }
  )

  upload.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {
        uploadInto(
          imageLabel
        )
      }
    }
  )

  paste.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {
        pasteInto(
          imageLabel
        )
      }
    }
  )

  copy.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {
        copyCurrentImage()
      }
    }
  )

  save.addActionListener(
    new ActionListener {
      override def actionPerformed(
          e: ActionEvent
      ): Unit = {
        saveCurrentImage()
      }
    }
  )

  tabs.addTab(
    "IMAGE STUDIO",
    imagePanel
  )

  val skills =
    new JTextArea()

  skills.setEditable(false)
  skills.setLineWrap(true)
  skills.setWrapStyleWord(true)

  skills.setFont(
    new Font(
      "SansSerif",
      Font.PLAIN,
      17
    )
  )

  skills.setText(
    "SCALA SWING SKILL LIBRARY\n\n" +
    "FOUNDATION\n\n" +
    "JFrame\n" +
    "JPanel\n" +
    "JLabel\n" +
    "JButton\n" +
    "JTextField\n" +
    "JTextArea\n" +
    "JScrollPane\n" +
    "JTabbedPane\n\n" +
    "EVENTS\n\n" +
    "ActionListener\n" +
    "Mouse Events\n" +
    "Keyboard Events\n" +
    "Swing Timer\n\n" +
    "GRAPHICS\n\n" +
    "Graphics\n" +
    "paintComponent\n" +
    "fillRect\n" +
    "fillOval\n" +
    "drawLine\n" +
    "drawString\n\n" +
    "GAME DEVELOPMENT\n\n" +
    "Player\n" +
    "Movement\n" +
    "Collision\n" +
    "Score\n" +
    "Levels\n" +
    "Pause\n" +
    "Restart\n" +
    "Win\n" +
    "Game Over\n\n" +
    "ADVANCED\n\n" +
    "Save / Load\n" +
    "Settings\n" +
    "High Score\n" +
    "Debug Mode\n" +
    "Animation\n" +
    "Performance\n" +
    "Project Architecture"
  )

  tabs.addTab(
    "SKILL LIBRARY",
    new JScrollPane(
      skills
    )
  )

  val prompts =
    new JTextArea()

  prompts.setEditable(false)

  prompts.setLineWrap(true)

  prompts.setWrapStyleWord(true)

  prompts.setFont(
    new Font(
      "Monospaced",
      Font.PLAIN,
      15
    )
  )

  prompts.setText(
    "MASTER CHATGPT PROMPT\n\n" +
    "Tu maza expert Scala Swing developer ahes.\n\n" +
    "Environment: [ENVIRONMENT]\n\n" +
    "Project: [PROJECT]\n\n" +
    "Goal: [GOAL]\n\n" +
    "Features: [FEATURES]\n\n" +
    "Controls: [CONTROLS]\n\n" +
    "Screens: [SCREENS]\n\n" +
    "Graphics: [GRAPHICS]\n\n" +
    "Mala complete runnable single-file code dya.\n" +
    "Complete imports dya.\n" +
    "No missing methods.\n" +
    "No undefined variables.\n" +
    "No placeholders.\n" +
    "No incomplete sections.\n" +
    "Existing features remove karu naka.\n" +
    "Return complete replacement code."
  )

  tabs.addTab(
    "MASTER PROMPT",
    new JScrollPane(
      prompts
    )
  )

  val errorLab =
    new JTextArea()

  errorLab.setEditable(false)

  errorLab.setLineWrap(true)

  errorLab.setWrapStyleWord(true)

  errorLab.setFont(
    new Font(
      "SansSerif",
      Font.PLAIN,
      17
    )
  )

  errorLab.setText(
    "ERROR FIX LAB\n\n" +
    "Complete error copy ???.\n\n" +
    "Current code paste ???.\n\n" +
    "Expected behavior ????.\n\n" +
    "ChatGPT ?? ?????:\n\n" +
    "Fakta ek line fix karu naka.\n" +
    "Complete corrected replacement code dya.\n" +
    "Existing features remove karu naka.\n\n" +
    "CHECK:\n" +
    "Imports\n" +
    "Variables\n" +
    "Methods\n" +
    "Braces\n" +
    "Parentheses\n" +
    "Strings\n" +
    "Events\n" +
    "Startup\n" +
    "GUI visibility"
  )

  tabs.addTab(
    "ERROR FIX LAB",
    new JScrollPane(
      errorLab
    )
  )

  val projectBuilder =
    new JTextArea()

  projectBuilder.setEditable(false)

  projectBuilder.setLineWrap(true)

  projectBuilder.setWrapStyleWord(true)

  projectBuilder.setFont(
    new Font(
      "SansSerif",
      Font.PLAIN,
      17
    )
  )

  projectBuilder.setText(
    "PROJECT BUILDER\n\n" +
    "PROJECT NAME:\n" +
    "____________________\n\n" +
    "TYPE:\n" +
    "Game / App / Tool\n\n" +
    "GOAL:\n" +
    "____________________\n\n" +
    "PLAYER / USER:\n" +
    "____________________\n\n" +
    "CONTROLS:\n" +
    "____________________\n\n" +
    "FEATURES:\n" +
    "____________________\n\n" +
    "SCORE:\n" +
    "____________________\n\n" +
    "LEVELS:\n" +
    "____________________\n\n" +
    "WIN CONDITION:\n" +
    "____________________\n\n" +
    "LOSE CONDITION:\n" +
    "____________________\n\n" +
    "SCREENS:\n" +
    "____________________\n\n" +
    "GRAPHICS:\n" +
    "____________________\n\n" +
    "SAVE:\n" +
    "YES / NO\n\n" +
    "SETTINGS:\n" +
    "YES / NO"
  )

  tabs.addTab(
    "PROJECT BUILDER",
    new JScrollPane(
      projectBuilder
    )
  )

  val ideas =
    new JTextArea()

  ideas.setEditable(false)

  ideas.setLineWrap(true)

  ideas.setWrapStyleWord(true)

  ideas.setFont(
    new Font(
      "SansSerif",
      Font.PLAIN,
      17
    )
  )

  ideas.setText(
    "PROJECT IDEA VAULT\n\n" +
    "BEGINNER\n\n" +
    "Calculator\n" +
    "Quiz\n" +
    "Clock\n" +
    "Stopwatch\n" +
    "To Do App\n" +
    "Drawing App\n\n" +
    "INTERMEDIATE\n\n" +
    "Snake\n" +
    "Memory Game\n" +
    "Maze\n" +
    "Puzzle\n" +
    "Brick Breaker\n" +
    "Racing Game\n" +
    "Typing Game\n\n" +
    "ADVANCED\n\n" +
    "Multi-screen Game\n" +
    "Learning Center\n" +
    "Simulation\n" +
    "Project Launcher\n" +
    "Save System\n" +
    "Settings System\n" +
    "Debug Center"
  )

  tabs.addTab(
    "IDEA VAULT",
    new JScrollPane(
      ideas
    )
  )

  frame.setContentPane(
    tabs
  )

  frame.setVisible(true)

  updateLessonDisplay()

  val starter =
    new Thread(
      new Runnable {
        override def run(): Unit = {

          try {
            Thread.sleep(800)
          } catch {
            case _: Throwable =>
          }

          SwingUtilities.invokeLater(
            new Runnable {
              override def run(): Unit = {

                teach(
                  lessonIndex
                )
              }
            }
          )
        }
      }
    )

  starter.start()
}

val login =
  new JFrame(
    "PRIVATE AI TEACHER"
  )

login.setSize(
  470,
  290
)

login.setDefaultCloseOperation(
  WindowConstants.EXIT_ON_CLOSE
)

login.setLocationRelativeTo(null)

val loginPanel =
  new JPanel(
    new GridBagLayout()
  )

loginPanel.setBackground(
  Color.WHITE
)

val gc =
  new GridBagConstraints()

gc.insets =
  new Insets(
    9,
    9,
    9,
    9
  )

gc.fill =
  GridBagConstraints.HORIZONTAL

val loginTitle =
  new JLabel(
    "PRIVATE AI TEACHER",
    SwingConstants.CENTER
  )

loginTitle.setFont(
  new Font(
    "SansSerif",
    Font.BOLD,
    28
  )
)

val loginInfo =
  new JLabel(
    "Enter access code",
    SwingConstants.CENTER
  )

val passwordField =
  new JPasswordField()

passwordField.setPreferredSize(
  new Dimension(
    290,
    36
  )
)

val unlock =
  makeButton(
    "UNLOCK"
  )

val loginStatus =
  new JLabel(
    " ",
    SwingConstants.CENTER
  )

gc.gridx = 0
gc.gridy = 0
gc.gridwidth = 2

loginPanel.add(
  loginTitle,
  gc
)

gc.gridy = 1

loginPanel.add(
  loginInfo,
  gc
)

gc.gridy = 2

loginPanel.add(
  passwordField,
  gc
)

gc.gridy = 3
gc.gridwidth = 1
gc.gridx = 0

loginPanel.add(
  unlock,
  gc
)

gc.gridx = 1

loginPanel.add(
  loginStatus,
  gc
)

login.setContentPane(
  loginPanel
)

def checkPassword(): Unit = {

  val entered =
    new String(
      passwordField.getPassword
    )

  if (
    entered == passwordSecret
  ) {

    login.dispose()

    try {

      openApplication()

    } catch {

      case ex: Throwable =>

        JOptionPane.showMessageDialog(
          null,
          "Application start error:\n" +
          ex.getClass.getName +
          "\n\n" +
          ex.getMessage
        )
    }

  } else {

    loginStatus.setText(
      "ACCESS DENIED"
    )

    passwordField.setText("")
  }
}

unlock.addActionListener(
  new ActionListener {
    override def actionPerformed(
        e: ActionEvent
    ): Unit = {
      checkPassword()
    }
  }
)

passwordField.addActionListener(
  new ActionListener {
    override def actionPerformed(
        e: ActionEvent
    ): Unit = {
      checkPassword()
    }
  }
)

var teacherTitle: JLabel = null
var teacherAvatar: JLabel = null

login.setVisible(true)

passwordField.requestFocusInWindow()