Code Sketch


BixuuPrisonEscape trieal
By: Mhalsakant School
Category: Programming
import java.awt.{BasicStroke, BorderLayout, Color, Dimension, Font, Graphics, Graphics2D, Polygon, RenderingHints}
import java.awt.event.{ActionEvent, ActionListener, KeyAdapter, KeyEvent, MouseAdapter, MouseEvent, MouseMotionAdapter, WindowAdapter, WindowEvent}
import java.awt.geom.{Ellipse2D, RoundRectangle2D}
import java.io.{BufferedReader, InputStreamReader, OutputStreamWriter, PrintWriter, File, FileInputStream, FileOutputStream}
import java.net.{InetAddress, InetSocketAddress, ServerSocket, Socket, SocketException}
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
import scala.util.Random

object BixuuPrisonEscape {
  final case class Profile(name: String, bucks: Int, diamonds: Int, escapes: Int, bestStage: Int, coupons: Int)
  final case class RemotePlayer(name: String, posX: Double, posY: Double, posZ: Double, stage: Int, role: String)
  final case class V3(px: Double, py: Double, pz: Double)
  final case class ScreenPoint(sx: Int, sy: Int, depth: Double, scale: Double)
  final case class Platform(posX: Double, topY: Double, posZ: Double, width: Double, depth: Double, checkpoint: Boolean)
  final case class Pickup(posX: Double, posY: Double, posZ: Double, kind: String, value: Int)
  final case class GuardBot(posX: Double, baseZ: Double, range: Double, phase: Double, var stun: Int)

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

  object LocalProfiles {
    private val dataFile = new File(System.getProperty("user.home"), ".bixuu_prison_escape_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 safeKey(name: String): String = name.trim.toLowerCase.replaceAll("[^a-z0-9_-]", "_").take(24)

    private def hash(text: String): String = {
      val digest = MessageDigest.getInstance("SHA-256")
      val bytes = digest.digest(text.getBytes("UTF-8"))
      val builder = new StringBuilder
      var i = 0
      while (i < bytes.length) {
        val unsignedValue = bytes(i) & 0xff
        val hexValue = Integer.toHexString(unsignedValue)
        if (hexValue.length == 1) builder.append('0')
        builder.append(hexValue)
        i += 1
      }
      builder.toString
    }

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

    private def saveAll(): Unit = {
      var out: FileOutputStream = null
      try {
        out = new FileOutputStream(dataFile)
        props.store(out, "Bixuu Prison Escape local 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 = "account." + safeKey(clean) + "."
        if (props.getProperty(key + "name") != null) false
        else {
          props.setProperty(key + "name", clean)
          props.setProperty(key + "passwordHash", hash(password))
          props.setProperty(key + "bucks", "250")
          props.setProperty(key + "diamonds", "20")
          props.setProperty(key + "escapes", "0")
          props.setProperty(key + "bestStage", "0")
          props.setProperty(key + "coupons", "0")
          saveAll()
          true
        }
      }
    }

    def login(name: String, password: String): Option[Profile] = synchronized {
      loadOnce()
      val key = "account." + safeKey(name) + "."
      val storedName = props.getProperty(key + "name")
      val storedHash = props.getProperty(key + "passwordHash")
      if (storedName != null && storedHash != null && storedHash == hash(password)) {
        Some(Profile(storedName, readInt(key + "bucks", 250), readInt(key + "diamonds", 20), readInt(key + "escapes", 0), readInt(key + "bestStage", 0), readInt(key + "coupons", 0)))
      } else None
    }

    def save(profile: Profile): Unit = synchronized {
      loadOnce()
      val key = "account." + safeKey(profile.name) + "."
      props.setProperty(key + "bucks", profile.bucks.toString)
      props.setProperty(key + "diamonds", profile.diamonds.toString)
      props.setProperty(key + "escapes", profile.escapes.toString)
      props.setProperty(key + "bestStage", profile.bestStage.toString)
      props.setProperty(key + "coupons", profile.coupons.toString)
      saveAll()
    }

    def leaderboard(): Vector[Profile] = synchronized {
      loadOnce()
      val all = mutable.ArrayBuffer[Profile]()
      val names = props.stringPropertyNames().iterator()
      while (names.hasNext) {
        val key = names.next()
        if (key.startsWith("account.") && key.endsWith(".name")) {
          val name = props.getProperty(key)
          val prefix = key.substring(0, key.length - 4)
          all += Profile(name, readInt(prefix + "bucks", 0), readInt(prefix + "diamonds", 0), readInt(prefix + "escapes", 0), readInt(prefix + "bestStage", 0), readInt(prefix + "coupons", 0))
        }
      }
      all.toVector.sortBy(p => (-p.escapes, -p.bestStage, p.name)).take(15)
    }
  }

  final class LanSession {
    private var serverSocket: ServerSocket = null
    private var clientSocket: Socket = null
    private var clientWriter: PrintWriter = null
    private val peerSockets = new CopyOnWriteArrayList[Socket]()
    private val peerWriters = new CopyOnWriteArrayList[PrintWriter]()
    @volatile private var running = false
    @volatile private var messageHandler: String => Unit = null

    private def notifyLine(line: String): Unit = {
      val handler = messageHandler
      if (handler != null) SwingUtilities.invokeLater(new Runnable {
        override def run(): Unit = handler(line)
      })
    }

    private def broadcast(line: String, except: PrintWriter): Unit = {
      val iterator = peerWriters.iterator()
      while (iterator.hasNext) {
        val writer = iterator.next()
        if (writer != except) writer.println(line)
      }
    }

    private def startReader(sock: Socket, writer: PrintWriter, hostSide: Boolean): Unit = {
      val thread = new Thread(new Runnable {
        override def run(): Unit = {
          var reader: BufferedReader = null
          try {
            reader = new BufferedReader(new InputStreamReader(sock.getInputStream, "UTF-8"))
            var line = reader.readLine()
            while (line != null && running) {
              notifyLine(line)
              if (hostSide) broadcast(line, writer)
              line = reader.readLine()
            }
          } catch { case _: Exception => notifyLine("SYS|A player disconnected") }
          finally {
            try { if (reader != null) reader.close() } catch { case _: Exception => () }
            if (hostSide) {
              peerSockets.remove(sock)
              peerWriters.remove(writer)
              try { sock.close() } catch { case _: Exception => () }
            }
          }
        }
      }, "Bixuu-Prison-Peer-Reader")
      thread.setDaemon(true)
      thread.start()
    }

    def host(port: Int, handler: String => Unit): String = {
      stop()
      messageHandler = handler
      serverSocket = new ServerSocket(port)
      running = true
      val localServer = serverSocket
      val acceptThread = new Thread(new Runnable {
        override def run(): Unit = {
          while (running && !localServer.isClosed) {
            try {
              val sock = localServer.accept()
              if (peerSockets.size() >= 12) sock.close()
              else {
                val writer = new PrintWriter(new OutputStreamWriter(sock.getOutputStream, "UTF-8"), true)
                peerSockets.add(sock)
                peerWriters.add(writer)
                notifyLine("SYS|A friend joined the prison escape room")
                startReader(sock, writer, true)
              }
            } catch { case _: Exception => if (running) notifyLine("SYS|Host listener stopped") }
          }
        }
      }, "Bixuu-Prison-Host")
      acceptThread.setDaemon(true)
      acceptThread.start()
      InetAddress.getLocalHost.getHostAddress
    }

    def join(ip: String, port: Int, handler: String => Unit): Unit = {
      stop()
      messageHandler = handler
      val sock = new Socket()
      sock.connect(new InetSocketAddress(ip, port), 3000)
      clientSocket = sock
      clientWriter = new PrintWriter(new OutputStreamWriter(sock.getOutputStream, "UTF-8"), true)
      running = true
      startReader(sock, clientWriter, false)
      send("SYS|A friend joined the prison escape room")
    }

    def send(message: String): Unit = {
      val safe = message.replace("\n", " ").replace("|", "/").take(220)
      if (clientWriter != null) clientWriter.println(safe)
      else broadcast(safe, null)
    }

    def stop(): Unit = {
      running = false
      try { if (clientWriter != null) clientWriter.close() } catch { case _: Exception => () }
      try { if (clientSocket != null) clientSocket.close() } catch { case _: Exception => () }
      try { if (serverSocket != null) serverSocket.close() } catch { case _: Exception => () }
      val socketIterator = peerSockets.iterator()
      while (socketIterator.hasNext) { try { socketIterator.next().close() } catch { case _: Exception => () } }
      peerSockets.clear()
      peerWriters.clear()
      clientWriter = null
      clientSocket = null
      serverSocket = null
      messageHandler = null
    }
  }

  final class MainFrame extends JFrame("BIXUU PRISON ESCAPE | 3D-STYLE CO-OP OBBY") {
    private val root = new JPanel(new BorderLayout())
    root.setBackground(new Color(9, 16, 31))
    root.setOpaque(true)
    private val network = new LanSession()
    private var currentProfile: Profile = null
    private var selectedAvatar = "JAILBREAK RUNNER"
    private var selectedMotion = "NINJA VAULT"
    private var activeGame: PrisonGamePanel = null
    private var currentMode = "SOLO"

    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
    setSize(1180, 790)
    setMinimumSize(new Dimension(980, 700))
    setLocationRelativeTo(null)
    setContentPane(root)
    addWindowListener(new WindowAdapter {
      override def windowClosing(event: WindowEvent): Unit = {
        if (activeGame != null) activeGame.stopGame()
        network.stop()
      }
    })

    private def styleButton(button: JButton): JButton = {
      button.setFont(new Font("SansSerif", Font.BOLD, 15))
      button.setForeground(Color.WHITE)
      button.setBackground(new Color(29, 49, 82))
      button.setFocusPainted(false)
      button.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(new Color(73, 211, 218), 1), BorderFactory.createEmptyBorder(10, 16, 10, 16)))
      button
    }

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

