Code Sketch


BixuuPrisonEscape
By: Mhalsakant School
Category: Programming
import java.awt.{BorderLayout, Color, Dimension, Font, Graphics, Graphics2D, GradientPaint, Polygon, RenderingHints}
import java.awt.event.{ActionEvent, ActionListener, KeyAdapter, KeyEvent, MouseAdapter, MouseEvent, MouseMotionAdapter, MouseWheelEvent, MouseWheelListener, WindowAdapter, WindowEvent}
import java.io.{BufferedReader, File, FileInputStream, FileOutputStream, InputStreamReader, OutputStreamWriter, PrintWriter}
import java.net.{InetAddress, ServerSocket, Socket}
import java.security.MessageDigest
import java.util.Properties
import java.util.concurrent.CopyOnWriteArrayList
import javax.swing.{BorderFactory, Box, BoxLayout, JButton, JComboBox, JFrame, JLabel, JOptionPane, JPanel, JPasswordField, JTextField, SwingConstants, SwingUtilities, Timer, WindowConstants}
import scala.collection.mutable

object BixuuPrisonEscape {
  final case class Profile(name: String, bucks: Int, diamonds: Int, wins: Int, bestStage: Int, coupons: Int, hero: String, animation: String)
  final case class V3(px: Double, py: Double, pz: Double)
  final case class Projected(sx: Int, sy: Int, depth: Double)
  final case class Platform3D(id: Int, centerX: Double, topY: Double, centerZ: Double, width: Double, depth: Double, checkpoint: Boolean, bounce: Boolean)
  final case class RemoteAvatar(name: String, px: Double, py: Double, pz: Double, stage: Int)

  def main(args: Array[String]): Unit = {
    SwingUtilities.invokeLater(new Runnable {
      override def run(): Unit = {
        val app = new MainFrame()
        app.setVisible(true)
      }
    })
  }

  object LocalStore {
    private val dataFile = new File(System.getProperty("user.home"), ".bixuu_prison_escape_story_profiles.properties")
    private val props = new Properties()
    private var loaded = false

    private def loadOnce(): Unit = {
      if (!loaded) {
        if (dataFile.exists()) {
          var in: FileInputStream = null
          try { in = new FileInputStream(dataFile); props.load(in) }
          catch { case _: Exception => () }
          finally { try { if (in != null) in.close() } catch { case _: Exception => () } }
        }
        loaded = true
      }
    }

    private def safeName(value: String): String = value.trim.toLowerCase.replaceAll("[^a-z0-9_-]", "_").take(24)

    private def digest(value: String): String = {
      val md = MessageDigest.getInstance("SHA-256")
      val bytes = md.digest(value.getBytes("UTF-8"))
      val out = new StringBuilder
      var i = 0
      while (i < bytes.length) {
        val b = bytes(i) & 255
        val part = Integer.toHexString(b)
        if (part.length == 1) out.append('0')
        out.append(part)
        i += 1
      }
      out.toString
    }

    private def readInt(key: String, fallback: Int): Int = {
      try { props.getProperty(key, fallback.toString).toInt }
      catch { case _: Exception => fallback }
    }

    private def saveProps(): Unit = {
      var out: FileOutputStream = null
      try { out = new FileOutputStream(dataFile); props.store(out, "Bixuu Prison Escape local demo profiles") }
      catch { case _: Exception => () }
      finally { try { if (out != null) out.close() } catch { case _: Exception => () } }
    }

    def create(name: String, password: String): Boolean = synchronized {
      loadOnce()
      val clean = name.trim
      if (clean.length < 3 || password.length < 4) false
      else {
        val key = "player." + safeName(clean) + "."
        if (props.getProperty(key + "name") != null) false
        else {
          props.setProperty(key + "name", clean)
          props.setProperty(key + "pass", digest(password))
          props.setProperty(key + "bucks", "250")
          props.setProperty(key + "diamonds", "20")
          props.setProperty(key + "wins", "0")
          props.setProperty(key + "stage", "0")
          props.setProperty(key + "coupons", "0")
          props.setProperty(key + "hero", "Prison Runner")
          props.setProperty(key + "animation", "Heroic Run")
          saveProps()
          true
        }
      }
    }

    def login(name: String, password: String): Option[Profile] = synchronized {
      loadOnce()
      val key = "player." + safeName(name) + "."
      val storedName = props.getProperty(key + "name")
      val storedPass = props.getProperty(key + "pass")
      if (storedName != null && storedPass != null && storedPass == digest(password)) {
        Some(Profile(storedName, readInt(key + "bucks", 250), readInt(key + "diamonds", 20), readInt(key + "wins", 0), readInt(key + "stage", 0), readInt(key + "coupons", 0), props.getProperty(key + "hero", "Prison Runner"), props.getProperty(key + "animation", "Heroic Run")))
      } else None
    }

    def save(profile: Profile): Unit = synchronized {
      loadOnce()
      val key = "player." + safeName(profile.name) + "."
      props.setProperty(key + "bucks", profile.bucks.toString)
      props.setProperty(key + "diamonds", profile.diamonds.toString)
      props.setProperty(key + "wins", profile.wins.toString)
      props.setProperty(key + "stage", profile.bestStage.toString)
      props.setProperty(key + "coupons", profile.coupons.toString)
      props.setProperty(key + "hero", profile.hero)
      props.setProperty(key + "animation", profile.animation)
      saveProps()
    }

    def winningList(): Vector[Profile] = synchronized {
      loadOnce()
      val result = mutable.ArrayBuffer[Profile]()
      val names = props.stringPropertyNames().iterator()
      while (names.hasNext) {
        val key = names.next()
        if (key.startsWith("player.") && key.endsWith(".name")) {
          val prefix = key.substring(0, key.length - 4)
          val n = props.getProperty(key)
          result += Profile(n, readInt(prefix + "bucks", 0), readInt(prefix + "diamonds", 0), readInt(prefix + "wins", 0), readInt(prefix + "stage", 0), readInt(prefix + "coupons", 0), props.getProperty(prefix + "hero", "Prison Runner"), props.getProperty(prefix + "animation", "Heroic Run"))
        }
      }
      result.toVector.sortBy(p => (-p.wins, -p.bestStage, p.name)).take(15)
    }
  }

