Code Sketch


BixuuWarriorRealms
By: Mhalsakant School
Category: Programming
// BIXUU WARRIOR REALMS - ENHANCED SOFTWARE 3D SCALA SWING EDITION
// 3D scene geometry: six-face cuboids, faceted spheres, octahedral crystals,
// perspective projection, painter depth-sorting, mouse/keyboard camera control.
// Pure Scala source using Java Swing/AWT; no Java source file or external engine.
// Kojo launch: BixuuWarriorRealms.main(Array[String]())

import java.awt.{BasicStroke, BorderLayout, Color, Dimension, Font, GradientPaint, Graphics, Graphics2D, GridLayout, Polygon, RenderingHints}
import java.awt.event.{ActionEvent, ActionListener, KeyAdapter, KeyEvent, MouseAdapter, MouseEvent, WindowAdapter, WindowEvent}
import java.awt.geom.Ellipse2D
import java.io.{BufferedReader, File, FileInputStream, FileOutputStream, InputStreamReader, OutputStreamWriter, PrintWriter}
import java.net.{InetAddress, ServerSocket, Socket}
import java.util.Properties
import java.util.concurrent.CopyOnWriteArrayList
import javax.swing.{BorderFactory, Box, BoxLayout, JButton, JFrame, JLabel, JOptionPane, JPanel, JScrollPane, JTextArea, JTextField, SwingConstants, SwingUtilities, Timer, WindowConstants}
import scala.collection.mutable
import scala.util.Random

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

  final case class PlayerProfile(name: String, bucks: Int, diamonds: Int, trophies: Int,
                                 coupons: Int, bestLevel: Int, wins: Int, totalCoins: Int,
                                 ownedCards: Set[String])
  final case class HeroCard(name: String, role: String, power: Int, color: Color, detail: String)
  final case class Platform3D(cx: Double, cy: Double, cz: Double, size: Double, checkpoint: Boolean)
  final case class Gem3D(x: Double, y: Double, z: Double, label: String, value: Int)
  final case class Point3D(sx: Int, sy: Int, scale: Double, depth: Double)
  final case class RenderFace3D(points: Vector[(Double, Double, Double)], color: Color, depth: Double)
  final case class RemoteAvatar(name: String, x: Double, y: Double, z: Double, level: Int)

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

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

    private def keyName(name: String): String = name.trim.replaceAll("[^A-Za-z0-9_-]", "_").take(24)

    def exists(name: String): Boolean = synchronized {
      ensureLoaded()
      props.getProperty("player." + keyName(name) + ".name") != null
    }

    def load(name: String): PlayerProfile = synchronized {
      ensureLoaded()
      val key = "player." + keyName(name) + "."
      val storedName = Option(props.getProperty(key + "name")).getOrElse(name)
      val cardsText = Option(props.getProperty(key + "cards")).getOrElse("Cloud Hopper,Clockwork Cub")
      val cards = cardsText.split(",").map(_.trim).filter(_.nonEmpty).toSet
      PlayerProfile(
        storedName,
        readInt(key + "bucks", 250),
        readInt(key + "diamonds", 20),
        readInt(key + "trophies", 0),
        readInt(key + "coupons", 0),
        readInt(key + "bestLevel", 0),
        readInt(key + "wins", 0),
        readInt(key + "totalCoins", 0),
        cards
      )
    }

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

    def save(profile: PlayerProfile): Unit = synchronized {
      ensureLoaded()
      val key = "player." + keyName(profile.name) + "."
      props.setProperty(key + "name", profile.name)
      props.setProperty(key + "bucks", profile.bucks.toString)
      props.setProperty(key + "diamonds", profile.diamonds.toString)
      props.setProperty(key + "trophies", profile.trophies.toString)
      props.setProperty(key + "coupons", profile.coupons.toString)
      props.setProperty(key + "bestLevel", profile.bestLevel.toString)
      props.setProperty(key + "wins", profile.wins.toString)
      props.setProperty(key + "totalCoins", profile.totalCoins.toString)
      props.setProperty(key + "cards", profile.ownedCards.toVector.sorted.mkString(","))
      var out: FileOutputStream = null
      try {
        out = new FileOutputStream(file)
        props.store(out, "Bixuu Warrior Realms local player profiles")
      } catch { case _: Exception => () }
      finally { try { if (out != null) out.close() } catch { case _: Exception => () } }
    }

    def leaderboard(): Vector[PlayerProfile] = synchronized {
      ensureLoaded()
      val names = props.stringPropertyNames()
      val found = mutable.ArrayBuffer[PlayerProfile]()
      val seen = mutable.Set[String]()
      val iterator = names.iterator()
      while (iterator.hasNext) {
        val key = iterator.next()
        if (key.startsWith("player.") && key.endsWith(".name")) {
          val n = props.getProperty(key)
          if (n != null && !seen.contains(n)) {
            seen += n
            found += load(n)
          }
        }
      }
      found.toVector.sortBy(p => (-p.trophies, -p.bestLevel, -p.wins, -p.totalCoins)).take(12)
    }
  }

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

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

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

    private def readLoop(socket: Socket, hostSide: Boolean, ownWriter: PrintWriter): Unit = {
      val thread = 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) {
              notifyLine(line)
              if (hostSide) broadcast(line, ownWriter)
              line = reader.readLine()
            }
          } catch { case _: Exception => notifyLine("SYSTEM|A player disconnected") }
          finally { try { if (reader != null) reader.close() } catch { case _: Exception => () } }
        }
      })
      thread.setDaemon(true)
      thread.start()
    }

    def host(port: Int, onLine: String => Unit): String = {
      stop()
      listener = onLine
      serverSocket = new ServerSocket(port)
      active = true
      val localServer = serverSocket
      val acceptThread = new Thread(new Runnable {
        override def run(): Unit = {
          while (active && !localServer.isClosed) {
            try {
              val socket = localServer.accept()
              if (peerSockets.size() >= 12) socket.close()
              else {
                peerSockets.add(socket)
                val writer = new PrintWriter(socket.getOutputStream, true)
                peerWriters.add(writer)
                notifyLine("SYSTEM|Friend connected")
                readLoop(socket, true, writer)
              }
            } catch { case _: Exception => if (active) notifyLine("SYSTEM|Room server stopped") }
          }
        }
      })
      acceptThread.setDaemon(true)
      acceptThread.start()
      try { InetAddress.getLocalHost.getHostAddress } catch { case _: Exception => "127.0.0.1" }
    }

    def join(ip: String, port: Int, onLine: String => Unit): Unit = {
      stop()
      listener = onLine
      clientSocket = new Socket(ip, port)
      clientSocket.setTcpNoDelay(true)
      clientWriter = new PrintWriter(clientSocket.getOutputStream, true)
      active = true
      readLoop(clientSocket, false, null)
      send("SYSTEM|A friend joined")
    }

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

    def isActive: Boolean = active

    def stop(): Unit = {
      active = 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 sockets = peerSockets.iterator()
      while (sockets.hasNext) { try { sockets.next().close() } catch { case _: Exception => () } }
      peerSockets.clear()
      peerWriters.clear()
      clientWriter = null
      clientSocket = null
      serverSocket = null
      listener = null
    }
  }

  final class MainFrame extends JFrame("BIXUU WARRIOR REALMS | 3D OBBY TOWER") {
    private val root = new JPanel(new BorderLayout())
    private val network = new LanRoom()
    private var activeObby: ObbyPanel = null
    var profile: PlayerProfile = PlayerProfile("Player", 250, 20, 0, 0, 0, 0, 0, Set("Cloud Hopper", "Clockwork Cub"))
    var selectedHero = "Nova Runner"
    var selectedAnimation = "Heroic Run"
    private var roomStatus = "Not connected"

    val heroCards = Vector(
      HeroCard("Nova Runner", "Speed Hero", 28, new Color(46, 205, 238), "Fast movement and bright trail."),
      HeroCard("Volt Mage", "Energy Hero", 34, new Color(170, 117, 246), "Electric aura and pulse style."),
      HeroCard("Aurora Guard", "Defender", 40, new Color(76, 211, 151), "Strong shield and steady jumps."),
      HeroCard("Cyber Scout", "Agile Explorer", 31, new Color(241, 178, 78), "Quick turns and nimble movement."),
      HeroCard("Titan Cub", "Ancient Hero", 43, new Color(230, 126, 105), "Heavy armour and bold style."),
      HeroCard("Cloud Hopper", "Sky Hero", 25, new Color(116, 178, 244), "Light feet and cloud effects.")
    )

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

    def networkActive: Boolean = network.isActive

    def heroColor: Color = {
      heroCards.find(_.name == selectedHero).map(_.color).getOrElse(new Color(48, 190, 225))
    }

    def sendPosition(px: Double, py: Double, pz: Double, level: Int): Unit = {
      val safeName = profile.name.replace("|", "_")
      network.send("POS|" + safeName + "|" + px + "|" + py + "|" + pz + "|" + level)
    }

    private def pagePanel(): JPanel = {
      val p = new JPanel(new BorderLayout(12, 12))
      p.setBackground(new Color(7, 13, 30))
      p.setBorder(BorderFactory.createEmptyBorder(18, 22, 18, 22))
      p
    }

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

    private def note(text: String): JLabel = {
      val label = new JLabel(text, SwingConstants.CENTER)
      label.setForeground(new Color(173, 198, 225))
      label.setFont(new Font("SansSerif", Font.PLAIN, 14))
      label
    }

    private def gameButton(text: String, color: Color)(action: => Unit): JButton = {
      val b = new JButton(text)
      b.setFont(new Font("SansSerif", Font.BOLD, 14))
      b.setForeground(Color.WHITE)
      b.setBackground(color)
      b.setOpaque(true)
      b.setFocusPainted(false)
      b.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createLineBorder(color.brighter(), 1),
        BorderFactory.createEmptyBorder(10, 12, 10, 12)
      ))
      b.addActionListener(new ActionListener {
        override def actionPerformed(event: ActionEvent): Unit = action
      })
      b
    }

    private def switchPage(panel: JPanel): Unit = {
      if (activeObby != null) { activeObby.stopGame(); activeObby = null }
      root.removeAll()
      root.add(panel, BorderLayout.CENTER)
      root.revalidate()
      root.repaint()
    }

    def showLogin(): Unit = {
      val panel = pagePanel()
      val center = new JPanel()
      center.setOpaque(false)
      center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS))
      center.add(Box.createVerticalGlue())
      center.add(title("BIXUU WARRIOR REALMS", 38))
      center.add(Box.createVerticalStrut(8))
      center.add(note("3D-STYLE SQUARE OBBY TOWER  ?  HERO ANIMATIONS  ?  FRIEND PLAY"))
      center.add(Box.createVerticalStrut(25))
      val nameField = new JTextField("Player", 20)
      nameField.setMaximumSize(new Dimension(360, 42))
      nameField.setHorizontalAlignment(SwingConstants.CENTER)
      nameField.setFont(new Font("SansSerif", Font.PLAIN, 18))
      center.add(nameField)
      center.add(Box.createVerticalStrut(12))
      val buttons = new JPanel(new GridLayout(1, 2, 10, 10))
      buttons.setOpaque(false)
      buttons.add(gameButton("CREATE ACCOUNT", new Color(24, 137, 173)) {
        val n = cleanName(nameField.getText)
        if (n.isEmpty) JOptionPane.showMessageDialog(this, "Enter a player ID using letters or numbers.")
        else if (LocalStore.exists(n)) JOptionPane.showMessageDialog(this, "This player ID already exists. Choose LOGIN.")
        else { profile = LocalStore.load(n); LocalStore.save(profile); showLobby() }
      })
      buttons.add(gameButton("LOGIN", new Color(105, 82, 166)) {
        val n = cleanName(nameField.getText)
        if (n.isEmpty) JOptionPane.showMessageDialog(this, "Enter your saved player ID.")
        else if (!LocalStore.exists(n)) JOptionPane.showMessageDialog(this, "Player ID not found. Create an account first.")
        else { profile = LocalStore.load(n); showLobby() }
      })
      center.add(buttons)
      center.add(Box.createVerticalStrut(16))
      center.add(note("Progress is saved locally on this computer."))
      center.add(Box.createVerticalStrut(12))
      val close = gameButton("CLOSE GAME", new Color(105, 69, 88)) { closeGame() }
      close.setAlignmentX(0.5f)
      center.add(close)
      center.add(Box.createVerticalGlue())
      panel.add(center, BorderLayout.CENTER)
      switchPage(panel)
    }

    private def cleanName(raw: String): String = raw.trim.replaceAll("[^A-Za-z0-9 _-]", "").take(20)

    def showLobby(): Unit = {
      val panel = pagePanel()
      panel.add(title("WELCOME, " + profile.name.toUpperCase, 28), BorderLayout.NORTH)
      val center = new JPanel(new GridLayout(3, 3, 13, 13))
      center.setOpaque(false)
      center.add(gameButton("START SQUARE OBBY", new Color(22, 133, 170)) { startObby() })
      center.add(gameButton("CHOOSE HERO + ANIMATION", new Color(112, 82, 174)) { showHeroAnimation() })
      center.add(gameButton("HERO / ENEMY CARDS", new Color(68, 114, 165)) { showCards() })
      center.add(gameButton("TASK BOARD", new Color(47, 135, 116)) { showTasks() })
      center.add(gameButton("MULTIPLAYER LAN", new Color(27, 126, 151)) { showMultiplayer() })
      center.add(gameButton("BIXUU SHOP", new Color(171, 122, 45)) { showShop() })
      center.add(gameButton("WINNING LIST", new Color(152, 106, 45)) { showWinningList() })
      center.add(gameButton("FRIEND CARD ROOM", new Color(115, 83, 157)) { showCardRoom() })
      center.add(gameButton("CLOSE GAME", new Color(100, 73, 88)) { closeGame() })
      panel.add(center, BorderLayout.CENTER)
      panel.add(note("Bixuu Bucks: " + profile.bucks + "   |   Diamonds: " + profile.diamonds + "   |   Trophies: " + profile.trophies + "   |   Coupons: " + profile.coupons + "   |   Best Level: " + profile.bestLevel), BorderLayout.SOUTH)
      switchPage(panel)
    }

    def showHeroAnimation(): Unit = {
      val panel = pagePanel()
      panel.add(title("HERO & ANIMATION SELECT", 27), BorderLayout.NORTH)
      val list = new JPanel(new GridLayout(0, 2, 10, 10))
      list.setOpaque(false)
      heroCards.foreach { hero =>
        list.add(gameButton(hero.name + "  |  " + hero.role + "  |  POWER " + hero.power, hero.color) {
          selectedHero = hero.name
          JOptionPane.showMessageDialog(this, "Selected: " + selectedHero)
        })
      }
      val center = new JPanel(new BorderLayout(8, 8))
      center.setOpaque(false)
      center.add(new JScrollPane(list), BorderLayout.CENTER)
      val animationButtons = new JPanel(new GridLayout(1, 4, 8, 8))
      animationButtons.setOpaque(false)
      val animations = Vector("Heroic Run", "Ninja Vault", "Robot Hover", "Cyber Sprint")
      animations.foreach { anim =>
        animationButtons.add(gameButton(anim.toUpperCase, new Color(62, 101, 150)) {
          selectedAnimation = anim
          JOptionPane.showMessageDialog(this, "Animation selected: " + selectedAnimation)
        })
      }
      center.add(animationButtons, BorderLayout.SOUTH)
      panel.add(center, BorderLayout.CENTER)
      panel.add(gameButton("BACK TO LOBBY", new Color(75, 91, 119)) { showLobby() }, BorderLayout.SOUTH)
      switchPage(panel)
    }

    def showCards(): Unit = {
      val panel = pagePanel()
      panel.add(title("HERO & ENEMY CARD COLLECTION", 25), BorderLayout.NORTH)
      val data = Vector("Cloud Hopper", "Clockwork Cub", "Moss Sprite", "Neon Lynx", "Crystal Golem", "Tide Guardian", "Ember Drake", "Titan Cub")
      val grid = new JPanel(new GridLayout(0, 2, 10, 10))
      grid.setOpaque(false)
      data.foreach { cardName =>
        val owned = profile.ownedCards.contains(cardName)
        grid.add(gameButton((if (owned) "OWNED  ?  " else "LOCKED  ?  ") + cardName, new Color(58, 108, 153)) {
          val message = if (owned) "This card is in your collection." else "Win parkour stages to unlock more cards."
          JOptionPane.showMessageDialog(this, message)
        })
      }
      panel.add(new JScrollPane(grid), BorderLayout.CENTER)
      panel.add(gameButton("BACK TO LOBBY", new Color(75, 91, 119)) { showLobby() }, BorderLayout.SOUTH)
      switchPage(panel)
    }

    def showTasks(): Unit = {
      val panel = pagePanel()
      panel.add(title("PARKOUR TASK BOARD", 26), BorderLayout.NORTH)
      val text = new JTextArea()
      text.setEditable(false)
      text.setFont(new Font("SansSerif", Font.BOLD, 17))
      text.setForeground(new Color(230, 241, 255))
      text.setBackground(new Color(15, 27, 52))
      text.setText(
        "DAILY TASKS\n\n" +
        "[ " + (if (profile.totalCoins >= 10) "X" else " ") + " ] Collect 10 Bixuu Coins\n" +
        "[ " + (if (profile.bestLevel >= 6) "X" else " ") + " ] Reach Checkpoint 6\n" +
        "[ " + (if (profile.wins >= 1) "X" else " ") + " ] Win one Parkour Tower\n\n" +
        "YOUR STATS\nCoins collected: " + profile.totalCoins + "\nBest checkpoint: " + profile.bestLevel + "\nTrophy wins: " + profile.wins + "\n\n" +
        "Reward: Complete the tower to earn 500 Bixuu Bucks, 25 Diamonds and 1 Card Room Coupon."
      )
      panel.add(new JScrollPane(text), BorderLayout.CENTER)
      panel.add(gameButton("BACK TO LOBBY", new Color(75, 91, 119)) { showLobby() }, BorderLayout.SOUTH)
      switchPage(panel)
    }

    def showWinningList(): Unit = {
      val panel = pagePanel()
      panel.add(title("BIXUU WINNING LIST", 27), BorderLayout.NORTH)
      val area = new JTextArea()
      area.setEditable(false)
      area.setFont(new Font("Monospaced", Font.BOLD, 16))
      area.setBackground(new Color(12, 23, 45))
      area.setForeground(new Color(235, 242, 255))
      val board = LocalStore.leaderboard()
      var text = "RANK  PLAYER                  WINS  TROPHIES  BEST LEVEL\n"
      text += "-------------------------------------------------------\n"
      var rank = 1
      board.foreach { p =>
        text += rank + "     " + p.name.take(20) + " " * math.max(1, 22 - p.name.take(20).length) + p.wins + "     " + p.trophies + "         " + p.bestLevel + "\n"
        rank += 1
      }
      if (board.isEmpty) text += "No winners yet. Be the first to reach the top!\n"
      area.setText(text)
      panel.add(new JScrollPane(area), BorderLayout.CENTER)
      panel.add(gameButton("BACK TO LOBBY", new Color(75, 91, 119)) { showLobby() }, BorderLayout.SOUTH)
      switchPage(panel)
    }

    def showShop(): Unit = {
      val panel = pagePanel()
      val shopHeader = new JPanel(new BorderLayout(4, 4))
      shopHeader.setOpaque(false)
      shopHeader.add(title("BIXUU OBBY SHOP", 26), BorderLayout.NORTH)
      shopHeader.add(note("Bixuu Bucks: " + profile.bucks + "  |  Diamonds: " + profile.diamonds), BorderLayout.SOUTH)
      panel.add(shopHeader, BorderLayout.NORTH)
      val grid = new JPanel(new GridLayout(0, 2, 10, 10))
      grid.setOpaque(false)
      grid.add(gameButton("NEON TRAIL  ?  80 BUCKS", new Color(28, 131, 168)) { purchase(80, "Neon Trail") })
      grid.add(gameButton("CRYSTAL AURA  ?  120 BUCKS", new Color(106, 83, 168)) { purchase(120, "Crystal Aura") })
      grid.add(gameButton("SPRING WINGS  ?  150 BUCKS", new Color(50, 143, 115)) { purchase(150, "Spring Wings") })
      grid.add(gameButton("DIAMOND INFO", new Color(158, 111, 47)) { JOptionPane.showMessageDialog(this, "Bixuu Diamonds are demo currency. No real-money purchase is available.") })
      panel.add(grid, BorderLayout.CENTER)
      panel.add(gameButton("BACK TO LOBBY", new Color(75, 91, 119)) { showLobby() }, BorderLayout.SOUTH)
      switchPage(panel)
    }

    private def purchase(cost: Int, item: String): Unit = {
      if (profile.bucks < cost) JOptionPane.showMessageDialog(this, "Not enough Bixuu Bucks. Complete parkour tasks to earn more.")
      else {
        profile = profile.copy(bucks = profile.bucks - cost, ownedCards = profile.ownedCards + item)
        LocalStore.save(profile)
        JOptionPane.showMessageDialog(this, item + " unlocked!")
        showShop()
      }
    }

    def showMultiplayer(): Unit = {
      val panel = pagePanel()
      panel.add(title("MULTIPLAYER ? FRIEND OBBY ROOM", 26), BorderLayout.NORTH)
      val status = new JLabel("Room status: Not connected", SwingConstants.CENTER)
      status.setForeground(Color.WHITE)
      val area = new JTextArea(10, 44)
      area.setEditable(false)
      area.setBackground(new Color(11, 22, 42))
      area.setForeground(new Color(226, 239, 255))
      val center = new JPanel(new BorderLayout(8, 8))
      center.setOpaque(false)
      center.add(status, BorderLayout.NORTH)
      center.add(new JScrollPane(area), BorderLayout.CENTER)
      val actions = new JPanel(new GridLayout(1, 3, 8, 8))
      actions.setOpaque(false)
      actions.add(gameButton("HOST ROOM", new Color(28, 131, 168)) {
        try {
          val ip = network.host(47821, (line: String) => handleNetworkLine(line, area))
          status.setText("Hosting at " + ip + ":47821  |  Max 12 friends")
          area.append("Room created. Share the IP with friends on the same trusted Wi-Fi.\n")
        } catch { case ex: Exception => JOptionPane.showMessageDialog(this, "Host failed: " + ex.getMessage) }
      })
      actions.add(gameButton("JOIN ROOM", new Color(105, 83, 166)) {
        val ip = JOptionPane.showInputDialog(this, "Enter host LAN IP:")
        if (ip != null && ip.trim.nonEmpty) {
          val portText = JOptionPane.showInputDialog(this, "Port:", "47821")
          val port = try { if (portText == null) 47821 else portText.trim.toInt } catch { case _: Exception => 47821 }
          try {
            network.join(ip.trim, port, (line: String) => handleNetworkLine(line, area))
            status.setText("Connected to " + ip.trim + ":" + port)
            area.append("Connected. Start the Obby to see your friends move.\n")
          } catch { case ex: Exception => JOptionPane.showMessageDialog(this, "Join failed: " + ex.getMessage) }
        }
      })
      actions.add(gameButton("LEAVE ROOM", new Color(140, 78, 97)) {
        network.stop()
        status.setText("Room status: Not connected")
        area.append("Disconnected.\n")
      })
      val bottom = new JPanel(new BorderLayout(8, 8))
      bottom.setOpaque(false)
      bottom.add(actions, BorderLayout.CENTER)
      bottom.add(gameButton("BACK TO LOBBY", new Color(75, 91, 119)) { showLobby() }, BorderLayout.SOUTH)
      panel.add(center, BorderLayout.CENTER)
      panel.add(bottom, BorderLayout.SOUTH)
      switchPage(panel)
    }

    private def handleNetworkLine(line: String, area: JTextArea): Unit = {
      if (line.startsWith("CHAT|")) area.append(line.substring(5) + "\n")
      else if (line.startsWith("SYSTEM|")) area.append(line.substring(7) + "\n")
      else if (line.startsWith("POS|")) {
        if (activeObby != null) activeObby.receiveNetworkLine(line)
      }
    }

    def showCardRoom(): Unit = {
      val panel = pagePanel()
      panel.add(title("PRIVATE FRIEND CARD ROOM", 25), BorderLayout.NORTH)
      val info = note("Coupon balance: " + profile.coupons + "  ?  Reach the tower trophy to earn a coupon.")
      val area = new JTextArea(10, 40)
      area.setEditable(false)
      val field = new JTextField()
      val send = gameButton("SEND CARD MESSAGE", new Color(27, 133, 143)) {
        val msg = field.getText.trim
        if (msg.nonEmpty) { network.send("CHAT|" + profile.name + ": " + msg); field.setText("") }
      }
      val row = new JPanel(new BorderLayout(6, 6))
      row.add(field, BorderLayout.CENTER)
      row.add(send, BorderLayout.EAST)
      val center = new JPanel(new BorderLayout(8, 8))
      center.setOpaque(false)
      center.add(info, BorderLayout.NORTH)
      center.add(new JScrollPane(area), BorderLayout.CENTER)
      center.add(row, BorderLayout.SOUTH)
      panel.add(center, BorderLayout.CENTER)
      val actions = new JPanel(new GridLayout(1, 2, 8, 8))
      actions.setOpaque(false)
      actions.add(gameButton("CREATE CARD ROOM (1 COUPON)", new Color(30, 127, 157)) {
        if (profile.coupons <= 0) JOptionPane.showMessageDialog(this, "Win the Obby Trophy first to earn a Card Room Coupon.")
        else {
          val portText = JOptionPane.showInputDialog(this, "Room port:", "47822")
          if (portText != null) {
            val port = try { portText.trim.toInt } catch { case _: Exception => 47822 }
            try {
              val ip = network.host(port, (line: String) => handleNetworkLine(line, area))
              profile = profile.copy(coupons = profile.coupons - 1)
              LocalStore.save(profile)
              area.append("Card room created at " + ip + ":" + port + "\n")
            } catch { case ex: Exception => JOptionPane.showMessageDialog(this, "Could not create room: " + ex.getMessage) }
          }
        }
      })
      actions.add(gameButton("BACK TO LOBBY", new Color(75, 91, 119)) { showLobby() })
      panel.add(actions, BorderLayout.SOUTH)
      switchPage(panel)
    }

    def startObby(): Unit = {
      if (activeObby != null) activeObby.stopGame()
      val game = new ObbyPanel(this)
      activeObby = game
      root.removeAll()
      root.add(game, BorderLayout.CENTER)
      root.revalidate()
      root.repaint()
      game.startGame()
      game.requestFocusInWindow()
    }

    def updateProgress(level: Int, coinsEarned: Int): Unit = {
      val newBest = math.max(profile.bestLevel, level)
      profile = profile.copy(bestLevel = newBest, bucks = profile.bucks + coinsEarned, totalCoins = profile.totalCoins + (if (coinsEarned > 0) 1 else 0))
      LocalStore.save(profile)
    }

    def parkourVictory(score: Int): Unit = {
      if (activeObby != null) { activeObby.stopGame(); activeObby = null }
      profile = profile.copy(
        bucks = profile.bucks + 500,
        diamonds = profile.diamonds + 25,
        trophies = profile.trophies + 1,
        coupons = profile.coupons + 1,
        wins = profile.wins + 1,
        bestLevel = math.max(profile.bestLevel, 18),
        ownedCards = profile.ownedCards + "Sky Champion"
      )
      LocalStore.save(profile)
      JOptionPane.showMessageDialog(this,
        "TROPHY UNLOCKED!\nParkour score: " + score + "\n+500 Bixuu Bucks\n+25 Bixuu Diamonds\n+1 Friend Card Room Coupon\nYour name is saved in the Winning List.",
        "BIXUU PARKOUR CHAMPION", JOptionPane.INFORMATION_MESSAGE)
      showLobby()
    }

    def closeGame(): Unit = {
      if (activeObby != null) activeObby.stopGame()
      network.stop()
      dispose()
    }
  }

  final class ObbyPanel(app: MainFrame) extends JPanel {
    private val platforms = Vector(
      Platform3D(0.0, 0.0, 0.0, 6.0, true),
      Platform3D(0.0, 2.3, 5.5, 5.5, false),
      Platform3D(3.8, 4.6, 10.5, 5.2, false),
      Platform3D(6.0, 6.9, 15.8, 5.2, true),
      Platform3D(2.0, 9.2, 21.0, 5.2, false),
      Platform3D(-2.8, 11.5, 26.2, 5.2, false),
      Platform3D(-6.0, 13.8, 31.5, 5.5, true),
      Platform3D(-3.0, 16.1, 36.8, 5.2, false),
      Platform3D(2.0, 18.4, 42.0, 5.2, false),
      Platform3D(6.0, 20.7, 47.2, 5.2, true),
      Platform3D(3.0, 23.0, 52.5, 5.2, false),
      Platform3D(-2.0, 25.3, 57.8, 5.2, false),
      Platform3D(-6.0, 27.6, 63.0, 5.5, true),
      Platform3D(-3.0, 29.9, 68.2, 5.2, false),
      Platform3D(2.0, 32.2, 73.5, 5.2, false),
      Platform3D(6.0, 34.5, 78.8, 5.2, true),
      Platform3D(3.0, 36.8, 84.0, 5.2, false),
      Platform3D(0.0, 39.1, 89.5, 9.0, true)
    )
    private val gems = mutable.ArrayBuffer[Gem3D]()
    private val pressed = mutable.Set[Int]()
    private val remotePlayers = mutable.Map[String, RemoteAvatar]()
    private val random = new Random(19)
    private val starPoints = (0 until 110).map(i => (random.nextInt(1600), random.nextInt(900), 1 + random.nextInt(3))).toVector
    private var playerX = 0.0
    private var playerY = 0.0
    private var playerZ = 0.0
    private var verticalSpeed = 0.0
    private var grounded = true
    private var checkpointIndex = 0
    private var currentPlatformIndex = 0
    private var bestLevelReached = 0
    private var cameraYaw = 0.0
    private var cameraPitch = -0.24
    private var dashFrames = 0
    private var shieldFrames = 0
    private var pulseFrames = 0
    private var health = 5
    private var score = 0
    private var collectedCoins = 0
    private var tickCount = 0
    private var hitCooldown = 0
    private var completed = false
    private var running = false
    private var paused = false
    private var jumpRequested = false
    private var interactRequested = false
    private var pulseRequested = false
    private var shieldRequested = false
    private var dashRequested = false
    private val gemValues = Vector(10, 15, 20, 10, 25, 15, 20, 30, 15, 25, 20, 35, 25, 30, 40, 25, 50)
    private var gemIndex = 0

    platforms.drop(1).foreach { p =>
      val value = gemValues(gemIndex % gemValues.length)
      gems += Gem3D(p.cx, p.cy + 0.9, p.cz, "BIXUU COIN", value)
      gemIndex += 1
    }

    private val hazards = Vector(4, 8, 12, 16)
    private val timer = new Timer(16, new ActionListener {
      override def actionPerformed(event: ActionEvent): Unit = updateGame()
    })

    setFocusable(true)
    setBackground(new Color(7, 12, 30))
    setPreferredSize(new Dimension(1200, 800))
    addKeyListener(new KeyAdapter {
      override def keyPressed(event: KeyEvent): Unit = {
        pressed += event.getKeyCode
        if (event.getKeyCode == KeyEvent.VK_P) { paused = !paused; repaint() }
        if (event.getKeyCode == KeyEvent.VK_SPACE) jumpRequested = true
        if (event.getKeyCode == KeyEvent.VK_E) interactRequested = true
        if (event.getKeyCode == KeyEvent.VK_F) pulseRequested = true
        if (event.getKeyCode == KeyEvent.VK_Q) shieldRequested = true
        if (event.getKeyCode == KeyEvent.VK_SHIFT) dashRequested = true
        if (event.getKeyCode == KeyEvent.VK_ESCAPE || event.getKeyCode == KeyEvent.VK_B) {
          stopGame()
          app.showLobby()
        }
      }
      override def keyReleased(event: KeyEvent): Unit = pressed -= event.getKeyCode
    })
    addMouseListener(new MouseAdapter {
      override def mousePressed(event: MouseEvent): Unit = {
        if (event.getButton == MouseEvent.BUTTON1 && event.getY > getHeight / 3) {
          if (event.getX < getWidth / 2) pressed += KeyEvent.VK_A else pressed += KeyEvent.VK_D
          if (event.getY < getHeight * 2 / 3) jumpRequested = true
        }
      }
      override def mouseReleased(event: MouseEvent): Unit = {
        pressed -= KeyEvent.VK_A
        pressed -= KeyEvent.VK_D
      }
    })
    private var lastDragX = -1
    private var lastDragY = -1
    addMouseMotionListener(new java.awt.event.MouseMotionAdapter {
      override def mouseDragged(event: MouseEvent): Unit = {
        if (lastDragX >= 0) cameraYaw += (event.getX - lastDragX).toDouble * 0.008
        if (lastDragY >= 0) cameraPitch = math.max(-0.62, math.min(-0.06,
          cameraPitch + (event.getY - lastDragY).toDouble * 0.0025))
        lastDragX = event.getX
        lastDragY = event.getY
        repaint()
      }
    })
    addMouseListener(new MouseAdapter {
      override def mouseReleased(event: MouseEvent): Unit = { lastDragX = -1; lastDragY = -1 }
    })
    addFocusListener(new java.awt.event.FocusAdapter {
      override def focusLost(event: java.awt.event.FocusEvent): Unit = {
        pressed.clear(); lastDragX = -1; lastDragY = -1
      }
    })

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

    private def updateGame(): Unit = {
      if (!running || paused || completed) return
      tickCount += 1
      if (pressed.contains(KeyEvent.VK_LEFT)) cameraYaw -= 0.018
      if (pressed.contains(KeyEvent.VK_RIGHT)) cameraYaw += 0.018
      var moveX = 0.0
      var moveZ = 0.0
      if (pressed.contains(KeyEvent.VK_A) || pressed.contains(KeyEvent.VK_LEFT)) moveX -= 0.17
      if (pressed.contains(KeyEvent.VK_D) || pressed.contains(KeyEvent.VK_RIGHT)) moveX += 0.17
      if (pressed.contains(KeyEvent.VK_W) || pressed.contains(KeyEvent.VK_UP)) moveZ += 0.18
      if (pressed.contains(KeyEvent.VK_S) || pressed.contains(KeyEvent.VK_DOWN)) moveZ -= 0.16
      val length = math.sqrt(moveX * moveX + moveZ * moveZ)
      if (length > 0.0) {
        moveX = moveX / length * 0.19
        moveZ = moveZ / length * 0.19
      }
      val speedMultiplier = if (dashFrames > 0 || dashRequested) 1.85 else 1.0
      playerX += moveX * speedMultiplier
      playerZ += moveZ * speedMultiplier
      if (dashRequested && dashFrames <= 0) dashFrames = 16
      if (dashFrames > 0) dashFrames -= 1
      dashRequested = false

      if (grounded) {
        val support = platforms(currentPlatformIndex)
        val stillOnPlatform = math.abs(playerX - support.cx) <= support.size / 2.0 - 0.25 &&
          math.abs(playerZ - support.cz) <= support.size / 2.0 - 0.25
        if (!stillOnPlatform) { grounded = false; verticalSpeed = 0.0 }
      }
      if (jumpRequested && grounded) {
        verticalSpeed = 0.53
        grounded = false
      }
      jumpRequested = false
      val previousY = playerY
      if (!grounded) {
        playerY += verticalSpeed
        verticalSpeed -= 0.022
      }
      if (!grounded && verticalSpeed <= 0.0) {
        var i = 0
        var landed = false
        while (i < platforms.length && !landed) {
          val p = platforms(i)
          val insideX = math.abs(playerX - p.cx) <= p.size / 2.0 - 0.35
          val insideZ = math.abs(playerZ - p.cz) <= p.size / 2.0 - 0.35
          if (insideX && insideZ && previousY >= p.cy && playerY <= p.cy) {
            playerY = p.cy
            verticalSpeed = 0.0
            grounded = true
            landed = true
            currentPlatformIndex = i
            if (i > bestLevelReached) {
              bestLevelReached = i
              score += i * 10
              app.updateProgress(i, 0)
            }
            if (p.checkpoint && i >= checkpointIndex) checkpointIndex = i
          }
          i += 1
        }
      }
      if (playerY < platforms(checkpointIndex).cy - 8.0) respawn()

      if (pulseRequested && pulseFrames <= 0) { pulseFrames = 22; score += 5 }
      if (shieldRequested && shieldFrames <= 0) shieldFrames = 60
      if (pulseFrames > 0) pulseFrames -= 1
      if (shieldFrames > 0) shieldFrames -= 1
      pulseRequested = false
      shieldRequested = false

      var gi = gems.length - 1
      while (gi >= 0) {
        val gem = gems(gi)
        if (math.abs(playerX - gem.x) < 1.5 && math.abs(playerZ - gem.z) < 1.7 && math.abs(playerY - (gem.y - 0.9)) < 1.4) {
          collectedCoins += 1
          score += gem.value
          app.updateProgress(currentPlatformIndex, gem.value)
          gems.remove(gi)
        }
        gi -= 1
      }
      if (hitCooldown > 0) hitCooldown -= 1
      if (hitCooldown <= 0 && shieldFrames <= 0 && hazards.contains(currentPlatformIndex) && grounded) {
        if (tickCount % 150 < 18 && currentPlatformIndex > checkpointIndex) {
          health -= 1
          hitCooldown = 55
          respawn()
        }
      }
      if (interactRequested && currentPlatformIndex == platforms.length - 1 && grounded) {
        completed = true
        stopGame()
        app.parkourVictory(score)
      }
      interactRequested = false
      if (tickCount % 5 == 0 && app.networkActive) {
        app.sendPosition(playerX, playerY, playerZ, currentPlatformIndex)
      }
      repaint()
    }

    private def respawn(): Unit = {
      val p = platforms(checkpointIndex)
      playerX = p.cx
      playerY = p.cy
      playerZ = p.cz
      currentPlatformIndex = checkpointIndex
      verticalSpeed = 0.0
      grounded = true
      health = math.max(1, health - 1)
      hitCooldown = 60
      repaint()
    }

    private def project(worldX: Double, worldY: Double, worldZ: Double): Point3D = {
      val dx = worldX - playerX
      val dy = worldY - (playerY + 5.4)
      val dz = worldZ - (playerZ - 13.0)
      val cosYaw = math.cos(cameraYaw)
      val sinYaw = math.sin(cameraYaw)
      val rotatedX = dx * cosYaw - dz * sinYaw
      val rotatedZ = dx * sinYaw + dz * cosYaw
      val pitch = cameraPitch
      val cosPitch = math.cos(pitch)
      val sinPitch = math.sin(pitch)
      val vertical = dy * cosPitch - rotatedZ * sinPitch
      val depth = math.max(2.5, rotatedZ * cosPitch + dy * sinPitch + 16.0)
      val focal = math.min(getWidth.toDouble, getHeight.toDouble) * 0.92
      val scale = focal / depth
      Point3D((getWidth.toDouble / 2.0 + rotatedX * scale).toInt,
        (getHeight.toDouble * 0.62 - vertical * scale).toInt, scale, depth)
    }

    private def averageDepth(points: Vector[(Double, Double, Double)]): Double = {
      var total = 0.0
      points.foreach { v => total += project(v._1, v._2, v._3).depth }
      total / math.max(1, points.length)
    }

    private def drawFace(g: Graphics2D, points: Vector[(Double, Double, Double)], color: Color): Unit = {
      if (points.length >= 3) {
        val projected = points.map(v => project(v._1, v._2, v._3))
        val poly = new Polygon()
        projected.foreach(p => poly.addPoint(p.sx, p.sy))
        g.setColor(color)
        g.fillPolygon(poly)
        g.setColor(new Color(color.brighter().getRed, color.brighter().getGreen, color.brighter().getBlue, 175))
        g.setStroke(new BasicStroke(0.8f))
        g.drawPolygon(poly)
      }
    }

    // A complete six-face cuboid. Faces are painter-sorted by camera depth.
    private def drawBox(g: Graphics2D, cx: Double, cy: Double, cz: Double,
                        sx: Double, sy: Double, sz: Double, color: Color): Unit = {
      val x1 = cx - sx / 2.0
      val x2 = cx + sx / 2.0
      val y1 = cy
      val y2 = cy + sy
      val z1 = cz - sz / 2.0
      val z2 = cz + sz / 2.0
      val faces = Vector(
        Vector((x1,y1,z2),(x2,y1,z2),(x2,y2,z2),(x1,y2,z2)) -> color.darker(),
        Vector((x2,y1,z1),(x1,y1,z1),(x1,y2,z1),(x2,y2,z1)) -> color.darker().darker(),
        Vector((x2,y1,z1),(x2,y1,z2),(x2,y2,z2),(x2,y2,z1)) -> color.darker(),
        Vector((x1,y1,z2),(x1,y1,z1),(x1,y2,z1),(x1,y2,z2)) -> color.darker(),
        Vector((x1,y2,z1),(x2,y2,z1),(x2,y2,z2),(x1,y2,z2)) -> color.brighter(),
        Vector((x1,y1,z1),(x2,y1,z1),(x2,y1,z2),(x1,y1,z2)) -> color.darker().darker()
      )
      val sortedFaces = faces.map { item =>
        RenderFace3D(item._1, item._2, averageDepth(item._1))
      }.sortBy(face => -face.depth)
      sortedFaces.foreach(face => drawFace(g, face.points, face.color))
    }

    // Faceted sphere mesh used for the avatar head, power orbs and crystals.
    private def drawSphere(g: Graphics2D, cx: Double, cy: Double, cz: Double,
                           radius: Double, base: Color, rings: Int, slices: Int): Unit = {
      val faces = mutable.ArrayBuffer[RenderFace3D]()
      var ring = 0
      while (ring < rings) {
        val a0 = math.Pi * ring.toDouble / rings.toDouble
        val a1 = math.Pi * (ring + 1).toDouble / rings.toDouble
        var slice = 0
        while (slice < slices) {
          val b0 = 2.0 * math.Pi * slice.toDouble / slices.toDouble
          val b1 = 2.0 * math.Pi * (slice + 1).toDouble / slices.toDouble
          def vertex(a: Double, b: Double): (Double, Double, Double) = {
            (cx + radius * math.sin(a) * math.cos(b),
             cy + radius * math.cos(a),
             cz + radius * math.sin(a) * math.sin(b))
          }
          val quad = Vector(vertex(a0,b0), vertex(a0,b1), vertex(a1,b1), vertex(a1,b0))
          val light = 0.72 + 0.28 * (0.5 + 0.5 * math.cos((b0 + b1) * 0.5))
          val shade = new Color(
            math.max(0, math.min(255, (base.getRed.toDouble * light).toInt)),
            math.max(0, math.min(255, (base.getGreen.toDouble * light).toInt)),
            math.max(0, math.min(255, (base.getBlue.toDouble * light).toInt)), base.getAlpha)
          faces += RenderFace3D(quad, shade, averageDepth(quad))
          slice += 1
        }
        ring += 1
      }
      faces.sortBy(face => -face.depth).foreach(face => drawFace(g, face.points, face.color))
    }

    private def drawCrystalMesh(g: Graphics2D, x: Double, y: Double, z: Double, radius: Double): Unit = {
      val top = (x, y + radius * 1.45, z)
      val bottom = (x, y - radius * 1.15, z)
      val front = (x, y, z + radius)
      val back = (x, y, z - radius)
      val left = (x - radius * 0.72, y, z)
      val right = (x + radius * 0.72, y, z)
      val faces = Vector(
        Vector(top, front, right), Vector(top, right, back),
        Vector(top, back, left), Vector(top, left, front),
        Vector(bottom, right, front), Vector(bottom, back, right),
        Vector(bottom, left, back), Vector(bottom, front, left)
      )
      faces.map(face => RenderFace3D(face, new Color(82, 230, 255), averageDepth(face)))
        .sortBy(face => -face.depth).foreach(face => drawFace(g, face.points, face.color))
    }

    private def drawPlatform(g: Graphics2D, p: Platform3D, index: Int): Unit = {
      val baseColor = if (index % 3 == 0) new Color(35, 117, 145)
        else if (index % 3 == 1) new Color(52, 91, 151)
        else new Color(69, 81, 149)
      drawBox(g, p.cx, p.cy - 0.65, p.cz, p.size, 0.65, p.size, baseColor)
      val half = p.size * 0.43
      val corners = Vector(
        project(p.cx - half, p.cy + 0.025, p.cz - half),
        project(p.cx + half, p.cy + 0.025, p.cz - half),
        project(p.cx + half, p.cy + 0.025, p.cz + half),
        project(p.cx - half, p.cy + 0.025, p.cz + half)
      )
      g.setColor(new Color(111, 236, 255, 210))
      g.setStroke(new BasicStroke(2.0f))
      g.drawLine(corners(0).sx, corners(0).sy, corners(1).sx, corners(1).sy)
      g.drawLine(corners(1).sx, corners(1).sy, corners(2).sx, corners(2).sy)
      g.drawLine(corners(2).sx, corners(2).sy, corners(3).sx, corners(3).sy)
      g.drawLine(corners(3).sx, corners(3).sy, corners(0).sx, corners(0).sy)
      val center = project(p.cx, p.cy + 0.04, p.cz)
      g.setColor(new Color(140, 233, 255, 105))
      g.drawOval(center.sx - math.max(3, (center.scale * 0.44).toInt),
        center.sy - math.max(2, (center.scale * 0.20).toInt),
        math.max(6, (center.scale * 0.88).toInt), math.max(4, (center.scale * 0.40).toInt))
      if (p.checkpoint) {
        drawBox(g, p.cx, p.cy + 0.03, p.cz, 0.10, 1.9, 0.10, new Color(255, 199, 76))
        drawBox(g, p.cx + 0.35, p.cy + 1.48, p.cz, 0.78, 0.38, 0.08, new Color(255, 211, 91))
      }
    }

    private def drawGem(g: Graphics2D, gem: Gem3D): Unit = {
      val bob = math.sin(tickCount.toDouble * 0.08 + gem.z) * 0.16
      val y = gem.y + bob
      val p = project(gem.x, y, gem.z)
      if (p.depth > 1.0 && p.scale > 2.0) {
        val size = math.max(0.22, math.min(0.72, p.scale * 0.012))
        val glow = math.max(5, math.min(28, (p.scale * 0.30).toInt))
        g.setColor(new Color(78, 214, 255, 48))
        g.fillOval(p.sx - glow, p.sy - glow, glow * 2, glow * 2)
        drawCrystalMesh(g, gem.x, y, gem.z, size)
        g.setColor(new Color(231, 250, 255, 190))
        g.drawOval(p.sx - glow / 2, p.sy - glow / 2, glow, glow)
      }
    }

    private def heroColor: Color = {
      app.selectedHero match {
        case "Nova Runner" => new Color(50, 193, 245)
        case "Volt Mage" => new Color(166, 111, 240)
        case "Aurora Guard" => new Color(67, 198, 132)
        case "Cyber Scout" => new Color(238, 166, 67)
        case "Titan Cub" => new Color(218, 111, 91)
        case _ => new Color(100, 171, 235)
      }
    }

    private def drawCharacter(g: Graphics2D, wx: Double, wy: Double, wz: Double, color: Color, phase: Double, remote: Boolean): Unit = {
      val foot = project(wx, wy, wz)
      val bob = if (remote) 0.0 else math.sin(phase) * 0.045
      val bodyY = wy + bob
      val size = math.max(9.0, math.min(26.0, foot.scale * 0.42))
      g.setColor(new Color(0, 0, 0, 90))
      g.fillOval(foot.sx - (size * 0.72).toInt, foot.sy - 2, (size * 1.44).toInt, math.max(4, (size * 0.34).toInt))
      if (!remote && shieldFrames > 0) {
        g.setColor(new Color(86, 223, 255, 55))
        g.fillOval(foot.sx - (size * 1.3).toInt, foot.sy - (size * 3.4).toInt, (size * 2.6).toInt, (size * 3.5).toInt)
        g.setColor(new Color(124, 238, 255, 190))
        g.setStroke(new BasicStroke(2.0f))
        g.drawOval(foot.sx - (size * 1.3).toInt, foot.sy - (size * 3.4).toInt, (size * 2.6).toInt, (size * 3.5).toInt)
      }
      val swing = if (app.selectedAnimation == "Ninja Vault") math.sin(phase * 1.8) * 0.24 else math.sin(phase) * 0.13
      val hover = if (app.selectedAnimation == "Robot Hover") 0.20 else 0.0
      val dark = color.darker()
      val boot = new Color(25, 32, 48)
      drawBox(g, wx - 0.18 + swing, bodyY + 0.06 + hover, wz, 0.25, 0.52, 0.30, dark)
      drawBox(g, wx + 0.18 - swing, bodyY + 0.06 + hover, wz, 0.25, 0.52, 0.30, dark)
      drawBox(g, wx - 0.18 + swing, bodyY + 0.02 + hover, wz + 0.08, 0.30, 0.17, 0.42, boot)
      drawBox(g, wx + 0.18 - swing, bodyY + 0.02 + hover, wz + 0.08, 0.30, 0.17, 0.42, boot)
      drawBox(g, wx, bodyY + 0.58 + hover, wz, 0.78, 0.86, 0.48, color)
      drawBox(g, wx, bodyY + 0.48 + hover, wz + 0.015, 0.82, 0.16, 0.50, new Color(30, 39, 58))
      drawBox(g, wx - 0.49, bodyY + 0.58 + hover + math.sin(phase) * 0.12, wz, 0.23, 0.68, 0.25, color.brighter())
      drawBox(g, wx + 0.49, bodyY + 0.58 + hover - math.sin(phase) * 0.12, wz, 0.23, 0.68, 0.25, color.brighter())
      drawBox(g, wx, bodyY + 0.82 + hover, wz - 0.31, 0.52, 0.60, 0.18, new Color(38, 53, 82))
      drawSphere(g, wx, bodyY + 1.63 + hover, wz, 0.34, new Color(235, 192, 154), 8, 12)
      drawBox(g, wx, bodyY + 1.83 + hover, wz, 0.70, 0.19, 0.48, color.darker())
      drawBox(g, wx, bodyY + 1.70 + hover, wz + 0.295, 0.47, 0.10, 0.055, new Color(31, 43, 66))
      val eyeLeft = project(wx - 0.105, bodyY + 1.65 + hover, wz + 0.327)
      val eyeRight = project(wx + 0.105, bodyY + 1.65 + hover, wz + 0.327)
      val eyeSize = math.max(2, math.min(5, (foot.scale * 0.075).toInt))
      g.setColor(new Color(235, 250, 255))
      g.fillOval(eyeLeft.sx - eyeSize / 2, eyeLeft.sy - eyeSize / 2, eyeSize, eyeSize)
      g.fillOval(eyeRight.sx - eyeSize / 2, eyeRight.sy - eyeSize / 2, eyeSize, eyeSize)
      if (!remote && app.selectedAnimation == "Ninja Vault") {
        g.setColor(new Color(167, 115, 255, 150))
        g.setStroke(new BasicStroke(4.0f))
        g.drawLine(foot.sx - 12, foot.sy - 26, foot.sx - 42, foot.sy - 48)
      }
      if (!remote && app.selectedAnimation == "Robot Hover") {
        g.setColor(new Color(99, 232, 237, 185))
        g.drawOval(foot.sx - 18, foot.sy - 5, 36, 10)
      }
      val namePoint = project(wx, bodyY + 2.25 + hover, wz)
      g.setFont(new Font("SansSerif", Font.BOLD, 11))
      g.setColor(new Color(245, 250, 255, 220))
      if (remote) g.drawString("FRIEND", namePoint.sx - 19, namePoint.sy)
      else g.drawString(app.profile.name, namePoint.sx - 22, namePoint.sy)
    }

    private def drawTrophy(g: Graphics2D, platform: Platform3D): Unit = {
      val x = platform.cx
      val y = platform.cy
      val z = platform.cz
      drawBox(g, x, y + 0.02, z, 1.8, 0.32, 1.8, new Color(59, 73, 111))
      drawBox(g, x, y + 0.34, z, 0.82, 0.18, 0.82, new Color(255, 194, 44))
      drawBox(g, x, y + 0.52, z, 0.48, 0.82, 0.42, new Color(255, 202, 52))
      drawBox(g, x, y + 1.28, z, 0.78, 0.18, 0.62, new Color(255, 220, 93))
      drawSphere(g, x, y + 1.78, z, 0.30, new Color(255, 219, 81), 8, 12)
      drawSphere(g, x - 0.54, y + 0.95, z, 0.24, new Color(255, 190, 45), 7, 10)
      drawSphere(g, x + 0.54, y + 0.95, z, 0.24, new Color(255, 190, 45), 7, 10)
      val p = project(x, y + 2.15, z)
      val glow = math.max(12, math.min(55, (p.scale * 0.72).toInt))
      g.setColor(new Color(255, 211, 84, 50))
      g.fillOval(p.sx - glow, p.sy - glow, glow * 2, glow * 2)
    }

    private def drawWorldDecorations(g: Graphics2D): Unit = {
      var i = 0
      while (i < 6) {
        val z = playerZ + 8.0 + i.toDouble * 15.0
        val height = 4.0 + (i % 3).toDouble * 1.8
        val leftX = -12.0 - (i % 2).toDouble * 1.7
        val rightX = 12.0 + (i % 2).toDouble * 1.7
        drawBox(g, leftX, -1.2, z, 1.4, height, 1.4, new Color(43, 58, 94))
        drawBox(g, rightX, -1.2, z + 5.0, 1.4, height + 2.0, 1.4, new Color(49, 55, 103))
        drawSphere(g, leftX, height + 0.2, z, 0.72, new Color(76, 126, 151), 6, 9)
        drawSphere(g, rightX, height + 1.4, z + 5.0, 0.78, new Color(95, 99, 161), 6, 9)
        i += 1
      }
      // Tall gateway pillars near the summit make the tower feel like a 3D world.
      val gateZ = platforms.last.cz - 2.2
      drawBox(g, -4.0, platforms.last.cy, gateZ, 0.55, 5.0, 0.65, new Color(90, 117, 160))
      drawBox(g, 4.0, platforms.last.cy, gateZ, 0.55, 5.0, 0.65, new Color(90, 117, 160))
      drawBox(g, 0.0, platforms.last.cy + 4.7, gateZ, 8.4, 0.55, 0.65, new Color(122, 142, 202))
    }

    private def drawBackground(g: Graphics2D): Unit = {
      val w = getWidth
      val h = getHeight
      g.setPaint(new GradientPaint(0, 0, new Color(10, 15, 42), 0, h, new Color(42, 63, 100)))
      g.fillRect(0, 0, w, h)
      var i = 0
      while (i < 95) {
        val sx = (i * 137 + tickCount / (1 + i % 4)) % math.max(1, w)
        val sy = (i * 71 + 19) % math.max(1, h / 2)
        val alpha = 70 + (i % 4) * 35
        g.setColor(new Color(205, 226, 255, alpha))
        g.fillOval(sx, sy, 1 + i % 3, 1 + i % 3)
        i += 1
      }
      g.setColor(new Color(85, 72, 151, 70))
      g.fillOval(w - 230, 45, 150, 150)
      g.setColor(new Color(196, 186, 255, 175))
      g.drawOval(w - 230, 45, 150, 150)
      g.setColor(new Color(16, 29, 59, 165))
      g.fillOval(-80, h * 52 / 100, w + 160, h * 55 / 100)
    }

    private def drawHud(g: Graphics2D): Unit = {
      val w = getWidth
      val h = getHeight
      g.setColor(new Color(5, 11, 27, 205))
      g.fillRoundRect(14, 14, 390, 112, 18, 18)
      g.setColor(new Color(235, 245, 255))
      g.setFont(new Font("SansSerif", Font.BOLD, 16))
      g.drawString("BIXUU WARRIOR REALMS ? 3D SQUARE OBBY", 29, 39)
      g.setFont(new Font("SansSerif", Font.PLAIN, 13))
      g.drawString("Player: " + app.profile.name + "  |  Hero: " + app.selectedHero, 29, 61)
      g.drawString("Animation: " + app.selectedAnimation + "  |  Coins: " + collectedCoins, 29, 82)
      g.drawString("Checkpoint: " + (currentPlatformIndex + 1) + "/" + platforms.length + "  |  Score: " + score + "  |  Health: " + health, 29, 104)
      g.setColor(new Color(5, 11, 27, 190))
      g.fillRoundRect(w - 310, 14, 294, 97, 17, 17)
      g.setColor(new Color(174, 219, 255))
      g.setFont(new Font("SansSerif", Font.BOLD, 13))
      g.drawString("WASD Move   SPACE Jump   SHIFT Dash", w - 294, 38)
      g.drawString("F Pulse   Q Shield   E Trophy", w - 294, 61)
      g.drawString("Drag Mouse Rotate / Tilt Camera   P Pause   B Back", w - 294, 84)
      if (paused) {
        g.setColor(new Color(3, 7, 18, 205))
        g.fillRect(0, 0, w, h)
        g.setColor(Color.WHITE)
        g.setFont(new Font("SansSerif", Font.BOLD, 38))
        g.drawString("PAUSED", w / 2 - 75, h / 2)
        g.setFont(new Font("SansSerif", Font.PLAIN, 16))
        g.drawString("Press P to resume ? B to return to lobby", w / 2 - 165, h / 2 + 34)
      }
    }

    override def paintComponent(graphics: Graphics): Unit = {
      super.paintComponent(graphics)
      val g = graphics.asInstanceOf[Graphics2D]
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
      g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
      g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
      drawBackground(g)
      drawWorldDecorations(g)
      val sorted = platforms.sortBy(p => -project(p.cx, p.cy, p.cz).depth)
      sorted.foreach { p =>
        val index = platforms.indexOf(p)
        if (p.cy <= playerY + 18.0 && p.cy >= playerY - 22.0) drawPlatform(g, p, index)
      }
      gems.foreach(gem => drawGem(g, gem))
      remotePlayers.values.foreach(r => drawCharacter(g, r.x, r.y, r.z, new Color(242, 174, 74), tickCount.toDouble * 0.08, true))
      drawCharacter(g, playerX, playerY, playerZ, app.heroColor, tickCount.toDouble * 0.11, false)
      if (currentPlatformIndex == platforms.length - 1) drawTrophy(g, platforms.last)
      drawHud(g)
      if (completed) {
        g.setColor(new Color(255, 216, 83))
        g.setFont(new Font("SansSerif", Font.BOLD, 30))
        g.drawString("TROPHY UNLOCKED!", getWidth / 2 - 145, getHeight / 2)
      }
    }

    def receiveNetworkLine(line: String): Unit = {
      val parts = line.split("\\|", -1)
      if (parts.length == 6 && parts(0) == "POS") {
        try {
          val remote = RemoteAvatar(parts(1), parts(2).toDouble, parts(3).toDouble, parts(4).toDouble, parts(5).toInt)
          remotePlayers.update(remote.name, remote)
        } catch { case _: Exception => () }
      }
      repaint()
    }
  }
}

BixuuWarriorRealms.main(Array[String]())