    private def titleLabel(text: String, size: Int): JLabel = {
      val label = new JLabel(text, SwingConstants.CENTER)
      label.setForeground(new Color(231, 248, 255))
      label.setFont(new Font("SansSerif", Font.BOLD, size))
      label
    }

    private def panel(background: Color): JPanel = {
      val p = new JPanel()
      p.setBackground(background)
      p
    }

    private def showLogin(): Unit = {
      if (activeGame != null) { activeGame.stopGame(); activeGame = null }
      network.stop()
      root.removeAll()
      val page = panel(new Color(9, 16, 31))
      page.setLayout(new BoxLayout(page, BoxLayout.Y_AXIS))
      page.add(Box.createVerticalGlue())
      page.add(titleLabel("BIXUU PRISON ESCAPE", 34))
      page.add(Box.createVerticalStrut(8))
      page.add(titleLabel("BREAK OUT ? SOLVE PUZZLES ? REACH THE SKY TROPHY", 14))
      page.add(Box.createVerticalStrut(25))
      val form = panel(new Color(19, 31, 53))
      form.setLayout(new BoxLayout(form, BoxLayout.Y_AXIS))
      form.setBorder(BorderFactory.createEmptyBorder(22, 36, 22, 36))
      val nameField = new JTextField(20)
      val passwordField = new JPasswordField(20)
      nameField.setMaximumSize(new Dimension(330, 38))
      passwordField.setMaximumSize(new Dimension(330, 38))
      nameField.setFont(new Font("SansSerif", Font.PLAIN, 16))
      passwordField.setFont(new Font("SansSerif", Font.PLAIN, 16))
      form.add(titleLabel("CREATE ACCOUNT OR LOGIN", 18))
      form.add(Box.createVerticalStrut(14))
      val nameLabel = new JLabel("PLAYER NAME")
      nameLabel.setForeground(Color.WHITE)
      val passLabel = new JLabel("PASSWORD (LOCAL PROFILE)")
      passLabel.setForeground(Color.WHITE)
      form.add(nameLabel)
      form.add(nameField)
      form.add(Box.createVerticalStrut(10))
      form.add(passLabel)
      form.add(passwordField)
      form.add(Box.createVerticalStrut(18))
      val actions = new JPanel(new java.awt.GridLayout(1, 2, 12, 0))
      actions.setOpaque(false)
      actions.add(makeButton("CREATE ACCOUNT") {
        val user = nameField.getText.trim
        val pass = new String(passwordField.getPassword)
        if (LocalProfiles.create(user, pass)) JOptionPane.showMessageDialog(this, "Account created. Now click LOGIN.")
        else JOptionPane.showMessageDialog(this, "Use a new name (3+ letters) and password (4+ characters).")
      })
      actions.add(makeButton("LOGIN") {
        val user = nameField.getText.trim
        val pass = new String(passwordField.getPassword)
        LocalProfiles.login(user, pass) match {
          case Some(profile) => currentProfile = profile; showLobby()
          case None => JOptionPane.showMessageDialog(this, "Login not found. Create an account first or check your password.")
        }
      })
      form.add(actions)
      page.add(form)
      page.add(Box.createVerticalStrut(20))
      page.add(titleLabel("Offline local accounts ? Optional LAN friend rooms ? Fictional arcade escape", 12))
      page.add(Box.createVerticalGlue())
      root.add(page, BorderLayout.CENTER)
      root.revalidate()
      root.repaint()
    }