  final class LanRoom {
    private final class Peer(val socket: Socket, val writer: PrintWriter)
    private val peers = new CopyOnWriteArrayList[Peer]()
    private var serverSocket: ServerSocket = null
    private var clientSocket: Socket = null
    private var clientWriter: PrintWriter = null
    @volatile private var active = false
    @volatile private var listener: String => Unit = null
    @volatile private var hosting = false

    def isActive: Boolean = active
    def setListener(callback: String => Unit): Unit = { listener = callback }

    private def emit(line: String): Unit = {
      val cb = listener
      if (cb != null) SwingUtilities.invokeLater(new Runnable { override def run(): Unit = cb(line) })
    }

    private def broadcast(line: String): Unit = {
      val it = peers.iterator()
      while (it.hasNext) {
        try { it.next().writer.println(line) } catch { case _: Exception => () }
      }
    }

    def host(port: Int): String = {
      stop()
      serverSocket = new ServerSocket(port)
      active = true
      hosting = true
      val localServer = serverSocket
      val acceptThread = new Thread(new Runnable {
        override def run(): Unit = {
          while (active && !localServer.isClosed) {
            try {
              val socket = localServer.accept()
              if (peers.size() >= 12) socket.close()
              else {
                val writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream, "UTF-8"), true)
                val peer = new Peer(socket, writer)
                peers.add(peer)
                emit("SYS|A friend joined the parkour room")
                val readerThread = new Thread(new Runnable {
                  override def run(): Unit = {
                    var reader: BufferedReader = null
                    try {
                      reader = new BufferedReader(new InputStreamReader(socket.getInputStream, "UTF-8"))
                      var line = reader.readLine()
                      while (line != null && active) {
                        emit(line)
                        broadcast(line)
                        line = reader.readLine()
                      }
                    } catch { case _: Exception => emit("SYS|A friend disconnected") }
                    finally {
                      try { if (reader != null) reader.close() } catch { case _: Exception => () }
                      peers.remove(peer)
                      try { socket.close() } catch { case _: Exception => () }
                    }
                  }
                }, "Bixuu-Prison-Peer")
                readerThread.setDaemon(true)
                readerThread.start()
              }
            } catch { case _: Exception => if (active) emit("SYS|Room listener stopped") }
          }
        }
      }, "Bixuu-Prison-Host")
      acceptThread.setDaemon(true)
      acceptThread.start()
      InetAddress.getLocalHost.getHostAddress
    }

    def join(ip: String, port: Int): Unit = {
      stop()
      clientSocket = new Socket(ip.trim, port)
      clientWriter = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream, "UTF-8"), true)
      active = true
      hosting = false
      val socket = clientSocket
      val readerThread = new Thread(new Runnable {
        override def run(): Unit = {
          var reader: BufferedReader = null
          try {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream, "UTF-8"))
            var line = reader.readLine()
            while (line != null && active) { emit(line); line = reader.readLine() }
          } catch { case _: Exception => emit("SYS|Connection ended") }
          finally { try { if (reader != null) reader.close() } catch { case _: Exception => () } }
        }
      }, "Bixuu-Prison-Client")
      readerThread.setDaemon(true)
      readerThread.start()
    }

    def send(line: String): Unit = {
      if (!active) return
      if (hosting) broadcast(line)
      else if (clientWriter != null) clientWriter.println(line)
    }

    def stop(): Unit = {
      active = false
      try { if (serverSocket != null) serverSocket.close() } catch { case _: Exception => () }
      try { if (clientSocket != null) clientSocket.close() } catch { case _: Exception => () }
      try { if (clientWriter != null) clientWriter.close() } catch { case _: Exception => () }
      val it = peers.iterator()
      while (it.hasNext) { try { it.next().socket.close() } catch { case _: Exception => () } }
      peers.clear()
      serverSocket = null
      clientSocket = null
      clientWriter = null
      hosting = false
    }
  }

  final class MainFrame extends JFrame("BIXUU PRISON ESCAPE ? STORY OBBY") {
    private val cards = new java.awt.CardLayout()
    private val root = new JPanel(cards)
    private val screenPanels = mutable.Map[String, JPanel]()
    private val lan = new LanRoom()
    private var currentProfile: Profile = null
    private var selectedHero = "Prison Runner"
    private var selectedAnimation = "Heroic Run"
    private var currentGame: ParkourPanel = null
    private var storyTimer: Timer = null

    private val bg = new Color(12, 19, 37)
    private val panelBg = new Color(22, 32, 55)
    private val cyan = new Color(69, 224, 225)
    private val gold = new Color(255, 207, 92)

    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
    setSize(1220, 790)
    setMinimumSize(new Dimension(1000, 680))
    setLocationRelativeTo(null)
    setContentPane(root)
    addWindowListener(new WindowAdapter {
      override def windowClosing(e: WindowEvent): Unit = {
        if (currentGame != null) currentGame.stopGame()
        if (storyTimer != null) storyTimer.stop()
        lan.stop()
      }
    })
    showLogin()

    private def styleButton(button: JButton): JButton = {
      button.setFont(new Font("SansSerif", Font.BOLD, 16))
      button.setForeground(Color.WHITE)
      button.setBackground(new Color(37, 91, 128))
      button.setFocusPainted(false)
      button.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(cyan, 1), BorderFactory.createEmptyBorder(10, 16, 10, 16)))
      button.setOpaque(true)
      button
    }

    private def makeButton(text: String)(action: => Unit): JButton = {
      val button = styleButton(new JButton(text))
      button.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = action })
      button
    }

    private def heading(text: String): JLabel = {
      val label = new JLabel(text, SwingConstants.CENTER)
      label.setForeground(gold)
      label.setFont(new Font("SansSerif", Font.BOLD, 30))
      label
    }

    private def basePanel(title: String): JPanel = {
      val panel = new JPanel(new BorderLayout(12, 12))
      panel.setBackground(bg)
      panel.setBorder(BorderFactory.createEmptyBorder(22, 28, 22, 28))
      panel.add(heading(title), BorderLayout.NORTH)
      panel
    }

    private def addCard(name: String, panel: JPanel): Unit = {
      screenPanels.get(name).foreach(oldPanel => root.remove(oldPanel))
      screenPanels.update(name, panel)
      root.add(panel, name)
      root.revalidate()
      root.repaint()
    }
    private def showCard(name: String): Unit = cards.show(root, name)

    private def showLogin(): Unit = {
      val panel = basePanel("BIXUU PRISON ESCAPE")
      val content = new JPanel()
      content.setOpaque(false)
      content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS))
      val subtitle = new JLabel("A CARTOON STORY OBBY ? CITY TAG ? PRISON STORY ? SKY SQUARE TOWER ? TROPHY")
      subtitle.setForeground(new Color(186, 215, 234))
      subtitle.setAlignmentX(0.5f)
      subtitle.setFont(new Font("SansSerif", Font.BOLD, 14))
      val nameField = new JTextField(20)
      val passwordField = new JPasswordField(20)
      val nameLabel = new JLabel("PLAYER NAME")
      val passLabel = new JLabel("PASSWORD")
      nameLabel.setForeground(Color.WHITE)
      passLabel.setForeground(Color.WHITE)
      val form = new JPanel(new java.awt.GridLayout(4, 1, 8, 8))
      form.setOpaque(false)
      form.add(nameLabel)
      form.add(nameField)
      form.add(passLabel)
      form.add(passwordField)
      val createButton = makeButton("CREATE ACCOUNT") {
        val passwordChars = passwordField.getPassword
        val pw = new String(passwordChars)
        val ok = LocalStore.create(nameField.getText, pw)
        java.util.Arrays.fill(passwordChars, 0.toChar)
        passwordField.setText("")
        if (ok) JOptionPane.showMessageDialog(this, "Account created. Now click LOGIN.")
        else JOptionPane.showMessageDialog(this, "Use a new name (3+ characters) and password (4+ characters).")
      }
      val loginButton = makeButton("LOGIN") {
        val passwordChars = passwordField.getPassword
        val pw = new String(passwordChars)
        val result = LocalStore.login(nameField.getText, pw)
        java.util.Arrays.fill(passwordChars, 0.toChar)
        passwordField.setText("")
        result match {
          case Some(profile) => currentProfile = profile; selectedHero = profile.hero; selectedAnimation = profile.animation; showLobby()
          case None => JOptionPane.showMessageDialog(this, "Login not found. Create your account first or check your details.")
        }
      }
      val buttons = new JPanel()
      buttons.setOpaque(false)
      buttons.add(createButton)
      buttons.add(loginButton)
      content.add(Box.createVerticalGlue())
      content.add(subtitle)
      content.add(Box.createVerticalStrut(28))
      content.add(form)
      content.add(Box.createVerticalStrut(18))
      content.add(buttons)
      content.add(Box.createVerticalGlue())
      panel.add(content, BorderLayout.CENTER)
      addCard("login", panel)
      showCard("login")
    }

    private def showLobby(): Unit = {
      val panel = basePanel("BIXUU PRISON ESCAPE ? MAIN LOBBY")
      val info = new JLabel("PLAYER: " + currentProfile.name + "     BUCKS: " + currentProfile.bucks + "     DIAMONDS: " + currentProfile.diamonds + "     TROPHIES: " + currentProfile.wins, SwingConstants.CENTER)
      info.setForeground(Color.WHITE)
      info.setFont(new Font("SansSerif", Font.BOLD, 15))
      val grid = new JPanel(new java.awt.GridLayout(3, 3, 14, 14))
      grid.setOpaque(false)
      grid.add(makeButton("? START PRISON STORY") { showStory() })
      grid.add(makeButton("? QUICK PARKOUR") { startGame() })
      grid.add(makeButton("? HERO & ANIMATION") { showHero() })
      grid.add(makeButton("? TASKS & REWARDS") { showTasks() })
      grid.add(makeButton("? WINNING LIST") { showWinners() })
      grid.add(makeButton("? MULTIPLAYER ROOM") { showMultiplayer() })
      grid.add(makeButton("? GAME STORY") { showStoryInfo() })
      grid.add(makeButton("CONTROLS") { showControls() })
      grid.add(makeButton("CLOSE GAME") { if (currentGame != null) currentGame.stopGame(); lan.stop(); dispose() })
      val center = new JPanel(new BorderLayout(10, 20))
      center.setOpaque(false)
      val brand = new JLabel("CLIMB THE SQUARE OBBY TOWER ? REACH THE TROPHY ? ENTER THE WINNING LIST", SwingConstants.CENTER)
      brand.setForeground(cyan)
      brand.setFont(new Font("SansSerif", Font.BOLD, 15))
      center.add(info, BorderLayout.NORTH)
      center.add(grid, BorderLayout.CENTER)
      center.add(brand, BorderLayout.SOUTH)
      panel.add(center, BorderLayout.CENTER)
      addCard("lobby", panel)
      showCard("lobby")
    }

    private def showStoryInfo(): Unit = {
      val panel = basePanel("THE PRISON STORY")
      val text = new JLabel("<html><div style='text-align:center;width:760px'>You are a young explorer in a colourful city. A cartoon Sky Warden tags you during a playful checkpoint challenge.<br><br>A friendly transport pod takes you to Bixuu Training Prison, a fantasy obstacle-course fortress.<br><br>Your challenge is to climb the magical square platforms, cross cloud bridges, bounce over slime pads and reach the golden trophy. This is a fictional arcade obby, not a real-world escape guide.</div></html>", SwingConstants.CENTER)
      text.setForeground(Color.WHITE)
      text.setFont(new Font("SansSerif", Font.PLAIN, 18))
      panel.add(text, BorderLayout.CENTER)
      panel.add(makeButton("BACK TO LOBBY") { showLobby() }, BorderLayout.SOUTH)
      addCard("storyInfo", panel)
      showCard("storyInfo")
    }

    private def showStory(): Unit = {
      if (storyTimer != null) storyTimer.stop()
      val panel = basePanel("PRISON ARRIVAL ? STORY MODE")
      val visual = new StoryVisualPanel()
      val message = new JLabel("CITY CHECKPOINT: A cartoon Sky Warden spots you!", SwingConstants.CENTER)
      message.setForeground(Color.WHITE)
      message.setFont(new Font("SansSerif", Font.BOLD, 16))
      val skip = makeButton("SKIP STORY ? START OBBY") { if (storyTimer != null) storyTimer.stop(); startGame() }
      val bottom = new JPanel(new BorderLayout(10, 8))
      bottom.setOpaque(false)
      bottom.add(message, BorderLayout.CENTER)
      bottom.add(skip, BorderLayout.EAST)
      panel.add(visual, BorderLayout.CENTER)
      panel.add(bottom, BorderLayout.SOUTH)
      addCard("story", panel)
      showCard("story")
      val lines = Vector(
        "CITY CHECKPOINT: A cartoon Sky Warden tags you in a playful challenge.",
        "WARDEN ESCORT: A friendly transport pod takes you to Bixuu Training Prison.",
        "PRISON ARRIVAL: The gate opens into a colourful fantasy obstacle world.",
        "THE CHALLENGE: Cross giant square platforms, bounce pads and cloud bridges.",
        "THE PRIZE: Reach the highest tower, claim the golden trophy and join the Winning List!"
      )
      var step = 0
      storyTimer = new Timer(1900, new ActionListener {
        override def actionPerformed(e: ActionEvent): Unit = {
          if (step < lines.length) {
            message.setText(lines(step))
            visual.setSceneStep(step)
            step += 1
          } else {
            storyTimer.stop()
            startGame()
          }
        }
      })
      visual.setSceneStep(0)
      storyTimer.start()
    }

    final class StoryVisualPanel extends JPanel {
      private var sceneStep = 0
      setPreferredSize(new Dimension(900, 460))
      setBackground(new Color(12, 22, 43))
      def setSceneStep(value: Int): Unit = { sceneStep = value; repaint() }

      override def paintComponent(graphics: Graphics): Unit = {
        super.paintComponent(graphics)
        val g = graphics.create().asInstanceOf[Graphics2D]
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        g.setPaint(new GradientPaint(0, 0, new Color(13, 22, 48), 0, getHeight, new Color(57, 91, 123)))
        g.fillRect(0, 0, getWidth, getHeight)
        var i = 0
        while (i < 9) {
          val bx = i * (getWidth / 9) + 12
          val bh = 90 + ((i * 37) % 110)
          g.setColor(new Color(30 + (i * 7) % 25, 48 + (i * 5) % 28, 75 + (i * 9) % 35))
          g.fillRect(bx, getHeight - bh - 45, 70, bh)
          g.setColor(new Color(91, 204, 226, 110))
          var wy = getHeight - bh - 30
          while (wy < getHeight - 65) { g.fillRect(bx + 12, wy, 8, 8); g.fillRect(bx + 38, wy, 8, 8); wy += 24 }
          i += 1
        }
        g.setColor(new Color(20, 35, 49))
        g.fillRect(0, getHeight - 45, getWidth, 45)
        // Cartoon explorer, drawn as a simple block-style character.
        val heroX = if (sceneStep < 2) getWidth / 2 - 120 else getWidth / 2 - 35
        val heroY = getHeight - 145
        g.setColor(new Color(62, 205, 220)); g.fillRoundRect(heroX - 18, heroY, 36, 55, 8, 8)
        g.setColor(new Color(238, 200, 160)); g.fillOval(heroX - 17, heroY - 34, 34, 34)
        g.setColor(new Color(28, 42, 69)); g.fillRoundRect(heroX - 20, heroY - 39, 40, 13, 6, 6)
        g.setColor(new Color(25, 37, 56)); g.fillRect(heroX - 15, heroY + 52, 11, 34); g.fillRect(heroX + 4, heroY + 52, 11, 34)
        if (sceneStep <= 1) {
          g.setColor(new Color(90, 199, 245)); g.fillRoundRect(getWidth / 2 + 65, getHeight - 160, 105, 58, 18, 18)
          g.setColor(new Color(172, 239, 255)); g.fillOval(getWidth / 2 + 85, getHeight - 151, 25, 18)
          g.fillOval(getWidth / 2 + 126, getHeight - 151, 25, 18)
          g.setColor(new Color(255, 204, 87)); g.fillOval(getWidth / 2 + 104, getHeight - 187, 30, 30)
          g.setColor(Color.WHITE); g.setFont(new Font("SansSerif", Font.BOLD, 15)); g.drawString("SKY WARDEN", getWidth / 2 + 75, getHeight - 171)
        } else {
          g.setColor(new Color(65, 84, 111)); g.fillRect(getWidth - 260, getHeight - 290, 190, 245)
          g.setColor(new Color(104, 204, 225)); g.fillRect(getWidth - 235, getHeight - 255, 140, 42)
          g.setColor(new Color(20, 31, 52)); g.fillRect(getWidth - 220, getHeight - 155, 45, 110); g.fillRect(getWidth - 150, getHeight - 155, 45, 110)
          g.setColor(gold); g.setFont(new Font("SansSerif", Font.BOLD, 17)); g.drawString("BIXUU TRAINING PRISON", getWidth - 260, getHeight - 305)
        }
        g.setColor(new Color(255, 219, 130)); g.setFont(new Font("SansSerif", Font.BOLD, 18))
        val caption = if (sceneStep < 2) "CITY CHECKPOINT" else "TRAINING PRISON ? FANTASY OBBY"
        g.drawString(caption, 28, 38)
        g.dispose()
      }
    }

    private def showHero(): Unit = {
      val panel = basePanel("CHOOSE YOUR HERO & ANIMATION")
      val content = new JPanel(new java.awt.GridLayout(5, 1, 10, 10))
      content.setOpaque(false)
      val heroBox = new JComboBox[String]()
      heroBox.addItem("Prison Runner")
      heroBox.addItem("Neon Ninja")
      heroBox.addItem("Sky Builder")
      heroBox.addItem("Robot Explorer")
      heroBox.addItem("Crystal Guardian")
      heroBox.addItem("Cloud Jumper")
      heroBox.setSelectedItem(currentProfile.hero)
      val animBox = new JComboBox[String]()
      animBox.addItem("Heroic Run")
      animBox.addItem("Ninja Vault")
      animBox.addItem("Robot Glide")
      animBox.addItem("Power Sprint")
      animBox.setSelectedItem(currentProfile.animation)
      val heroLabel = new JLabel("CHOOSE CHARACTER")
      val animLabel = new JLabel("CHOOSE ANIMATION")
      heroLabel.setForeground(Color.WHITE)
      animLabel.setForeground(Color.WHITE)
      val preview = new JLabel("3D-STYLE BLOCK HERO ? CUSTOM COLOURS ? PARKOUR READY", SwingConstants.CENTER)
      preview.setForeground(cyan)
      content.add(heroLabel); content.add(heroBox); content.add(animLabel); content.add(animBox); content.add(preview)
      val saveButton = makeButton("SAVE HERO") {
        selectedHero = heroBox.getSelectedItem.toString
        selectedAnimation = animBox.getSelectedItem.toString
        currentProfile = currentProfile.copy(hero = selectedHero, animation = selectedAnimation)
        LocalStore.save(currentProfile)
        JOptionPane.showMessageDialog(this, "Hero and animation saved!")
        showLobby()
      }
      panel.add(content, BorderLayout.CENTER)
      panel.add(saveButton, BorderLayout.SOUTH)
      addCard("hero", panel)
      showCard("hero")
    }

    private def showTasks(): Unit = {
      val panel = basePanel("DAILY TASKS & REWARDS")
      val text = new JLabel("<html><div style='text-align:center'>TASK 1 ? Reach platform 5: +50 Bixuu Bucks<br><br>TASK 2 ? Reach platform 10: +100 Bixuu Bucks<br><br>TASK 3 ? Collect 10 coins: +1 Card Room Coupon<br><br>FINAL TASK ? Reach the Golden Trophy: +500 Bucks, +25 Diamonds and +1 Coupon</div></html>", SwingConstants.CENTER)
      text.setForeground(Color.WHITE)
      text.setFont(new Font("SansSerif", Font.BOLD, 18))
      panel.add(text, BorderLayout.CENTER)
      panel.add(makeButton("BACK") { showLobby() }, BorderLayout.SOUTH)
      addCard("tasks", panel)
      showCard("tasks")
    }

    private def showWinners(): Unit = {
      val panel = basePanel("BIXUU WINNING LIST")
      val text = new javax.swing.JTextArea()
      text.setEditable(false)
      text.setBackground(new Color(17, 26, 44))
      text.setForeground(Color.WHITE)
      text.setFont(new Font("Monospaced", Font.BOLD, 16))
      val list = LocalStore.winningList()
      if (list.isEmpty) text.setText("No trophies yet. Be the first winner!\n")
      else {
        var rank = 1
        list.foreach { p => text.append(rank + ". " + p.name + "   TROPHIES: " + p.wins + "   BEST STAGE: " + p.bestStage + "\n"); rank += 1 }
      }
      panel.add(new javax.swing.JScrollPane(text), BorderLayout.CENTER)
      panel.add(makeButton("BACK") { showLobby() }, BorderLayout.SOUTH)
      addCard("winners", panel)
      showCard("winners")
    }

    private def showControls(): Unit = {
      val panel = basePanel("PARKOUR CONTROLS")
      val text = new JLabel("<html><div style='text-align:center'>W A S D / ARROWS ? Move<br><br>SPACE ? Jump<br><br>SHIFT ? Dash<br><br>Mouse Drag ? Rotate Camera<br><br>Mouse Wheel ? Zoom In / Out<br><br>E ? Collect Coin / Claim Trophy<br><br>P ? Pause<br><br>B ? Return to Lobby</div></html>", SwingConstants.CENTER)
      text.setForeground(Color.WHITE)
      text.setFont(new Font("SansSerif", Font.BOLD, 18))
      panel.add(text, BorderLayout.CENTER)
      panel.add(makeButton("BACK") { showLobby() }, BorderLayout.SOUTH)
      addCard("controls", panel)
      showCard("controls")
    }

    private def showMultiplayer(): Unit = {
      val panel = basePanel("LAN FRIEND ROOM")
      val status = new JLabel("Not connected. Use a trusted local Wi-Fi network.", SwingConstants.CENTER)
      status.setForeground(Color.WHITE)
      status.setFont(new Font("SansSerif", Font.BOLD, 16))
      val hostButton = makeButton("HOST FRIEND ROOM") {
        try {
          val portText = JOptionPane.showInputDialog(this, "Room port (default 47821):", "47821")
          if (portText != null) {
            val port = try { portText.trim.toInt } catch { case _: Exception => 47821 }
            if (port < 1024 || port > 65535) JOptionPane.showMessageDialog(this, "Choose a port between 1024 and 65535.")
            else { val ip = lan.host(port); status.setText("HOSTING: " + ip + " : " + port + "  |  Share only with friends on your trusted Wi-Fi.") }
          }
        } catch { case ex: Exception => JOptionPane.showMessageDialog(this, "Could not host room: " + ex.getMessage) }
      }
      val joinButton = makeButton("JOIN FRIEND ROOM") {
        try {
          val ip = JOptionPane.showInputDialog(this, "Friend's local IP address:")
          if (ip != null && ip.trim.nonEmpty) {
            val portText = JOptionPane.showInputDialog(this, "Room port:", "47821")
            val port = try { if (portText == null) 47821 else portText.trim.toInt } catch { case _: Exception => 47821 }
            lan.join(ip.trim, port)
            status.setText("JOINED ROOM: " + ip.trim + " : " + port)
          }
        } catch { case ex: Exception => JOptionPane.showMessageDialog(this, "Could not join room: " + ex.getMessage) }
      }
      val stopButton = makeButton("DISCONNECT") { lan.stop(); status.setText("Disconnected from room.") }
      val playButton = makeButton("PLAY PARKOUR") { startGame() }
      val rows = new JPanel(new java.awt.GridLayout(4, 1, 12, 12))
      rows.setOpaque(false)
      rows.add(hostButton); rows.add(joinButton); rows.add(stopButton); rows.add(playButton)
      panel.add(rows, BorderLayout.CENTER)
      panel.add(status, BorderLayout.SOUTH)
      addCard("multi", panel)
      showCard("multi")
    }

    private def startGame(): Unit = {
      if (storyTimer != null) storyTimer.stop()
      if (currentGame != null) currentGame.stopGame()
      currentGame = new ParkourPanel(currentProfile, lan, (updated: Profile) => { currentProfile = updated; LocalStore.save(updated) }, () => { if (currentGame != null) currentGame.stopGame(); showLobby() })
      addCard("game", currentGame)
      showCard("game")
      currentGame.requestFocusInWindow()
    }
  }

  final class ParkourPanel(initialProfile: Profile, lan: LanRoom, updateProfile: Profile => Unit, onBack: () => Unit) extends JPanel {
    private val skyTop = new Color(10, 18, 43)
    private val skyBottom = new Color(49, 77, 115)
    private val cyan = new Color(80, 225, 230)
    private val gold = new Color(255, 211, 93)
    private val platforms = buildPlatforms()
    private val pressed = mutable.HashSet[Int]()
    private val collected = mutable.HashSet[Int]()
    private val remotePlayers = mutable.Map[String, RemoteAvatar]()
    private var profile = initialProfile
    private var playerX = 0.0
    private var playerY = 0.0
    private var playerZ = 0.0
    private var velocityY = 0.0
    private var grounded = true
    private var cameraYaw = 0.0
    private var cameraZoom = 1.0
    private var mouseDown = false
    private var dragX = 0
    private var checkpointX = 0.0
    private var checkpointY = 0.0
    private var checkpointZ = 0.0
    private var checkpointStage = 0
    private var bestStage = 0
    private var tick = 0
    private var dashCooldown = 0
    private var paused = false
    private var won = false
    private var pulseCooldown = 0
    private var shieldTicks = 0
    private var message = "CLIMB THE SQUARE OBBY TOWER. REACH THE GOLD TROPHY!"
    private var messageTicks = 250
    private var lastSentTick = 0
    private val gameTimer = new Timer(16, new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { updateGame(); repaint() } })

    setFocusable(true)
    setPreferredSize(new Dimension(1180, 720))
    setBackground(skyTop)
    addKeyListener(new KeyAdapter {
      override def keyPressed(e: KeyEvent): Unit = {
        pressed += e.getKeyCode
        if (e.getKeyCode == KeyEvent.VK_P || e.getKeyCode == KeyEvent.VK_ESCAPE) paused = !paused
        if (e.getKeyCode == KeyEvent.VK_B && won) onBack()
        if (e.getKeyCode == KeyEvent.VK_E && !won) interact()
      }
      override def keyReleased(e: KeyEvent): Unit = pressed -= e.getKeyCode
    })
    addMouseListener(new MouseAdapter {
      override def mousePressed(e: MouseEvent): Unit = { mouseDown = true; dragX = e.getX }
      override def mouseReleased(e: MouseEvent): Unit = { mouseDown = false }
    })
    addMouseMotionListener(new MouseMotionAdapter {
      override def mouseDragged(e: MouseEvent): Unit = {
        if (mouseDown) { cameraYaw += (e.getX - dragX).toDouble * 0.008; dragX = e.getX }
      }
    })
    addMouseWheelListener(new MouseWheelListener {
      override def mouseWheelMoved(e: MouseWheelEvent): Unit = {
        cameraZoom = math.max(0.65, math.min(1.55, cameraZoom - e.getWheelRotation.toDouble * 0.08))
        repaint()
      }
    })
    lan.setListener((line: String) => receiveNetwork(line))
    gameTimer.start()

    def stopGame(): Unit = gameTimer.stop()

    private def buildPlatforms(): Vector[Platform3D] = {
      val result = Vector.newBuilder[Platform3D]
      result += Platform3D(0, 0.0, 0.0, 0.0, 7.2, 6.0, true, false)
      var i = 1
      while (i <= 20) {
        val platformX = if (i % 4 == 0) 0.0 else if (i % 2 == 0) -1.75 else 1.75
        val platformZ = i.toDouble * 3.65
        val platformY = i.toDouble * 0.43
        result += Platform3D(i, platformX, platformY, platformZ, 3.25, 2.75, i % 5 == 0, i % 4 == 0)
        i += 1
      }
      result.result()
    }

    private def receiveNetwork(line: String): Unit = {
      if (line.startsWith("POS|")) {
        val parts = line.split("\\|", -1)
        if (parts.length >= 6) {
          try { remotePlayers.update(parts(1), RemoteAvatar(parts(1), parts(2).toDouble, parts(3).toDouble, parts(4).toDouble, parts(5).toInt)) }
          catch { case _: Exception => () }
        }
      } else if (line.startsWith("SYS|")) {
        message = line.substring(4)
        messageTicks = 200
      }
    }

    private def updateGame(): Unit = {
      if (paused || won) return
      tick += 1
      if (dashCooldown > 0) dashCooldown -= 1
      if (pulseCooldown > 0) pulseCooldown -= 1
      if (shieldTicks > 0) shieldTicks -= 1
      if (messageTicks > 0) messageTicks -= 1
      val oldY = playerY
      val forwardX = math.sin(cameraYaw)
      val forwardZ = math.cos(cameraYaw)
      val rightX = math.cos(cameraYaw)
      val rightZ = -math.sin(cameraYaw)
      val moveSpeed = if (profile.bucks > 800) 0.155 else 0.135
      if (pressed.contains(KeyEvent.VK_W) || pressed.contains(KeyEvent.VK_UP)) { playerX += forwardX * moveSpeed; playerZ += forwardZ * moveSpeed }
      if (pressed.contains(KeyEvent.VK_S) || pressed.contains(KeyEvent.VK_DOWN)) { playerX -= forwardX * moveSpeed; playerZ -= forwardZ * moveSpeed }
      if (pressed.contains(KeyEvent.VK_A) || pressed.contains(KeyEvent.VK_LEFT)) { playerX -= rightX * moveSpeed; playerZ -= rightZ * moveSpeed }
      if (pressed.contains(KeyEvent.VK_D) || pressed.contains(KeyEvent.VK_RIGHT)) { playerX += rightX * moveSpeed; playerZ += rightZ * moveSpeed }
      if (pressed.contains(KeyEvent.VK_SPACE) && grounded) { velocityY = 0.34; grounded = false }
      if (pressed.contains(KeyEvent.VK_SHIFT) && dashCooldown <= 0) { playerX += forwardX * 1.25; playerZ += forwardZ * 1.25; dashCooldown = 42 }
      if (!grounded) { velocityY -= 0.012; playerY += velocityY }
      grounded = false
      if (velocityY <= 0.0) {
        val landing = platforms.find(p => oldY >= p.topY - 0.01 && playerY <= p.topY && math.abs(playerX - p.centerX) <= p.width / 2.0 - 0.25 && math.abs(playerZ - p.centerZ) <= p.depth / 2.0 - 0.20)
        landing match {
          case Some(p) =>
            playerY = p.topY
            velocityY = 0.0
            grounded = true
            if (p.id > bestStage) { bestStage = p.id; profile = profile.copy(bestStage = math.max(profile.bestStage, bestStage)); updateProfile(profile) }
            if (p.checkpoint && p.id >= checkpointStage) { checkpointStage = p.id; checkpointX = playerX; checkpointY = playerY; checkpointZ = playerZ; message = "CHECKPOINT " + p.id + " SAVED!"; messageTicks = 150 }
            if (p.bounce && tick % 10 == 0) { velocityY = 0.26; grounded = false }
          case None => ()
        }
      }
      if (playerY < -5.0) {
        playerX = checkpointX; playerY = checkpointY; playerZ = checkpointZ; velocityY = 0.0; grounded = true
        message = "WHOOPS! RESPAWNED AT CHECKPOINT " + checkpointStage
        messageTicks = 170
      }
      platforms.foreach { p =>
        if (p.id > 0 && !collected.contains(p.id)) {
          val pickupX = p.centerX
          val pickupY = p.topY + 1.15
          val pickupZ = p.centerZ
          val dx = playerX - pickupX
          val dy = playerY + 1.0 - pickupY
          val dz = playerZ - pickupZ
          if (dx * dx + dy * dy + dz * dz < 2.0) {
            collected += p.id
            profile = profile.copy(bucks = profile.bucks + 15)
            updateProfile(profile)
            message = "+15 BIXUU BUCKS ? SQUARE COIN COLLECTED!"
            messageTicks = 130
          }
        }
      }
      if (bestStage >= 20 && playerZ > 70.0 && math.abs(playerX) < 2.0 && pressed.contains(KeyEvent.VK_E)) claimTrophy()
      if (lan.isActive && tick - lastSentTick >= 6) {
        val safeName = profile.name.replace('|', '_').replace('\n', '_')
        lan.send("POS|" + safeName + "|" + playerX + "|" + playerY + "|" + playerZ + "|" + bestStage)
        lastSentTick = tick
      }
    }

    private def interact(): Unit = {
      if (bestStage >= 20 && playerZ > 70.0 && math.abs(playerX) < 2.0) claimTrophy()
      else { message = "Collect the glowing square coins and climb to the golden trophy!"; messageTicks = 160 }
    }

    private def claimTrophy(): Unit = {
      if (!won) {
        won = true
        profile = profile.copy(bucks = profile.bucks + 500, diamonds = profile.diamonds + 25, wins = profile.wins + 1, coupons = profile.coupons + 1, bestStage = 20)
        updateProfile(profile)
        message = "TROPHY CLAIMED! YOU ARE A BIXUU PRISON ESCAPE CHAMPION!"
        messageTicks = 999999
      }
    }

    private def project(point: V3): Option[Projected] = {
      val cameraX = playerX
      val cameraY = playerY + 4.1
      val cameraZ = playerZ - 8.5 - (cameraZoom - 1.0) * 4.0
      val dx = point.px - cameraX
      val dy = point.py - cameraY
      val dz = point.pz - cameraZ
      val cosYaw = math.cos(cameraYaw)
      val sinYaw = math.sin(cameraYaw)
      val viewX = dx * cosYaw - dz * sinYaw
      val viewZ = dx * sinYaw + dz * cosYaw
      val pitch = -0.22
      val viewY = dy * math.cos(pitch) - viewZ * math.sin(pitch)
      val depth = dy * math.sin(pitch) + viewZ * math.cos(pitch)
      if (depth <= 0.45) None
      else {
        val focal = math.min(getWidth, getHeight).toDouble * 0.92 * cameraZoom
        val sx = (getWidth.toDouble / 2.0 + viewX * focal / depth).toInt
        val sy = (getHeight.toDouble * 0.53 - viewY * focal / depth).toInt
        Some(Projected(sx, sy, depth))
      }
    }

    private def shaded(base: Color, factor: Double): Color = {
      val r = math.max(0, math.min(255, (base.getRed * factor).toInt))
      val g = math.max(0, math.min(255, (base.getGreen * factor).toInt))
      val b = math.max(0, math.min(255, (base.getBlue * factor).toInt))
      new Color(r, g, b)
    }

    private def drawCube(g: Graphics2D, centerX: Double, centerY: Double, centerZ: Double, width: Double, height: Double, depth: Double, color: Color): Unit = {
      val hx = width / 2.0
      val hy = height / 2.0
      val hz = depth / 2.0
      val vertices = Vector(
        V3(centerX - hx, centerY - hy, centerZ - hz), V3(centerX + hx, centerY - hy, centerZ - hz),
        V3(centerX + hx, centerY + hy, centerZ - hz), V3(centerX - hx, centerY + hy, centerZ - hz),
        V3(centerX - hx, centerY - hy, centerZ + hz), V3(centerX + hx, centerY - hy, centerZ + hz),
        V3(centerX + hx, centerY + hy, centerZ + hz), V3(centerX - hx, centerY + hy, centerZ + hz)
      )
      val faceIndices = Vector(Vector(0, 1, 2, 3), Vector(4, 5, 6, 7), Vector(0, 1, 5, 4), Vector(3, 2, 6, 7), Vector(0, 3, 7, 4), Vector(1, 2, 6, 5))
      val faceColors = Vector(0.68, 1.12, 0.82, 0.92, 0.74, 0.86)
      val prepared = faceIndices.zipWithIndex.flatMap { item =>
        val points = item._1.map(index => project(vertices(index)))
        if (points.forall(_.isDefined)) {
          val visible = points.map(_.get)
          val averageDepth = visible.map(_.depth).sum / visible.length.toDouble
          Some((visible, averageDepth, faceColors(item._2)))
        } else None
      }.sortBy(item => -item._2)
      prepared.foreach { item =>
        val poly = new Polygon()
        item._1.foreach(p => poly.addPoint(p.sx, p.sy))
        g.setColor(shaded(color, item._3))
        g.fillPolygon(poly)
        g.setColor(new Color(5, 12, 22, 120))
        g.drawPolygon(poly)
      }
    }

    private def platformColor(id: Int): Color = id % 5 match {
      case 0 => new Color(62, 157, 186)
      case 1 => new Color(75, 122, 171)
      case 2 => new Color(98, 113, 164)
      case 3 => new Color(68, 151, 139)
      case _ => new Color(119, 112, 166)
    }

    private def drawCharacter(g: Graphics2D, px: Double, py: Double, pz: Double, base: Color, remote: Boolean): Unit = {
      val bob = if (remote) 0.0 else math.sin(tick.toDouble * 0.12) * 0.035
      drawCube(g, px, py + 1.22 + bob, pz, 0.78, 0.95, 0.48, base)
      drawCube(g, px, py + 1.92 + bob, pz + 0.02, 0.52, 0.52, 0.50, new Color(235, 202, 164))
      drawCube(g, px - 0.54, py + 1.22 + bob, pz, 0.22, 0.82, 0.24, shaded(base, 0.82))
      drawCube(g, px + 0.54, py + 1.22 + bob, pz, 0.22, 0.82, 0.24, shaded(base, 0.82))
      val legSwing = if (grounded) math.sin(tick.toDouble * 0.18) * 0.12 else 0.0
      drawCube(g, px - 0.20, py + 0.43 + legSwing, pz, 0.26, 0.76, 0.30, new Color(30, 39, 62))
      drawCube(g, px + 0.20, py + 0.43 - legSwing, pz, 0.26, 0.76, 0.30, new Color(30, 39, 62))
      drawCube(g, px, py + 2.27 + bob, pz, 0.58, 0.13, 0.58, new Color(35, 50, 75))
    }

    private def drawBackground(g: Graphics2D): Unit = {
      g.setPaint(new GradientPaint(0, 0, new Color(7, 16, 38), 0, getHeight, new Color(72, 103, 143)))
      g.fillRect(0, 0, getWidth, getHeight)
      g.setColor(new Color(255, 255, 255, 125))
      var i = 0
      while (i < 55) {
        val sx = (i * 173 + 43) % math.max(1, getWidth)
        val sy = (i * 71 + 19) % math.max(1, getHeight / 2)
        g.fillOval(sx, sy, 2, 2)
        i += 1
      }
      g.setColor(new Color(182, 213, 239, 35))
      g.fillOval(getWidth - 260, 65, 150, 150)
      g.setColor(new Color(225, 235, 245, 45))
      g.fillOval(getWidth - 245, 78, 125, 125)
    }

    private def drawWorld(g: Graphics2D): Unit = {
      drawCube(g, 0.0, -0.65, 0.0, 22.0, 1.3, 20.0, new Color(42, 62, 77))
      val visiblePlatforms = platforms.filter(p => p.centerZ > playerZ - 12.0 && p.centerZ < playerZ + 55.0).sortBy(p => -p.centerZ)
      visiblePlatforms.foreach { p =>
        drawCube(g, p.centerX, p.topY - 0.20, p.centerZ, p.width, 0.40, p.depth, platformColor(p.id))
        if (p.checkpoint) drawCube(g, p.centerX, p.topY + 0.48, p.centerZ, 0.20, 0.95, 0.20, gold)
        if (p.bounce) drawCube(g, p.centerX, p.topY + 0.18, p.centerZ, 1.15, 0.16, 0.9, new Color(70, 229, 193))
        if (p.id > 0 && !collected.contains(p.id)) drawCube(g, p.centerX, p.topY + 1.12 + math.sin(tick * 0.08 + p.id) * 0.12, p.centerZ, 0.55, 0.55, 0.55, gold)
      }
      drawCube(g, -5.0, 1.0, 8.0, 0.7, 2.1, 0.7, new Color(93, 113, 150))
      drawCube(g, -5.0, 2.35, 8.0, 0.85, 0.65, 0.85, new Color(52, 66, 94))
      drawCube(g, 5.0, 1.0, 12.0, 0.7, 2.1, 0.7, new Color(93, 113, 150))
      drawCube(g, 5.0, 2.35, 12.0, 0.85, 0.65, 0.85, new Color(52, 66, 94))
      drawCharacter(g, playerX, playerY, playerZ, new Color(69, 198, 219), false)
      remotePlayers.values.foreach(r => drawCharacter(g, r.px, r.py, r.pz, new Color(227, 166, 75), true))
      val last = platforms.last
      drawCube(g, last.centerX, last.topY + 0.85, last.centerZ + 1.2, 1.05, 1.7, 0.40, gold)
      drawCube(g, last.centerX, last.topY + 1.95, last.centerZ + 1.2, 0.75, 0.25, 0.75, gold)
    }

    private def drawHud(g: Graphics2D): Unit = {
      g.setColor(new Color(6, 12, 27, 218))
      g.fillRoundRect(14, 14, 370, 142, 18, 18)
      g.setColor(cyan)
      g.setFont(new Font("SansSerif", Font.BOLD, 19))
      g.drawString("BIXUU PRISON ESCAPE", 29, 42)
      g.setColor(Color.WHITE)
      g.setFont(new Font("SansSerif", Font.BOLD, 13))
      g.drawString("PLAYER: " + profile.name, 29, 66)
      g.drawString("STAGE: " + bestStage + "/20    COINS: " + collected.size + "/20", 29, 88)
      g.drawString("BUCKS: " + profile.bucks + "    WINS: " + profile.wins, 29, 110)
      g.drawString("CHECKPOINT: " + checkpointStage + "    FRIENDS: " + remotePlayers.size, 29, 132)
      g.setColor(new Color(8, 16, 30, 190))
      g.fillRoundRect(18, getHeight - 48, getWidth - 36, 30, 12, 12)
      g.setColor(new Color(222, 234, 247))
      g.setFont(new Font("SansSerif", Font.BOLD, 12))
      g.drawString("WASD MOVE  ?  SPACE JUMP  ?  SHIFT DASH  ?  E CLAIM TROPHY  ?  MOUSE DRAG ROTATE  ?  WHEEL ZOOM", 29, getHeight - 28)
      if (messageTicks > 0) {
        g.setColor(gold)
        g.setFont(new Font("SansSerif", Font.BOLD, 16))
        g.drawString(message, 410, 36)
      }
      if (paused || won) {
        g.setColor(new Color(5, 9, 22, 205))
        g.fillRect(0, 0, getWidth, getHeight)
        g.setFont(new Font("SansSerif", Font.BOLD, 38))
        

        g.setFont(new Font("SansSerif", Font.BOLD, 18))
        g.setColor(Color.WHITE)

      }
    }

    private def drawCentered(g: Graphics2D, text: String, centerX: Int, baseY: Int): Unit = {
      val metrics = g.getFontMetrics
      g.drawString(text, centerX - metrics.stringWidth(text) / 2, baseY)
    }

    override def paintComponent(graphics: Graphics): Unit = {
      super.paintComponent(graphics)
      val g = graphics.create().asInstanceOf[Graphics2D]
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
      g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
      drawBackground(g)
      drawWorld(g)
      drawHud(g)
      g.dispose()
    }

    requestFocusInWindow()
  }
}

BixuuPrisonEscape.main(Array[String]())