    private def showLobby(): Unit = {
      root.removeAll()
      val page = panel(new Color(9, 16, 31))
      page.setLayout(new BorderLayout(12, 12))
      val header = panel(new Color(16, 29, 51))
      header.setLayout(new BorderLayout())
      header.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 20))
      header.add(titleLabel("BIXUU PRISON ESCAPE", 28), BorderLayout.CENTER)
      val profileText = new JLabel("PLAYER: " + currentProfile.name + "   |   BIXUU BUCKS: " + currentProfile.bucks + "   |   DIAMONDS: " + currentProfile.diamonds + "   |   ESCAPES: " + currentProfile.escapes)
      profileText.setForeground(new Color(117, 231, 227))
      profileText.setFont(new Font("SansSerif", Font.BOLD, 13))
      header.add(profileText, BorderLayout.SOUTH)
      page.add(header, BorderLayout.NORTH)

      val content = panel(new Color(9, 16, 31))
      content.setLayout(new BorderLayout(16, 16))
      val left = panel(new Color(18, 32, 55))
      left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS))
      left.setBorder(BorderFactory.createEmptyBorder(22, 22, 22, 22))
      left.add(titleLabel("CHOOSE YOUR RUNNER", 18))
      left.add(Box.createVerticalStrut(16))
      val avatarNames = Vector("JAILBREAK RUNNER", "NEON SCOUT", "IRON BUILDER", "SKY VAULTER")
      val avatarSelector = new JComboBox[String](avatarNames.toArray)
      avatarSelector.setFont(new Font("SansSerif", Font.BOLD, 14))
      avatarSelector.setMaximumSize(new Dimension(300, 38))
      avatarSelector.setSelectedItem(selectedAvatar)
      avatarSelector.addActionListener(new ActionListener { override def actionPerformed(event: ActionEvent): Unit = selectedAvatar = avatarSelector.getSelectedItem.toString })
      left.add(avatarSelector)
      left.add(Box.createVerticalStrut(12))
      val motions = Vector("NINJA VAULT", "HEROIC RUN", "ROBOT HOP", "QUICK DASH")
      val motionSelector = new JComboBox[String](motions.toArray)
      motionSelector.setMaximumSize(new Dimension(300, 38))
      motionSelector.setFont(new Font("SansSerif", Font.BOLD, 14))
      motionSelector.setSelectedItem(selectedMotion)
      motionSelector.addActionListener(new ActionListener { override def actionPerformed(event: ActionEvent): Unit = selectedMotion = motionSelector.getSelectedItem.toString })
      left.add(new JLabel("  ANIMATION STYLE"))
      left.add(motionSelector)
      left.add(Box.createVerticalStrut(20))
      left.add(titleLabel("MISSION OBJECTIVES", 16))
      val objectives = new JLabel("<html><div style='color:#d9efff'>? Collect 3 energy keycards<br>? Rescue 2 friendly bots<br>? Open the sky exit<br>? Climb the square parkour tower<br>? Claim the top trophy</div></html>")
      left.add(objectives)
      left.add(Box.createVerticalGlue())
      left.add(makeButton("PRISON STORY") { showStory() })
      left.add(Box.createVerticalStrut(8))
      left.add(makeButton("WINNING LIST") { showWinningList() })
      left.add(Box.createVerticalStrut(8))
      left.add(makeButton("CARD ROOM COUPON") { showCouponRoom() })

      val right = panel(new Color(12, 22, 40))
      right.setLayout(new BoxLayout(right, BoxLayout.Y_AXIS))
      right.setBorder(BorderFactory.createEmptyBorder(24, 24, 24, 24))
      right.add(titleLabel("SELECT GAME MODE", 22))
      right.add(Box.createVerticalStrut(24))
      right.add(makeButton("SOLO PRISON ESCAPE") { startGame("SOLO") })
      right.add(Box.createVerticalStrut(12))
      right.add(makeButton("HOST LAN FRIEND ROOM") { hostRoom() })
      right.add(Box.createVerticalStrut(12))
      right.add(makeButton("JOIN FRIEND ROOM") { joinRoom() })
      right.add(Box.createVerticalStrut(12))
      right.add(makeButton("TRAINING YARD") { startGame("TRAINING") })
      right.add(Box.createVerticalStrut(12))
      right.add(makeButton("SHOP & COSTUMES") { showShop() })
      right.add(Box.createVerticalGlue())
      right.add(makeButton("LOG OUT") { showLogin() })
      right.add(makeButton("CLOSE GAME") { network.stop(); dispose() })
      content.add(left, BorderLayout.WEST)
      content.add(right, BorderLayout.CENTER)
      page.add(content, BorderLayout.CENTER)
      root.add(page, BorderLayout.CENTER)
      root.revalidate()
      root.repaint()
    }

    private def startGame(mode: String): Unit = {
      currentMode = mode
      activeGame = new PrisonGamePanel(currentProfile, selectedAvatar, selectedMotion, mode, network, (updated: Profile) => {
        currentProfile = updated
        LocalProfiles.save(updated)
      }, () => showLobby())
      root.removeAll()
      root.add(activeGame, BorderLayout.CENTER)
      root.revalidate()
      root.repaint()
      activeGame.requestFocusInWindow()
      activeGame.startGame()
    }

    private def hostRoom(): Unit = {
      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 from 1024 to 65535.")
        else {
          try {
            val ip = network.host(port, (line: String) => if (activeGame != null) activeGame.receiveNetwork(line))
            JOptionPane.showMessageDialog(this, "Room created.\nShare this local IP with your friend: " + ip + "\nPort: " + port + "\nSame trusted Wi-Fi is required.")
            startGame("LAN HOST")
          } catch { case ex: Exception => network.stop(); JOptionPane.showMessageDialog(this, "Could not host room: " + ex.getMessage) }
        }
      }
    }

    private def joinRoom(): Unit = {
      val ip = JOptionPane.showInputDialog(this, "Friend's local IP address:")
      if (ip != null && ip.trim.nonEmpty) {
        val portText = JOptionPane.showInputDialog(this, "Room port:", "47821")
        if (portText != null) {
          val port = try { portText.trim.toInt } catch { case _: Exception => 47821 }
          try {
            network.join(ip.trim, port, (line: String) => if (activeGame != null) activeGame.receiveNetwork(line))
            startGame("LAN CLIENT")
          } catch { case ex: Exception => network.stop(); JOptionPane.showMessageDialog(this, "Could not join room: " + ex.getMessage) }
        }
      }
    }

    private def showStory(): Unit = {
      val story =
        "BIXUU PRISON ESCAPE ? THE STORY\n\n" +
        "You wake up inside the high-security Bixuu Island Prison. The main gate is locked, " +
        "the power system is offline, and patrol bots guard the corridors.\n\n" +
        "MISSION 1 ? Explore the cell block and collect 3 energy keycards.\n" +
        "MISSION 2 ? Rescue 2 friendly helper bots to restore the access network.\n" +
        "MISSION 3 ? Reach the control gate and activate the escape route.\n" +
        "MISSION 4 ? Jump across the rising square platforms, use checkpoints, and avoid falling.\n" +
        "FINAL MISSION ? Reach the rooftop trophy before the patrol bots catch you.\n\n" +
        "Controls: WASD to move, SPACE to jump, SHIFT to dash, E to interact, F for an energy pulse, " +
        "mouse wheel to zoom, and drag the mouse to rotate the camera.\n\n" +
        "This is a fictional arcade adventure. Use the Lobby buttons to choose Solo, Training, or a LAN friend room."
      JOptionPane.showMessageDialog(this, story, "PRISON STORY & MISSIONS", JOptionPane.INFORMATION_MESSAGE)
    }

    private def showWinningList(): Unit = {
      val rows = LocalProfiles.leaderboard()
      val builder = new StringBuilder("BIXUU PRISON ESCAPE ? WINNING LIST\n\n")
      if (rows.isEmpty) builder.append("No escapes recorded yet. Be the first!\n")
      else {
        var rank = 1
        rows.foreach { p =>
          builder.append(rank).append(". ").append(p.name).append("   Escapes: ").append(p.escapes).append("   Best stage: ").append(p.bestStage).append("\n")
          rank += 1
        }
      }
      JOptionPane.showMessageDialog(this, builder.toString, "WINNING LIST", JOptionPane.INFORMATION_MESSAGE)
    }

    private def showCouponRoom(): Unit = {
      if (currentProfile.coupons <= 0) JOptionPane.showMessageDialog(this, "No Card Room Coupon yet. Win the tower trophy to earn one.")
      else {
        val answer = JOptionPane.showConfirmDialog(this, "Use one coupon to open a friend card room?", "CARD ROOM", JOptionPane.YES_NO_OPTION)
        if (answer == JOptionPane.YES_OPTION) {
          currentProfile = currentProfile.copy(coupons = currentProfile.coupons - 1)
          LocalProfiles.save(currentProfile)
          JOptionPane.showMessageDialog(this, "Coupon used! Use HOST LAN FRIEND ROOM or JOIN FRIEND ROOM to invite a friend.")
        }
      }
    }

    private def showShop(): Unit = {
      val options = Vector("Blue Runner Suit ? 120 Bucks", "Prison Neon Trail ? 90 Bucks", "Crystal Helmet ? 150 Bucks", "Cancel")
      val choice = JOptionPane.showOptionDialog(this, "Choose a cosmetic. These are local demo items.", "BIXUU SHOP", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options.toArray, options(0))
      if (choice >= 0 && choice < 3) {
        val prices = Vector(120, 90, 150)
        val price = prices(choice)
        if (currentProfile.bucks >= price) {
          currentProfile = currentProfile.copy(bucks = currentProfile.bucks - price)
          LocalProfiles.save(currentProfile)
          JOptionPane.showMessageDialog(this, "Cosmetic unlocked!")
          showLobby()
        } else JOptionPane.showMessageDialog(this, "Not enough Bixuu Bucks. Complete missions to earn more.")
      }
    }

    // IMPORTANT: Build the first screen before the frame is shown.
    // Without this call the JFrame opens with an empty white content pane.
    showLogin()
  }

  final class PrisonGamePanel(profileAtStart: Profile, avatarName: String, motionName: String, modeName: String, network: LanSession, saveProfile: Profile => Unit, backToLobby: () => Unit) extends JPanel with java.awt.event.KeyListener {
    private val dark = new Color(8, 15, 29)
    private val cyan = new Color(62, 230, 224)
    private val gold = new Color(255, 208, 92)
    private var profile = profileAtStart
    private var playerPosX = 0.0
    private var playerPosY = 0.0
    private var playerPosZ = 0.0
    private var velocityY = 0.0
    private var cameraYaw = 0.0
    private var cameraPitch = 0.37
    private var cameraZoom = 1.0
    private var grounded = true
    private var jumpReady = true
    private var dashTicks = 0
    private var pulseTicks = 0
    private var shieldTicks = 0
    private var alertTicks = 0
    private var invulnerableTicks = 0
    private var stage = 1
    private var keycards = 0
    private var rescuedFriends = 0
    private var bucksEarned = 0
    private var gameWon = false
    private var paused = false
    private var running = false
    private var tickCount = 0
    private var checkpointX = 0.0
    private var checkpointY = 0.0
    private var checkpointZ = 0.0
    private var mouseDragX = 0
    private var mouseDragY = 0
    private var showMap = false
    private val pressedKeys = mutable.Set[Int]()
    private val remotePlayers = mutable.LinkedHashMap[String, RemotePlayer]()
    private val random = new Random()
    private val platforms = Vector(
      Platform(0.0, 0.0, 31.0, 5.0, 4.5, true),
      Platform(2.7, 0.9, 36.0, 3.2, 3.0, false),
      Platform(-1.8, 1.8, 41.0, 3.2, 3.0, true),
      Platform(2.0, 2.7, 46.0, 3.2, 3.0, false),
      Platform(-2.0, 3.6, 51.0, 3.2, 3.0, true),
      Platform(0.0, 4.5, 56.0, 5.0, 4.2, false),
      Platform(0.0, 5.0, 60.0, 6.0, 5.0, false)
    )
    private val keycardSpots = Vector(V3(-4.2, 0.5, 5.0), V3(4.0, 0.5, 13.0), V3(-4.0, 0.5, 22.0))
    private val friendSpots = Vector(V3(3.0, 0.4, 8.0), V3(-3.0, 0.4, 18.0))
    private val keycardFound = mutable.Set[Int]()
    private val friendRescued = mutable.Set[Int]()
    private val guards = Vector(
      GuardBot(-6.0, 8.0, 3.0, 0.3, 0),
      GuardBot(5.5, 18.0, 3.5, 1.7, 0),
      GuardBot(0.0, 25.0, 2.5, 2.5, 0)
    )
    private val gems = mutable.ArrayBuffer[Pickup]()
    private var escapeMessage = "Find 3 energy keycards and rescue 2 friendly bots."
    private var lastNetworkSend = 0
    private val clock = new Timer(16, new ActionListener { override def actionPerformed(event: ActionEvent): Unit = gameTick() })

    setBackground(dark)
    setFocusable(true)
    addKeyListener(this)
    setLayout(new BorderLayout())
    setPreferredSize(new Dimension(1100, 720))

    private val controls = new JPanel()
    controls.setBackground(new Color(15, 26, 45))
    controls.setBorder(BorderFactory.createEmptyBorder(6, 8, 6, 8))
    private def controlButton(label: String)(action: => Unit): JButton = {
      val b = new JButton(label)
      b.setForeground(Color.WHITE)
      b.setBackground(new Color(26, 54, 78))
      b.setFocusPainted(false)
      b.addActionListener(new ActionListener { override def actionPerformed(event: ActionEvent): Unit = { action; requestFocusInWindow() } })
      b
    }
    controls.add(controlButton("JUMP") { doJump() })
    controls.add(controlButton("INTERACT / KEY") { interact() })
    controls.add(controlButton("ENERGY PULSE") { pulseTicks = 50; stunNearbyGuards() })
    controls.add(controlButton("DASH") { dashTicks = 18 })
    controls.add(controlButton("MAP") { showMap = !showMap })
    controls.add(controlButton("PAUSE") { paused = !paused })
    controls.add(controlButton("BACK TO LOBBY") { stopGame(); backToLobby() })
    add(controls, BorderLayout.SOUTH)

    addMouseListener(new MouseAdapter {
      override def mousePressed(event: MouseEvent): Unit = { mouseDragX = event.getX; mouseDragY = event.getY; requestFocusInWindow() }
      override def mouseReleased(event: MouseEvent): Unit = { mouseDragX = 0; mouseDragY = 0 }
    })
    addMouseMotionListener(new MouseMotionAdapter {
      override def mouseDragged(event: MouseEvent): Unit = {
        val dx = event.getX - mouseDragX
        val dy = event.getY - mouseDragY
        cameraYaw += dx.toDouble * 0.006
        cameraPitch = math.max(0.18, math.min(0.72, cameraPitch - dy.toDouble * 0.002))
        mouseDragX = event.getX
        mouseDragY = event.getY
      }
    })
    addMouseWheelListener(new java.awt.event.MouseWheelListener {
      override def mouseWheelMoved(event: java.awt.event.MouseWheelEvent): Unit = cameraZoom = math.max(0.65, math.min(1.65, cameraZoom - event.getWheelRotation.toDouble * 0.07))
    })

    def startGame(): Unit = { running = true; clock.start(); requestFocusInWindow() }
    def stopGame(): Unit = { running = false; clock.stop(); pressedKeys.clear() }

    def receiveNetwork(line: String): Unit = {
      val parts = line.split("\\|", -1).toVector
      if (parts.length >= 7 && parts(0) == "POS") {
        try {
          val remote = RemotePlayer(parts(1), parts(2).toDouble, parts(3).toDouble, parts(4).toDouble, parts(5).toInt, parts(6))
          if (remote.name != profile.name) remotePlayers.update(remote.name, remote)
        } catch { case _: Exception => () }
      } else if (line.startsWith("SYS|")) escapeMessage = line.substring(4)
    }

    override def keyPressed(event: KeyEvent): Unit = {
      pressedKeys += event.getKeyCode
      if (event.getKeyCode == KeyEvent.VK_E) interact()
      if (event.getKeyCode == KeyEvent.VK_SPACE) doJump()
      if (event.getKeyCode == KeyEvent.VK_F) { pulseTicks = 50; stunNearbyGuards() }
      if (event.getKeyCode == KeyEvent.VK_SHIFT) dashTicks = 18
      if (event.getKeyCode == KeyEvent.VK_P || event.getKeyCode == KeyEvent.VK_ESCAPE) paused = !paused
      if (event.getKeyCode == KeyEvent.VK_M) showMap = !showMap
      if (event.getKeyCode == KeyEvent.VK_B && gameWon) { stopGame(); backToLobby() }
    }
    override def keyReleased(event: KeyEvent): Unit = { pressedKeys -= event.getKeyCode }
    override def keyTyped(event: KeyEvent): Unit = ()

    private def doJump(): Unit = { if (grounded && !paused && !gameWon) { velocityY = 0.25; grounded = false; jumpReady = false } }

    private def interact(): Unit = {
      if (paused || gameWon) return
      var collected = false
      var i = 0
      while (i < keycardSpots.length) {
        val item = keycardSpots(i)
        if (!keycardFound.contains(i) && distance(playerPosX, playerPosY, playerPosZ, item.px, item.py, item.pz) < 2.2) {
          keycardFound += i
          keycards += 1
          bucksEarned += 35
          escapeMessage = "Energy keycard collected! " + keycards + "/3"
          collected = true
        }
        i += 1
      }
      var j = 0
      while (j < friendSpots.length) {
        val item = friendSpots(j)
        if (!friendRescued.contains(j) && distance(playerPosX, playerPosY, playerPosZ, item.px, item.py, item.pz) < 2.3) {
          friendRescued += j
          rescuedFriends += 1
          bucksEarned += 50
          escapeMessage = "Friendly training bot rescued! " + rescuedFriends + "/2"
          collected = true
        }
        j += 1
      }
      if (playerPosZ > 25.0 && playerPosZ < 30.5) {
        if (keycards >= 3 && rescuedFriends >= 2) {
          escapeMessage = "Exit gate unlocked! Climb the square parkour tower."
          checkpointX = 0.0; checkpointY = 0.0; checkpointZ = 30.0
        } else escapeMessage = "Exit locked: keycards " + keycards + "/3, rescues " + rescuedFriends + "/2"
      }
      if (playerPosZ > 58.0 && playerPosY > 3.8 && keycards >= 3 && rescuedFriends >= 2) completeEscape()
      if (!collected && playerPosZ <= 25.0) escapeMessage = "Move close to a glowing object and press E."
      repaint()
    }

    private def completeEscape(): Unit = {
      if (!gameWon) {
        gameWon = true
        val reward = 500 + bucksEarned
        profile = profile.copy(bucks = profile.bucks + reward, diamonds = profile.diamonds + 25, escapes = profile.escapes + 1, bestStage = math.max(profile.bestStage, 7), coupons = profile.coupons + 1)
        saveProfile(profile)
        escapeMessage = "ESCAPE COMPLETE! Trophy + 500 Bucks + 25 Diamonds + 1 Friend Card Coupon."
      }
    }

    private def distance(ax: Double, ay: Double, az: Double, bx: Double, by: Double, bz: Double): Double = {
      val dx = ax - bx
      val dy = ay - by
      val dz = az - bz
      math.sqrt(dx * dx + dy * dy + dz * dz)
    }

    private def stunNearbyGuards(): Unit = {
      guards.foreach { guard =>
        if (distance(playerPosX, playerPosY, playerPosZ, guard.posX, 0.0, guard.baseZ) < 6.0) guard.stun = 140
      }
      escapeMessage = "Energy pulse sent ? nearby patrol bots are paused briefly."
    }

    private def supportedAt(posX: Double, posY: Double, posZ: Double): Option[Platform] = {
      if (posZ < 29.0 && math.abs(posX) < 9.4) Some(Platform(0, 0, 0, 18, 60, false))
      else platforms.find(p => math.abs(posX - p.posX) <= p.width / 2.0 && math.abs(posZ - p.posZ) <= p.depth / 2.0 && posY >= p.topY - 0.12 && posY <= p.topY + 0.42)
    }

    private def respawn(): Unit = {
      playerPosX = checkpointX
      playerPosY = checkpointY
      playerPosZ = checkpointZ
      velocityY = 0.0
      grounded = true
      invulnerableTicks = 100
      escapeMessage = "Checkpoint reached. Try the next square platform!"
    }

    private def gameTick(): Unit = {
      if (!running || paused || gameWon) { repaint(); return }
      tickCount += 1
      if (pulseTicks > 0) pulseTicks -= 1
      if (dashTicks > 0) dashTicks -= 1
      if (shieldTicks > 0) shieldTicks -= 1
      if (alertTicks > 0) alertTicks -= 1
      if (invulnerableTicks > 0) invulnerableTicks -= 1
      val moveSpeed = if (dashTicks > 0) 0.19 else 0.095
      val forwardX = math.sin(cameraYaw)
      val forwardZ = math.cos(cameraYaw)
      val rightX = math.cos(cameraYaw)
      val rightZ = -math.sin(cameraYaw)
      if (pressedKeys.contains(KeyEvent.VK_W) || pressedKeys.contains(KeyEvent.VK_UP)) { playerPosX += forwardX * moveSpeed; playerPosZ += forwardZ * moveSpeed }
      if (pressedKeys.contains(KeyEvent.VK_S) || pressedKeys.contains(KeyEvent.VK_DOWN)) { playerPosX -= forwardX * moveSpeed; playerPosZ -= forwardZ * moveSpeed }
      if (pressedKeys.contains(KeyEvent.VK_A)) { playerPosX -= rightX * moveSpeed; playerPosZ -= rightZ * moveSpeed }
      if (pressedKeys.contains(KeyEvent.VK_D)) { playerPosX += rightX * moveSpeed; playerPosZ += rightZ * moveSpeed }
      if (pressedKeys.contains(KeyEvent.VK_LEFT)) cameraYaw -= 0.025
      if (pressedKeys.contains(KeyEvent.VK_RIGHT)) cameraYaw += 0.025
      playerPosX = math.max(-8.7, math.min(8.7, playerPosX))
      if (playerPosZ > 29.4 && (keycards < 3 || rescuedFriends < 2)) {
        playerPosZ = 29.4
        escapeMessage = "Exit locked ? collect all 3 keycards and rescue both friendly bots."
      }

      val wasGrounded = grounded
      if (!grounded) {
        velocityY -= 0.012
        playerPosY += velocityY
      }
      val support = supportedAt(playerPosX, playerPosY, playerPosZ)
      if (support.isDefined && velocityY <= 0.0) {
        val platform = support.get
        if (playerPosY <= platform.topY + 0.18) {
          playerPosY = platform.topY
          velocityY = 0.0
          grounded = true
          if (platform.checkpoint && platform.posZ > checkpointZ) {
            checkpointX = platform.posX; checkpointY = platform.topY; checkpointZ = platform.posZ
            escapeMessage = "Parkour checkpoint saved!"
          }
        }
      } else if (playerPosZ >= 29.0) grounded = false
      if (playerPosZ < 29.0 && playerPosY < 0.0) { playerPosY = 0.0; velocityY = 0.0; grounded = true }
      if (playerPosY < -5.0 || playerPosZ < -8.0) respawn()

      guards.foreach { guard =>
        if (guard.stun > 0) guard.stun -= 1
        else {
          val botZ = guard.baseZ + math.sin(tickCount.toDouble * 0.035 + guard.phase) * guard.range
          if (invulnerableTicks <= 0 && distance(playerPosX, playerPosY, playerPosZ, guard.posX, 0.0, botZ) < 1.25) {
            respawn()
            alertTicks = 60
            escapeMessage = "Patrol bot tagged you! Returned to last checkpoint."
          }
        }
      }
      if (playerPosZ > 28.0 && keycards >= 3 && rescuedFriends >= 2 && playerPosZ > 58.0 && playerPosY > 3.8) completeEscape()
      if (modeName.startsWith("LAN")) {
        lastNetworkSend += 1
        if (lastNetworkSend >= 6) {
          lastNetworkSend = 0
          network.send("POS|" + profile.name + "|" + playerPosX + "|" + playerPosY + "|" + playerPosZ + "|" + stage + "|RUNNER")
        }
      }
      repaint()
    }

    private def project(point: V3): Option[ScreenPoint] = {
      val camX = playerPosX - math.sin(cameraYaw) * 6.5
      val camY = playerPosY + 3.0
      val camZ = playerPosZ - math.cos(cameraYaw) * 6.5
      val dx = point.px - camX
      val dy = point.py - camY
      val dz = point.pz - camZ
      val cosYaw = math.cos(cameraYaw)
      val sinYaw = math.sin(cameraYaw)
      val viewX = dx * cosYaw - dz * sinYaw
      val viewZ0 = dx * sinYaw + dz * cosYaw
      val cosPitch = math.cos(cameraPitch)
      val sinPitch = math.sin(cameraPitch)
      val viewY = dy * cosPitch + viewZ0 * sinPitch
      val viewZ = -dy * sinPitch + viewZ0 * cosPitch
      if (viewZ <= 0.35) None
      else {
        val focal = math.min(getWidth, getHeight).toDouble * 0.92 * cameraZoom
        val scale = focal / viewZ
        val sx = (getWidth.toDouble * 0.5 + viewX * scale).toInt
        val sy = (getHeight.toDouble * 0.54 - viewY * scale).toInt
        Some(ScreenPoint(sx, sy, viewZ, scale))
      }
    }

    private def drawPoly(g: Graphics2D, points: Vector[V3], color: Color): Unit = {
      val projected = points.map(project)
      if (projected.forall(_.isDefined)) {
        val valid = projected.flatten
        val xs = valid.map(_.sx).toArray
        val ys = valid.map(_.sy).toArray
        val polygon = new Polygon(xs, ys, valid.length)
        g.setColor(color)
        g.fillPolygon(polygon)
        g.setColor(new Color(8, 17, 29, 150))
        g.setStroke(new BasicStroke(1.1f))
        g.drawPolygon(polygon)
      }
    }

    private def drawCube(g: Graphics2D, centerX: Double, baseY: Double, centerZ: Double, sizeX: Double, sizeY: Double, sizeZ: Double, baseColor: Color): Unit = {
      val x0 = centerX - sizeX / 2.0
      val x1 = centerX + sizeX / 2.0
      val y0 = baseY
      val y1 = baseY + sizeY
      val z0 = centerZ - sizeZ / 2.0
      val z1 = centerZ + sizeZ / 2.0
      val v = Vector(V3(x0,y0,z0), V3(x1,y0,z0), V3(x1,y1,z0), V3(x0,y1,z0), V3(x0,y0,z1), V3(x1,y0,z1), V3(x1,y1,z1), V3(x0,y1,z1))
      val faces = Vector(
        (Vector(0,1,2,3), shade(baseColor, 0.88)),
        (Vector(4,5,6,7), shade(baseColor, 0.72)),
        (Vector(0,3,7,4), shade(baseColor, 0.58)),
        (Vector(1,2,6,5), shade(baseColor, 1.14)),
        (Vector(3,2,6,7), shade(baseColor, 1.30)),
        (Vector(0,1,5,4), shade(baseColor, 0.48))
      )
      val ordered = faces.map { item =>
        val facePoints = item._1.map(index => v(index))
        val depth = facePoints.map(p => project(p).map(_.depth).getOrElse(9999.0)).sum / facePoints.length.toDouble
        (facePoints, item._2, depth)
      }.sortBy(item => -item._3)
      ordered.foreach(item => drawPoly(g, item._1, item._2))
    }

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

    private def drawGround(g: Graphics2D): Unit = {
      drawPoly(g, Vector(V3(-10.0,-0.3,-5.0), V3(10.0,-0.3,-5.0), V3(10.0,-0.3,30.0), V3(-10.0,-0.3,30.0)), new Color(32, 53, 70))
      var z = -2
      while (z <= 30) {
        drawPoly(g, Vector(V3(-10.0,-0.27,z.toDouble), V3(10.0,-0.27,z.toDouble), V3(10.0,-0.27,z + 0.045), V3(-10.0,-0.27,z + 0.045)), new Color(50, 75, 88, 120))
        z += 4
      }
      drawCube(g, -9.6, -0.1, 12.0, 0.8, 7.0, 31.0, new Color(39, 65, 91))
      drawCube(g, 9.6, -0.1, 12.0, 0.8, 7.0, 31.0, new Color(39, 65, 91))
      drawCube(g, -5.5, -0.1, 9.0, 2.0, 3.2, 1.2, new Color(55, 75, 100))
      drawCube(g, 5.5, -0.1, 17.0, 2.0, 3.2, 1.2, new Color(55, 75, 100))
      drawCube(g, 0.0, -0.1, 28.8, 6.0, 5.2, 0.8, new Color(67, 107, 137))
    }

    private def drawPlatforms(g: Graphics2D): Unit = {
      platforms.foreach { p =>
        val color = if (p.checkpoint) new Color(42, 176, 159) else new Color(71, 112, 166)
        drawCube(g, p.posX, p.topY - 0.38, p.posZ, p.width, 0.38, p.depth, color)
        if (p.checkpoint) drawCube(g, p.posX, p.topY, p.posZ, p.width * 0.72, 0.07, p.depth * 0.72, new Color(93, 232, 195))
      }
    }

    private def drawDiamond(g: Graphics2D, worldX: Double, worldY: Double, worldZ: Double, color: Color): Unit = {
      val s = 0.42
      drawPoly(g, Vector(V3(worldX,worldY+s,worldZ), V3(worldX+s,worldY,worldZ), V3(worldX,worldY-s,worldZ), V3(worldX-s,worldY,worldZ)), shade(color, 1.25))
      drawPoly(g, Vector(V3(worldX,worldY+s,worldZ), V3(worldX,worldY,worldZ+s), V3(worldX+s,worldY,worldZ), V3(worldX,worldY-s,worldZ)), color)
      drawPoly(g, Vector(V3(worldX,worldY+s,worldZ), V3(worldX-s,worldY,worldZ), V3(worldX,worldY,worldZ-s), V3(worldX,worldY,worldZ+s)), shade(color, 0.65))
    }

    private def drawPlayer(g: Graphics2D, px: Double, py: Double, pz: Double, tint: Color, isRemote: Boolean): Unit = {
      val bob = if (!isRemote && grounded) math.sin(tickCount.toDouble * 0.12) * 0.035 else 0.0
      val y = py + bob
      drawCube(g, px, y + 0.78, pz, 0.72, 0.95, 0.42, tint)
      drawCube(g, px, y + 1.82, pz, 0.54, 0.55, 0.50, new Color(236, 205, 169))
      drawCube(g, px - 0.43, y + 0.88, pz, 0.22, 0.86, 0.26, shade(tint, 0.9))
      drawCube(g, px + 0.43, y + 0.88, pz, 0.22, 0.86, 0.26, shade(tint, 0.9))
      drawCube(g, px - 0.2, y, pz + 0.02, 0.26, 0.72, 0.30, new Color(32, 48, 72))
      drawCube(g, px + 0.2, y, pz + 0.02, 0.26, 0.72, 0.30, new Color(32, 48, 72))
      drawCube(g, px, y + 2.12, pz - 0.02, 0.62, 0.12, 0.58, new Color(238, 190, 77))
    }

    private def drawScene(g: Graphics2D): Unit = {
      val w = getWidth
      val h = getHeight
      val bg = new java.awt.GradientPaint(0, 0, new Color(8, 20, 40), 0, h, new Color(45, 58, 79))
      g.setPaint(bg)
      g.fillRect(0, 0, w, h)
      g.setColor(new Color(195, 229, 243, 40))
      var star = 0
      while (star < 38) {
        val sx = (star * 137 + 31) % math.max(1, w)
        val sy = (star * 61 + 17) % math.max(1, h / 2)
        g.fillOval(sx, sy, 2, 2)
        star += 1
      }
      drawGround(g)
      drawPlatforms(g)
      drawCube(g, -7.8, -0.1, 5.0, 1.0, 4.8, 1.0, new Color(92, 106, 131))
      drawCube(g, 7.8, -0.1, 13.0, 1.0, 4.8, 1.0, new Color(92, 106, 131))
      drawCube(g, 0.0, -0.1, 30.0, 0.45, 5.0, 0.45, new Color(69, 204, 205))

      keycardSpots.zipWithIndex.foreach { item =>
        if (!keycardFound.contains(item._2)) drawDiamond(g, item._1.px, item._1.py + math.sin(tickCount * 0.06) * 0.18, item._1.pz, new Color(80, 226, 255))
      }
      friendSpots.zipWithIndex.foreach { item =>
        if (!friendRescued.contains(item._2)) drawCube(g, item._1.px, item._1.py, item._1.pz, 0.8, 1.0, 0.65, new Color(245, 190, 83))
      }
      guards.foreach { guard =>
        val botZ = guard.baseZ + math.sin(tickCount.toDouble * 0.035 + guard.phase) * guard.range
        val color = if (guard.stun > 0) new Color(90, 230, 247) else new Color(214, 80, 102)
        drawCube(g, guard.posX, 0.0, botZ, 0.9, 1.65, 0.85, color)
        drawCube(g, guard.posX, 1.62, botZ, 0.72, 0.55, 0.72, new Color(48, 54, 79))
      }
      remotePlayers.values.foreach { remote => drawPlayer(g, remote.posX, remote.posY, remote.posZ, new Color(129, 178, 245), true) }
      drawPlayer(g, playerPosX, playerPosY, playerPosZ, new Color(73, 213, 177), false)
      if (playerPosZ > 56.0) drawCube(g, 0.0, 5.0, 63.0, 1.6, 2.4, 1.0, gold)
      drawHud(g)
    }

    private def drawHud(g: Graphics2D): Unit = {
      g.setColor(new Color(5, 12, 24, 205))
      g.fillRoundRect(15, 14, 350, 125, 18, 18)
      g.setColor(cyan)
      g.setFont(new Font("SansSerif", Font.BOLD, 18))
      g.drawString("BIXUU PRISON ESCAPE", 30, 40)
      g.setColor(Color.WHITE)
      g.setFont(new Font("SansSerif", Font.BOLD, 13))
      g.drawString("PLAYER: " + profile.name + "   MODE: " + modeName, 30, 63)
      g.drawString("KEYCARDS: " + keycards + "/3    RESCUES: " + rescuedFriends + "/2", 30, 84)
      g.drawString("BUCKS: " + (profile.bucks + bucksEarned) + "    HEIGHT: " + playerPosZ.toInt, 30, 105)
      g.setColor(new Color(20, 30, 43))
      g.fillRoundRect(30, 115, 260, 10, 8, 8)
      g.setColor(new Color(68, 217, 183))
      g.fillRoundRect(30, 115, math.max(0, math.min(260, keycards * 86)), 10, 8, 8)
      g.setFont(new Font("SansSerif", Font.BOLD, 12))
      g.setColor(new Color(231, 242, 251))
      g.drawString("WASD Move  ?  SPACE Jump  ?  E Interact  ?  F Pulse  ?  Mouse Wheel Zoom", 25, getHeight - 60)
      g.setColor(gold)
      g.drawString(escapeMessage, 25, getHeight - 42)
      if (showMap) drawMiniMap(g)
      if (paused) {
        g.setColor(new Color(3, 7, 14, 185))
        g.fillRect(0, 0, getWidth, getHeight)
        g.setFont(new Font("SansSerif", Font.BOLD, 38))
        g.setColor(Color.WHITE)
        centerText(g, "PAUSED", getWidth / 2, getHeight / 2)
      }
      if (gameWon) {
        g.setColor(new Color(3, 7, 14, 190))
        g.fillRect(0, 0, getWidth, getHeight)
        g.setFont(new Font("SansSerif", Font.BOLD, 34))
        g.setColor(gold)
        centerText(g, "PRISON ESCAPE COMPLETE!", getWidth / 2, getHeight / 2 - 28)
        g.setFont(new Font("SansSerif", Font.BOLD, 18))
        g.setColor(Color.WHITE)
        centerText(g, "TROPHY + 500 BUCKS + 25 DIAMONDS + 1 CARD ROOM COUPON", getWidth / 2, getHeight / 2 + 15)
        centerText(g, "Press B to return to Lobby", getWidth / 2, getHeight / 2 + 55)
      }
    }

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

    private def drawMiniMap(g: Graphics2D): Unit = {
      val left = getWidth - 195
      val top = 18
      g.setColor(new Color(5, 12, 24, 220))
      g.fillRoundRect(left, top, 175, 210, 14, 14)
      g.setColor(cyan)
      g.setFont(new Font("SansSerif", Font.BOLD, 13))
      g.drawString("PRISON MAP", left + 17, top + 23)
      g.setColor(new Color(70, 91, 116))
      g.fillRoundRect(left + 30, top + 35, 115, 155, 7, 7)
      g.setColor(new Color(93, 220, 186))
      val px = left + 87 + (playerPosX * 5.0).toInt
      val pz = top + 178 - (playerPosZ * 2.2).toInt
      g.fillOval(px - 5, pz - 5, 10, 10)
      g.setColor(new Color(255, 208, 92))
      keycardSpots.zipWithIndex.foreach { item => if (!keycardFound.contains(item._2)) g.fillOval(left + 87 + (item._1.px * 5.0).toInt - 3, top + 178 - (item._1.pz * 2.2).toInt - 3, 6, 6) }
    }

    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)
      drawScene(g)
      g.dispose()
    }
  }
}

BixuuPrisonEscape.main(Array[String]())