Code Sketch


Bixuu Cricket League trial
By: Mhalsakant School
Category: Programming
import java.awt.{BasicStroke, BorderLayout, CardLayout, Color, Dimension, Font, GradientPaint, Graphics, Graphics2D, Polygon, RenderingHints}
import java.awt.event.{ActionEvent, ActionListener, KeyAdapter, KeyEvent, MouseAdapter, MouseEvent, MouseMotionAdapter, MouseWheelEvent, MouseWheelListener, WindowAdapter, WindowEvent}
import java.awt.geom.{Ellipse2D, RoundRectangle2D}
import java.io.{File, FileInputStream, FileOutputStream}
import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.util.{Date, Properties}
import javax.swing.{BorderFactory, Box, BoxLayout, JButton, JComboBox, JFrame, JLabel, JOptionPane, JPanel, JPasswordField, JScrollPane, JTextArea, JTextField, SwingConstants, Timer, WindowConstants}
import scala.collection.mutable.ArrayBuffer
import scala.util.Random

object BixuuCricketLeague {
  private val BG = new Color(7, 17, 31)
  private val PANEL = new Color(17, 34, 55)
  private val PANEL2 = new Color(25, 49, 73)
  private val CYAN = new Color(64, 219, 225)
  private val GOLD = new Color(255, 197, 76)
  private val WHITE = new Color(246, 249, 252)
  private val MUTED = new Color(169, 189, 209)
  private val GREEN = new Color(47, 178, 116)
  private val RED = new Color(222, 82, 91)
  private val BLUE = new Color(55, 132, 207)

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

  private def button(text: String, fill: Color): JButton = {
    val b = new JButton(text)
    b.setFont(new Font("SansSerif", Font.BOLD, 13))
    b.setForeground(WHITE)
    b.setBackground(fill)
    b.setFocusPainted(false)
    b.setOpaque(true)
    b.setBorder(BorderFactory.createCompoundBorder(
      BorderFactory.createLineBorder(new Color(77, 112, 144), 1),
      BorderFactory.createEmptyBorder(8, 12, 8, 12)))
    b
  }

  private def heading(text: String, size: Int): JLabel = {
    val l = new JLabel(text)
    l.setForeground(WHITE)
    l.setFont(new Font("SansSerif", Font.BOLD, size))
    l
  }

  private def label(text: String): JLabel = {
    val l = new JLabel(text)
    l.setForeground(MUTED)
    l.setFont(new Font("SansSerif", Font.PLAIN, 13))
    l
  }

  private def darkPanel(): JPanel = {
    val p = new JPanel()
    p.setBackground(BG)
    p.setOpaque(true)
    p
  }

  private def hashPassword(chars: Array[Char]): String = {
    val raw = new String(chars)
    val bytes = MessageDigest.getInstance("SHA-256").digest(raw.getBytes("UTF-8"))
    val out = new StringBuilder
    var i = 0
    while (i < bytes.length) {
      val v = bytes(i) & 255
      val h = java.lang.Integer.toHexString(v)
      if (h.length == 1) out.append("0")
      out.append(h)
      i += 1
    }
    java.util.Arrays.fill(chars, 0.toChar)
    out.toString
  }

  private def safeInt(value: String, fallback: Int): Int = {
    try value.toInt catch { case _: Exception => fallback }
  }

  class CricketApp extends JFrame {
    private val profileFile = new File(System.getProperty("user.home"), ".bixuu_cricket_league_matchplay.properties")
    private val profiles = new Properties()
    private var playerId = ""
    private var playerName = ""
    private var bucks = 500
    private var diamonds = 50
    private var trophies = 0
    private var wins = 0
    private var teamName = "Bixuu Blasters"
    private var captainName = "Aarav Mehta"
    private var couponCount = 0
    private var selectedMode = "Quick T20"
    private var selectedOpponent = "New Zealand"
    private var selectedOvers = 2
    private var selectedField = "BALANCED"
    private var selectedCaptain = "Aarav Mehta"
    private var battingFirst = true
    private var tossDone = false
    private var tossWon = false
    private var claimedRewardDay = 0
    private var lastRewardDate = ""
    private var trainingTokens = 0
    private var hasRcbTeamCard = false
    private var lastResult = "No match played yet."

    private val rootLayout = new CardLayout()
    private val root = new JPanel(rootLayout)
    private val nameField = new JTextField(20)
    private val idField = new JTextField(20)
    private val passwordField = new JPasswordField(20)
    private val lobbyStats = new JLabel(" ")
    private val teamNameField = new JTextField("Bixuu Blasters", 20)
    private val teamCaptainBox = new JComboBox[String](Vector("Aarav Mehta", "Kabir Rao", "Reyansh Shah", "Vivaan Patil", "Ishaan Das", "Arjun Nair", "Dev Malhotra", "Neil Kulkarni", "Rohan Iyer", "Aditya Sen", "Yuvaan Joshi").toArray)
    private val modeBox = new JComboBox[String](Vector("Quick T20", "Bixuu Premier League", "World Cup", "Practice Match", "Custom Friendly").toArray)
    private val opponentBox = new JComboBox[String](Vector("India", "Bangladesh", "New Zealand", "England", "Pakistan", "Australia", "South Africa", "Sri Lanka", "Afghanistan").toArray)
    private val oversBox = new JComboBox[String](Vector("2 Overs (Quick Match)", "5 Overs", "10 Overs", "20 Overs").toArray)
    private val captainBox = new JComboBox[String](Vector("Aarav Mehta", "Kabir Rao", "Reyansh Shah", "Vivaan Patil", "Ishaan Das", "Arjun Nair", "Dev Malhotra", "Neil Kulkarni", "Rohan Iyer", "Aditya Sen", "Yuvaan Joshi").toArray)
    private val fieldBox = new JComboBox[String](Vector("BALANCED", "ATTACKING", "BOUNDARY DEFENCE", "SPIN TRAP").toArray)
    private val tossResult = new JLabel("Call HEADS or TAILS to begin the toss.")
    private val tossChoice = new JLabel("The toss winner chooses to bat or bowl.")
    private val continueToss = button("CONTINUE TO MATCH", GREEN)
    private var rewardsPage: JPanel = null
    private val resultTitle = heading("MATCH RESULT", 28)
    private val resultDetails = label(" ")
    private val matchPanel = new CricketMatchPanel(this)
    private val cardRoomStatus = new JLabel("Friend card room: not connected.")

    loadProfiles()
    setTitle("BIXUU CRICKET LEAGUE ? MATCH PLAY")
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
    setMinimumSize(new Dimension(1100, 760))
    setSize(1280, 850)
    setLocationRelativeTo(null)
    setContentPane(root)

    root.add(buildLoginPage(), "login")
    root.add(buildLobbyPage(), "lobby")
    root.add(buildTeamPage(), "team")
    root.add(buildMatchCenter(), "matchcenter")
    root.add(buildTossPage(), "toss")
    root.add(matchPanel, "match")
    root.add(buildResultPage(), "result")
    root.add(buildRewardsPage(), "rewards")
    rootLayout.show(root, "login")

    addWindowListener(new WindowAdapter {
      override def windowClosing(e: WindowEvent): Unit = matchPanel.stopMatch()
    })

    private def profileKey(id: String, field: String): String = "user." + id + "." + field

    private def loadProfiles(): Unit = {
      if (profileFile.exists()) {
        var in: FileInputStream = null
        try {
          in = new FileInputStream(profileFile)
          profiles.load(in)
        } catch { case _: Exception => () }
        finally { if (in != null) try in.close() catch { case _: Exception => () } }
      }
    }

    private def saveProfiles(): Unit = {
      var out: FileOutputStream = null
      try {
        out = new FileOutputStream(profileFile)
        profiles.store(out, "Bixuu Cricket League local profile data")
      } catch { case _: Exception => JOptionPane.showMessageDialog(this, "Could not save profile: " + profileFile.getName) }
      finally { if (out != null) try out.close() catch { case _: Exception => () } }
    }

    private def loadProfile(id: String): Unit = {
      playerId = id
      playerName = profiles.getProperty(profileKey(id, "name"), "Cricket Player")
      bucks = safeInt(profiles.getProperty(profileKey(id, "bucks"), "500"), 500)
      diamonds = safeInt(profiles.getProperty(profileKey(id, "diamonds"), "50"), 50)
      trophies = safeInt(profiles.getProperty(profileKey(id, "trophies"), "0"), 0)
      wins = safeInt(profiles.getProperty(profileKey(id, "wins"), "0"), 0)
      teamName = profiles.getProperty(profileKey(id, "team"), "Bixuu Blasters")
      captainName = profiles.getProperty(profileKey(id, "captain"), "Aarav Mehta")
      couponCount = safeInt(profiles.getProperty(profileKey(id, "coupons"), "0"), 0)
      claimedRewardDay = safeInt(profiles.getProperty(profileKey(id, "rewardDay"), "0"), 0)
      lastRewardDate = profiles.getProperty(profileKey(id, "lastRewardDate"), "")
      trainingTokens = safeInt(profiles.getProperty(profileKey(id, "tokens"), "0"), 0)
      hasRcbTeamCard = profiles.getProperty(profileKey(id, "rcbCard"), "false").equalsIgnoreCase("true")
      teamNameField.setText(teamName)
      updateLobbyStats()
    }

    private def saveProfile(): Unit = {
      if (playerId.nonEmpty) {
        profiles.setProperty(profileKey(playerId, "name"), playerName)
        profiles.setProperty(profileKey(playerId, "bucks"), bucks.toString)
        profiles.setProperty(profileKey(playerId, "diamonds"), diamonds.toString)
        profiles.setProperty(profileKey(playerId, "trophies"), trophies.toString)
        profiles.setProperty(profileKey(playerId, "wins"), wins.toString)
        profiles.setProperty(profileKey(playerId, "team"), teamName)
        profiles.setProperty(profileKey(playerId, "captain"), captainName)
        profiles.setProperty(profileKey(playerId, "coupons"), couponCount.toString)
        profiles.setProperty(profileKey(playerId, "rewardDay"), claimedRewardDay.toString)
        profiles.setProperty(profileKey(playerId, "lastRewardDate"), lastRewardDate)
        profiles.setProperty(profileKey(playerId, "tokens"), trainingTokens.toString)
        profiles.setProperty(profileKey(playerId, "rcbCard"), hasRcbTeamCard.toString)
        saveProfiles()
      }
    }

    private def createAccount(): Unit = {
      val name = nameField.getText.trim
      val pass = passwordField.getPassword
      if (name.length < 3 || pass.length < 4) {
        JOptionPane.showMessageDialog(this, "Enter a player name (at least 3 letters) and password (at least 4 characters).")
        java.util.Arrays.fill(pass, 0.toChar)
        return
      }
      val digest = hashPassword(pass)
      var id = "BCL-" + (100000 + Random.nextInt(899999)).toString
      while (profiles.getProperty(profileKey(id, "passwordHash"), "").nonEmpty) {
        id = "BCL-" + (100000 + Random.nextInt(899999)).toString
      }
      profiles.setProperty(profileKey(id, "name"), name)
      profiles.setProperty(profileKey(id, "passwordHash"), digest)
      profiles.setProperty(profileKey(id, "bucks"), "500")
      profiles.setProperty(profileKey(id, "diamonds"), "50")
      profiles.setProperty(profileKey(id, "trophies"), "0")
      profiles.setProperty(profileKey(id, "wins"), "0")
      profiles.setProperty(profileKey(id, "team"), "Bixuu Blasters")
      profiles.setProperty(profileKey(id, "captain"), "Aarav Mehta")
      profiles.setProperty(profileKey(id, "coupons"), "0")
      profiles.setProperty(profileKey(id, "rewardDay"), "0")
      profiles.setProperty(profileKey(id, "lastRewardDate"), "")
      profiles.setProperty(profileKey(id, "tokens"), "0")
      profiles.setProperty(profileKey(id, "rcbCard"), "false")
      loadProfile(id)
      saveProfile()
      JOptionPane.showMessageDialog(this, "Account created! Your Cricket ID is:\n" + id + "\nKeep this ID for future login.")
      showPage("lobby")
    }

    private def loginAccount(): Unit = {
      val id = idField.getText.trim.toUpperCase
      val pass = passwordField.getPassword
      val entered = hashPassword(pass)
      val saved = profiles.getProperty(profileKey(id, "passwordHash"), "")
      if (saved.nonEmpty && saved == entered) {
        loadProfile(id)
        showPage("lobby")
      } else JOptionPane.showMessageDialog(this, "Cricket ID or password is incorrect. Create an account first.")
    }

    private def showPage(name: String): Unit = {
      rootLayout.show(root, name)
      root.revalidate()
      root.repaint()
    }

    private def updateLobbyStats(): Unit = {
      lobbyStats.setText("PLAYER: " + playerName + "   ID: " + playerId + "   BIXUU BUCKS: " + bucks + "   DIAMONDS: " + diamonds + "   TROPHIES: " + trophies + "   TOKENS: " + trainingTokens + (if (hasRcbTeamCard) "   RCB CARD: OWNED" else ""))
    }

    def currentTeam: String = teamName
    def currentCaptain: String = captainName
    def activePlayerName: String = playerName

    private def buildLoginPage(): JPanel = {
      val p = new JPanel(new BorderLayout(18, 18))
      p.setBackground(BG)
      p.setBorder(BorderFactory.createEmptyBorder(35, 60, 35, 60))
      val title = heading("BIXUU CRICKET LEAGUE", 36)
      title.setForeground(CYAN)
      val subtitle = label("BUILD YOUR XI  ?  WIN THE TOSS  ?  AIM YOUR SHOTS  ?  TAKE WICKETS")
      val top = new JPanel(new BorderLayout())
      top.setOpaque(false)
      top.add(title, BorderLayout.NORTH)
      top.add(subtitle, BorderLayout.SOUTH)
      p.add(top, BorderLayout.NORTH)

      val card = new JPanel()
      card.setBackground(PANEL)
      card.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(new Color(54, 101, 142), 2), BorderFactory.createEmptyBorder(28, 34, 28, 34)))
      card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS))
      card.add(heading("PLAYER LOGIN / CREATE ACCOUNT", 24))
      card.add(Box.createVerticalStrut(16))
      card.add(label("PLAYER NAME ? new account"))
      card.add(nameField)
      card.add(Box.createVerticalStrut(10))
      card.add(label("CRICKET ID ? existing account"))
      card.add(idField)
      card.add(Box.createVerticalStrut(10))
      card.add(label("PASSWORD"))
      card.add(passwordField)
      card.add(Box.createVerticalStrut(18))
      val actions = new JPanel()
      actions.setOpaque(false)
      val create = button("CREATE ACCOUNT", GREEN)
      val login = button("LOGIN", BLUE)
      actions.add(create)
      actions.add(login)
      card.add(actions)
      card.add(Box.createVerticalStrut(14))
      card.add(label("Your profile is saved locally on this computer."))
      create.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = createAccount() })
      login.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = loginAccount() })
      val holder = new JPanel(new BorderLayout())
      holder.setOpaque(false)
      holder.add(card, BorderLayout.CENTER)
      p.add(holder, BorderLayout.CENTER)
      p
    }

    private def buildLobbyPage(): JPanel = {
      val p = new JPanel(new BorderLayout(14, 14))
      p.setBackground(BG)
      p.setBorder(BorderFactory.createEmptyBorder(20, 22, 20, 22))
      val top = new JPanel(new BorderLayout())
      top.setBackground(PANEL)
      top.setBorder(BorderFactory.createEmptyBorder(13, 16, 13, 16))
      val title = heading("? BIXUU CRICKET LEAGUE", 27)
      title.setForeground(CYAN)
      top.add(title, BorderLayout.NORTH)
      lobbyStats.setForeground(GOLD)
      lobbyStats.setFont(new Font("SansSerif", Font.BOLD, 12))
      top.add(lobbyStats, BorderLayout.SOUTH)
      p.add(top, BorderLayout.NORTH)

      val center = new JPanel(new BorderLayout(12, 12))
      center.setOpaque(false)
      center.add(new StadiumPreview(), BorderLayout.CENTER)
      val menu = new JPanel()
      menu.setBackground(PANEL)
      menu.setBorder(BorderFactory.createEmptyBorder(14, 14, 14, 14))
      menu.setLayout(new BoxLayout(menu, BoxLayout.Y_AXIS))
      menu.add(heading("CRICKET WORLD", 21))
      menu.add(Box.createVerticalStrut(12))
      val play = button("PLAY MATCH", GREEN)
      val team = button("CREATE / EDIT TEAM", BLUE)
      val rewards = button("7-DAY REWARDS", new Color(145, 103, 37))
      val room = button("LAN FRIEND ROOM", new Color(89, 83, 150))
      val logout = button("LOG OUT", new Color(105, 62, 73))
      val rows = Vector(play, team, rewards, room, logout)
      rows.foreach { b => b.setAlignmentX(0.0f); b.setMaximumSize(new Dimension(250, 44)); menu.add(b); menu.add(Box.createVerticalStrut(9)) }
      play.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { captainBox.setSelectedItem(captainName); showPage("matchcenter") } })
      team.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = showPage("team") })
      rewards.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { renderRewards(); showPage("rewards") } })
      room.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = showLanDialog() })
      logout.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { saveProfile(); passwordField.setText(""); showPage("login") } })
      center.add(menu, BorderLayout.EAST)
      p.add(center, BorderLayout.CENTER)
      val footer = label("TOSS FIRST ? SELECT CAPTAIN ? SET YOUR FIELD ? BAT OR BOWL ? WIN THE MATCH")
      p.add(footer, BorderLayout.SOUTH)
      p
    }

    private def showLanDialog(): Unit = {
      val options: Array[java.lang.Object] = Array[java.lang.Object]("HOST ROOM", "JOIN ROOM", "CANCEL")
      val choice = JOptionPane.showOptionDialog(this, "LAN friend match prototype. Use a trusted home Wi-Fi network.", "BIXUU FRIEND ROOM", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options(0))
      if (choice == 0) JOptionPane.showMessageDialog(this, "LAN friend-room menu is available in this demo build. Match results are local; full multiplayer ball synchronization is not implemented.")
      else if (choice == 1) JOptionPane.showMessageDialog(this, "Join-room matchmaking is a prototype. Use the same trusted Wi-Fi; full live cricket simulation sync is not implemented.")
    }

    private def buildTeamPage(): JPanel = {
      val p = new JPanel()
      p.setBackground(BG)
      p.setBorder(BorderFactory.createEmptyBorder(25, 35, 25, 35))
      p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS))
      p.add(heading("TEAM CREATOR ? BUILD YOUR XI", 27))
      p.add(Box.createVerticalStrut(10))
      p.add(label("Choose your club name and captain. All demo players are fictional."))
      p.add(Box.createVerticalStrut(18))
      p.add(label("TEAM NAME"))
      teamNameField.setMaximumSize(new Dimension(360, 34))
      p.add(teamNameField)
      p.add(Box.createVerticalStrut(13))
      p.add(label("CAPTAIN"))
      teamCaptainBox.setMaximumSize(new Dimension(360, 34))
      p.add(teamCaptainBox)
      p.add(Box.createVerticalStrut(18))
      val save = button("SAVE TEAM", GREEN)
      val back = button("BACK TO LOBBY", new Color(75, 86, 105))
      val row = new JPanel()
      row.setOpaque(false)
      row.add(save)
      row.add(back)
      p.add(row)
      save.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = {
        val value = teamNameField.getText.trim
        if (value.length < 3) JOptionPane.showMessageDialog(CricketApp.this, "Team name must contain at least 3 characters.")
        else {
          teamName = value
          captainName = teamCaptainBox.getSelectedItem.toString
          saveProfile()
          updateLobbyStats()
          JOptionPane.showMessageDialog(CricketApp.this, "Team saved: " + teamName + "\nCaptain: " + captainName)
        }
      } })
      back.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = showPage("lobby") })
      val squad = new JTextArea(10, 32)
      squad.setEditable(false)
      squad.setBackground(PANEL)
      squad.setForeground(WHITE)
      squad.setFont(new Font("Monospaced", Font.PLAIN, 13))
      squad.setText("YOUR XI\n\n" + captainName + "  (CAPTAIN)\nKabir Rao\nReyansh Shah\nVivaan Patil\nIshaan Das\nArjun Nair\nDev Malhotra\nNeil Kulkarni\nRohan Iyer\nAditya Sen\nYuvaan Joshi")
      p.add(Box.createVerticalStrut(18))
      p.add(new JScrollPane(squad))
      p.add(Box.createVerticalStrut(12))
      p.add(label("Tip: Your selected captain leads the toss and match screen."))
      p.add(Box.createVerticalStrut(14))
      p
    }

    private def buildMatchCenter(): JPanel = {
      val p = new JPanel()
      p.setBackground(BG)
      p.setBorder(BorderFactory.createEmptyBorder(25, 40, 25, 40))
      p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS))
      p.add(heading("MATCH CENTER", 28))
      p.add(Box.createVerticalStrut(8))
      p.add(label("Choose match format, opponent, overs, captain and your field setup."))
      p.add(Box.createVerticalStrut(16))
      p.add(label("MATCH FORMAT")); p.add(modeBox)
      p.add(Box.createVerticalStrut(10))
      p.add(label("OPPONENT TEAM")); p.add(opponentBox)
      p.add(Box.createVerticalStrut(10))
      p.add(label("OVERS")); p.add(oversBox)
      p.add(Box.createVerticalStrut(10))
      p.add(label("YOUR CAPTAIN")); p.add(captainBox)
      p.add(Box.createVerticalStrut(10))
      p.add(label("FIELD PRESET")); p.add(fieldBox)
      val start = button("GO TO TOSS", GREEN)
      val back = button("BACK TO LOBBY", new Color(75, 86, 105))
      val row = new JPanel(); row.setOpaque(false); row.add(start); row.add(back)
      p.add(Box.createVerticalStrut(19)); p.add(row)
      start.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = {
        selectedMode = modeBox.getSelectedItem.toString
        selectedOpponent = opponentBox.getSelectedItem.toString
        val oversText = oversBox.getSelectedItem.toString
        selectedOvers = if (oversText.startsWith("5")) 5 else if (oversText.startsWith("10")) 10 else if (oversText.startsWith("20")) 20 else 2
        selectedCaptain = captainBox.getSelectedItem.toString
        selectedField = fieldBox.getSelectedItem.toString
        tossDone = false
        tossWon = false
        battingFirst = true
        tossResult.setText("Call HEADS or TAILS to begin the toss.")
        tossChoice.setText("Toss winner may choose BAT or BOWL.")
        continueToss.setEnabled(false)
        showPage("toss")
      } })
      back.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = showPage("lobby") })
      p
    }

    private def buildTossPage(): JPanel = {
      val p = new JPanel()
      p.setBackground(BG)
      p.setBorder(BorderFactory.createEmptyBorder(35, 55, 35, 55))
      p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS))
      p.add(heading("MATCH TOSS", 30))
      p.add(Box.createVerticalStrut(14))
      p.add(label("YOUR TEAM: " + teamName + "    CAPTAIN: " + selectedCaptain))
      p.add(label("OPPONENT: " + selectedOpponent + "    FORMAT: " + selectedMode + "    OVERS: " + selectedOvers))
      p.add(Box.createVerticalStrut(18))
      val heads = button("CALL HEADS", BLUE)
      val tails = button("CALL TAILS", new Color(111, 75, 148))
      val coinRow = new JPanel(); coinRow.setOpaque(false); coinRow.add(heads); coinRow.add(tails)
      p.add(heading("? HEADS OR TAILS?", 23))
      p.add(Box.createVerticalStrut(12)); p.add(coinRow)
      tossResult.setForeground(CYAN); tossResult.setFont(new Font("SansSerif", Font.BOLD, 16))
      tossChoice.setForeground(WHITE); tossChoice.setFont(new Font("SansSerif", Font.PLAIN, 14))
      p.add(Box.createVerticalStrut(15)); p.add(tossResult); p.add(Box.createVerticalStrut(7)); p.add(tossChoice)
      val bat = button("BAT FIRST", GREEN)
      val bowl = button("BOWL FIRST", BLUE)
      val decisionRow = new JPanel(); decisionRow.setOpaque(false); decisionRow.add(bat); decisionRow.add(bowl)
      bat.setEnabled(false); bowl.setEnabled(false)
      p.add(Box.createVerticalStrut(12)); p.add(decisionRow)
      p.add(Box.createVerticalStrut(16)); p.add(continueToss)
      val back = button("BACK TO MATCH CENTER", new Color(75, 86, 105))
      p.add(Box.createVerticalStrut(10)); p.add(back)
      def callToss(called: String): Unit = {
        if (tossDone) return
        tossDone = true
        tossWon = Random.nextBoolean()
        if (tossWon) {
          tossResult.setText("YOU WON THE TOSS! Your call: " + called)
          tossChoice.setText("Choose whether " + teamName + " will BAT or BOWL first.")
          bat.setEnabled(true)
          bowl.setEnabled(true)
          continueToss.setEnabled(false)
        } else {
          battingFirst = Random.nextBoolean()
          tossResult.setText(selectedOpponent + " won the toss. Their call: " + (if (battingFirst) "You are batting first." else "You are fielding first."))
          tossChoice.setText("Opponent decision is locked. Continue to the match.")
          bat.setEnabled(false)
          bowl.setEnabled(false)
          continueToss.setEnabled(true)
        }
      }
      heads.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = callToss("HEADS") })
      tails.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = callToss("TAILS") })
      bat.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { battingFirst = true; tossChoice.setText("You elected to BAT first."); continueToss.setEnabled(true) } })
      bowl.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { battingFirst = false; tossChoice.setText("You elected to BOWL first."); continueToss.setEnabled(true) } })
      continueToss.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = {
        if (tossDone) {
          matchPanel.startMatch(selectedMode, selectedOpponent, selectedOvers, battingFirst, selectedField, selectedCaptain)
          showPage("match")
          matchPanel.requestFocusInWindow()
        }
      } })
      back.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = showPage("matchcenter") })
      p
    }

    private def buildResultPage(): JPanel = {
      val p = new JPanel()
      p.setBackground(BG)
      p.setBorder(BorderFactory.createEmptyBorder(60, 60, 60, 60))
      p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS))
      resultTitle.setForeground(GOLD)
      resultDetails.setForeground(WHITE)
      p.add(resultTitle)
      p.add(Box.createVerticalStrut(15))
      p.add(resultDetails)
      val lobby = button("BACK TO LOBBY", BLUE)
      val again = button("PLAY ANOTHER MATCH", GREEN)
      val row = new JPanel(); row.setOpaque(false); row.add(lobby); row.add(again)
      p.add(Box.createVerticalStrut(24)); p.add(row)
      lobby.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = showPage("lobby") })
      again.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = showPage("matchcenter") })
      p
    }

    private def claimReward(day: Int): Unit = {
      if (playerId.isEmpty) {
        JOptionPane.showMessageDialog(this, "Please log in before claiming rewards.")
        return
      }
      if (day != claimedRewardDay + 1 || day < 1 || day > 7) {
        JOptionPane.showMessageDialog(this, "Claim the next unlocked reward day in order.")
        return
      }
      val today = new SimpleDateFormat("yyyy-MM-dd").format(new Date())
      if (lastRewardDate == today) {
        JOptionPane.showMessageDialog(this, "You have already claimed today's reward. Come back tomorrow.")
        return
      }

      val rewardMessage = day match {
        case 1 => bucks += 200; "Day 1 reward: 200 Bixuu Bucks!"
        case 2 => bucks += 400; "Day 2 reward: 400 Bixuu Bucks!"
        case 3 => bucks += 800; "Day 3 reward: 800 Bixuu Bucks!"
        case 4 => bucks += 10000; "Day 4 reward: 10,000 Bixuu Bucks!"
        case 5 => bucks += 7000; trophies += 1; "Day 5 reward: 7,000 Bixuu Bucks and 1 Trophy!"
        case 6 => trainingTokens += 20; "Day 6 reward: 20 Training Tokens!"
        case 7 => hasRcbTeamCard = true; "Day 7 reward: RCB-inspired Team Card unlocked!"
        case _ => "No reward available."
      }
      claimedRewardDay = day
      lastRewardDate = today
      saveProfile()
      updateLobbyStats()
      renderRewards()
      JOptionPane.showMessageDialog(this, rewardMessage)
    }

    private def buildRewardsPage(): JPanel = {
      val p = new JPanel()
      p.setBackground(BG)
      p.setBorder(BorderFactory.createEmptyBorder(25, 35, 25, 35))
      p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS))
      rewardsPage = p
      renderRewards()
      p
    }

    private def renderRewards(): Unit = {
      if (rewardsPage == null) return
      rewardsPage.removeAll()
      rewardsPage.add(heading("7-DAY CRICKET REWARDS", 27))
      rewardsPage.add(Box.createVerticalStrut(12))
      rewardsPage.add(label("Claim one reward per calendar day. Your reward progress is saved locally."))
      rewardsPage.add(Box.createVerticalStrut(12))
      val rewardRows = Vector("DAY 1 ? 200 BIXUU BUCKS", "DAY 2 ? 400 BIXUU BUCKS", "DAY 3 ? 800 BIXUU BUCKS", "DAY 4 ? 10,000 BIXUU BUCKS", "DAY 5 ? 7,000 BUCKS + TROPHY", "DAY 6 ? 20 TRAINING TOKENS", "DAY 7 ? RCB-INSPIRED TEAM CARD")
      rewardRows.zipWithIndex.foreach { pair =>
        val day = pair._2 + 1
        val row = new JPanel(new BorderLayout())
        row.setBackground(PANEL)
        row.setBorder(BorderFactory.createEmptyBorder(7, 10, 7, 10))
        val text = new JLabel(pair._1)
        text.setForeground(WHITE)
        val canClaim = day == claimedRewardDay + 1 && claimedRewardDay < 7
        val claimed = day <= claimedRewardDay
        val claim = button(if (claimed) "CLAIMED" else if (canClaim) "CLAIM" else "LOCKED", if (canClaim) GREEN else new Color(75, 83, 98))
        claim.setEnabled(canClaim)
        claim.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = claimReward(day) })
        row.add(text, BorderLayout.CENTER)
        row.add(claim, BorderLayout.EAST)
        rewardsPage.add(row)
        rewardsPage.add(Box.createVerticalStrut(7))
      }
      val back = button("BACK TO LOBBY", new Color(75, 86, 105))
      back.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = showPage("lobby") })
      rewardsPage.add(Box.createVerticalStrut(15))
      rewardsPage.add(back)
      rewardsPage.revalidate()
      rewardsPage.repaint()
    }

    def addMatchReward(won: Boolean, matchScore: String): Unit = {
      val earned = if (won) 180 else 70
      bucks += earned
      if (won) { wins += 1; trophies += 1; couponCount += 1 }
      saveProfile()
      updateLobbyStats()
      lastResult = matchScore + "  ?  Earned " + earned + " Bixuu Bucks" + (if (won) "  ?  WIN TROPHY + CARD ROOM COUPON" else "")
      resultDetails.setText(lastResult)
      resultTitle.setText(if (won) "? YOU WON THE MATCH!" else "MATCH COMPLETE")
    }

    def showMatchResult(won: Boolean, matchScore: String): Unit = {
      addMatchReward(won, matchScore)
      showPage("result")
    }
  }

  class CricketMatchPanel(app: CricketApp) extends JPanel(new BorderLayout(8, 8)) {
    private var matchMode = "Quick T20"
    private var opponent = "New Zealand"
    private var myTeam = "Bixuu Blasters"
    private var myCaptain = "Aarav Mehta"
    private var fieldPreset = "BALANCED"
    private var oversLimit = 2
    private var maxBalls = 12
    private var inningsNo = 1
    private var battingFirst = true
    private var userBatting = true
    private var userRuns = 0
    private var userWickets = 0
    private var opponentRuns = 0
    private var opponentWickets = 0
    private var ballsThisInnings = 0
    private var target = 0
    private var ballActive = false
    private var ballProgress = 0.0
    private var ballFlightX = 0.0
    private var ballFlightY = 0.0
    private var shotAim = 0
    private var wicketTarget = "MIDDLE"
    private var bowlLine = "MIDDLE"
    private var bowlLength = "GOOD"
    private var bowlType = "FAST"
    private var currentShot = "DRIVE"
    private var pauseState = false
    private var matchFinished = false
    private var lastCommentary = "Press START DELIVERY to begin."
    private var commentaryBeforePause = "Press START DELIVERY to begin."
    private var cameraAngle = 0.0
    private var zoomFactor = 1.0
    private var dragPointX = 0
    private var dragPointY = 0
    private var fieldPresetBox: JComboBox[String] = null

    private val scoreLabel = new JLabel("0/0   OVERS 0.0")
    private val targetLabel = new JLabel("INNINGS 1")
    private val commentary = new JLabel("Press START DELIVERY to begin.")
    private val startDeliveryButton = button("START DELIVERY", GREEN)
    private val shotButtons = Vector(button("DEFEND", BLUE), button("DRIVE", BLUE), button("LOFT", BLUE), button("SWEEP", BLUE), button("CUT", BLUE))
    private val bowlButton = button("BOWL DELIVERY", BLUE)
    private val pauseButton = button("PAUSE", new Color(94, 77, 127))
    private val aimLeft = button("AIM LEG SIDE", new Color(63, 100, 140))
    private val aimCenter = button("AIM STRAIGHT", new Color(63, 100, 140))
    private val aimRight = button("AIM OFF SIDE", new Color(63, 100, 140))
    private val lineButtons = Vector(button("OFF STUMP", new Color(54, 91, 137)), button("MIDDLE", new Color(54, 91, 137)), button("LEG STUMP", new Color(54, 91, 137)))
    private val lengthButtons = Vector(button("YORKER", new Color(106, 79, 133)), button("FULL", new Color(106, 79, 133)), button("GOOD", new Color(106, 79, 133)), button("SHORT", new Color(106, 79, 133)))
    private val typeButtons = Vector(button("FAST", new Color(133, 79, 58)), button("SWING", new Color(133, 79, 58)), button("OFF SPIN", new Color(133, 79, 58)), button("LEG SPIN", new Color(133, 79, 58)))
    private val stadium = new StadiumCanvas()
    private val timer = new Timer(16, new ActionListener { override def actionPerformed(e: ActionEvent): Unit = tick() })

    setBackground(BG)
    setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8))
    scoreLabel.setForeground(GOLD); scoreLabel.setFont(new Font("Monospaced", Font.BOLD, 19))
    targetLabel.setForeground(CYAN); targetLabel.setFont(new Font("SansSerif", Font.BOLD, 13))
    commentary.setForeground(WHITE); commentary.setFont(new Font("SansSerif", Font.BOLD, 13))

    private val header = new JPanel(new BorderLayout(6, 6))
    header.setBackground(PANEL)
    header.setBorder(BorderFactory.createEmptyBorder(9, 13, 9, 13))
    header.add(scoreLabel, BorderLayout.CENTER)
    header.add(targetLabel, BorderLayout.EAST)
    header.add(commentary, BorderLayout.SOUTH)
    add(header, BorderLayout.NORTH)
    add(stadium, BorderLayout.CENTER)

    private val controlRoot = new JPanel()
    controlRoot.setBackground(PANEL)
    controlRoot.setLayout(new BoxLayout(controlRoot, BoxLayout.Y_AXIS))
    private val mainControls = new JPanel(); mainControls.setOpaque(false)
    mainControls.add(startDeliveryButton); mainControls.add(bowlButton); mainControls.add(pauseButton)
    private val battingControls = new JPanel(); battingControls.setOpaque(false)
    shotButtons.foreach(b => battingControls.add(b))
    battingControls.add(aimLeft); battingControls.add(aimCenter); battingControls.add(aimRight)
    private val bowlingControls = new JPanel(); bowlingControls.setOpaque(false)
    lineButtons.foreach(b => bowlingControls.add(b))
    lengthButtons.foreach(b => bowlingControls.add(b))
    typeButtons.foreach(b => bowlingControls.add(b))
    fieldPresetBox = new JComboBox[String](Vector("BALANCED", "ATTACKING", "BOUNDARY DEFENCE", "SPIN TRAP").toArray)
    bowlingControls.add(new JLabel("FIELD:")); bowlingControls.add(fieldPresetBox)
    private val bottomControls = new JPanel(); bottomControls.setOpaque(false)
    val backButton = button("END / BACK TO LOBBY", new Color(119, 58, 70))
    bottomControls.add(backButton)
    controlRoot.add(mainControls); controlRoot.add(battingControls); controlRoot.add(bowlingControls); controlRoot.add(bottomControls)
    add(controlRoot, BorderLayout.SOUTH)

    startDeliveryButton.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = startDelivery() })
    bowlButton.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = startDelivery() })
    shotButtons.zipWithIndex.foreach { pair =>
      pair._1.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = playShot(Vector("DEFEND", "DRIVE", "LOFT", "SWEEP", "CUT")(pair._2)) })
    }
    aimLeft.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = setAim(-1) })
    aimCenter.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = setAim(0) })
    aimRight.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = setAim(1) })
    lineButtons.zipWithIndex.foreach { pair =>
      pair._1.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { bowlLine = Vector("OFF", "MIDDLE", "LEG")(pair._2); updateCommentary("Bowling line: " + bowlLine + " STUMP. Aim is set.") } })
    }
    lengthButtons.zipWithIndex.foreach { pair =>
      pair._1.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { bowlLength = Vector("YORKER", "FULL", "GOOD", "SHORT")(pair._2); updateCommentary("Length selected: " + bowlLength + ".") } })
    }
    typeButtons.zipWithIndex.foreach { pair =>
      pair._1.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { bowlType = Vector("FAST", "SWING", "OFF SPIN", "LEG SPIN")(pair._2); updateCommentary("Delivery type: " + bowlType + ".") } })
    }
    fieldPresetBox.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { fieldPreset = fieldPresetBox.getSelectedItem.toString; stadium.repaint() } })
    pauseButton.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = togglePause() })
    backButton.addActionListener(new ActionListener { override def actionPerformed(e: ActionEvent): Unit = { timer.stop(); app.showMatchResult(false, currentScoreSummary() + " ? Match ended early") } })

    addKeyListener(new KeyAdapter {
      override def keyPressed(e: KeyEvent): Unit = handleKey(e.getKeyCode)
    })
    stadium.addKeyListener(new KeyAdapter { override def keyPressed(e: KeyEvent): Unit = handleKey(e.getKeyCode) })
    setFocusable(true)

    def startMatch(newMode: String, newOpponent: String, overs: Int, batFirst: Boolean, field: String, captain: String): Unit = {
      matchMode = newMode
      opponent = newOpponent
      myTeam = app.currentTeam
      myCaptain = captain
      oversLimit = overs
      maxBalls = oversLimit * 6
      battingFirst = batFirst
      userBatting = batFirst
      inningsNo = 1
      userRuns = 0; userWickets = 0; opponentRuns = 0; opponentWickets = 0
      ballsThisInnings = 0; target = 0
      ballActive = false; ballProgress = 0.0; pauseState = false; matchFinished = false
      fieldPreset = field
      fieldPresetBox.setSelectedItem(field)
      bowlLine = "MIDDLE"; bowlLength = "GOOD"; bowlType = "FAST"; shotAim = 0
      updateControls()
      updateScore()
      updateCommentary("Toss complete. " + (if (userBatting) "You are batting first." else "You are bowling first.") + " Press START DELIVERY.")
      timer.start()
      requestFocusInWindow()
      stadium.requestFocusInWindow()
      stadium.repaint()
    }

    private def updateControls(): Unit = {
      startDeliveryButton.setVisible(userBatting)
      bowlButton.setVisible(!userBatting)
      battingControls.setVisible(userBatting)
      bowlingControls.setVisible(!userBatting)
      startDeliveryButton.setEnabled(!ballActive && !pauseState && !matchFinished)
      bowlButton.setEnabled(!ballActive && !pauseState && !matchFinished)
      shotButtons.foreach(_.setEnabled(ballActive && userBatting && !pauseState))
      lineButtons.foreach(_.setEnabled(!ballActive && !userBatting && !pauseState))
      lengthButtons.foreach(_.setEnabled(!ballActive && !userBatting && !pauseState))
      typeButtons.foreach(_.setEnabled(!ballActive && !userBatting && !pauseState))
    }

    private def updateCommentary(text: String): Unit = {
      lastCommentary = text
      commentary.setText(text)
      stadium.repaint()
    }

    private def setAim(value: Int): Unit = {
      shotAim = value
      wicketTarget = if (value < 0) "LEG SIDE" else if (value > 0) "OFF SIDE" else "STRAIGHT"
      updateCommentary("Shot aim: " + wicketTarget + ". Choose your shot when the ball reaches the crease.")
    }

    private def startDelivery(): Unit = {
      if (matchFinished || pauseState || ballActive) return
      ballActive = true
      ballProgress = 0.0
      updateControls()
      if (userBatting) updateCommentary("BOWLER RUNS IN ? time your shot! Press 1?5 or click a shot button.")
      else updateCommentary("YOU BOWL " + bowlType + " ? " + bowlLine + " line, " + bowlLength + " length. Target the stumps!")
      stadium.repaint()
    }

    private def playShot(shot: String): Unit = {
      if (!userBatting || matchFinished || pauseState || !ballActive) return
      val timingError = Math.abs(ballProgress - 0.70)
      val quality = Math.max(0.0, 1.0 - timingError / 0.34)
      var runs = 0
      var isWicket = false
      val roll = Random.nextInt(100)
      if (quality < 0.16) {
        isWicket = roll < 30
        runs = 0
      } else {
        shot match {
          case "DEFEND" => runs = if (quality > 0.72) 1 else 0
          case "DRIVE" => runs = if (quality > 0.91) 4 else if (quality > 0.70) 3 else if (quality > 0.48) 2 else 1
          case "LOFT" =>
            if (quality > 0.92) runs = 6
            else if (quality > 0.72) runs = 4
            else if (quality > 0.50) runs = 2
            else { runs = 0; isWicket = roll < 23 }
          case "SWEEP" => runs = if (quality > 0.86) 4 else if (quality > 0.60) 2 else if (quality > 0.30) 1 else 0
          case "CUT" => runs = if (quality > 0.88) 4 else if (quality > 0.57) 2 else if (quality > 0.30) 1 else 0
          case _ => runs = 0
        }
        if (shotAim != 0 && runs == 4 && Random.nextInt(100) < 18) runs = 2
      }
      ballActive = false
      ballsThisInnings += 1
      if (isWicket) userWickets += 1 else userRuns += runs
      val message = if (isWicket) "WICKET! The fielder takes the catch. Select a safer shot next ball."
        else if (runs == 6) "SIX! Huge lofted shot into the stands!"
        else if (runs == 4) "FOUR! The ball races to the boundary!"
        else if (runs == 0) "DOT BALL ? good fielding."
        else runs + " run(s) ? " + shot + " toward " + wicketTarget + "."
      updateCommentary(message)
      afterDelivery()
    }

    private def missedShot(): Unit = {
      if (!ballActive) return
      ballActive = false
      ballsThisInnings += 1
      val wicket = Random.nextInt(100) < 12
      if (wicket) userWickets += 1
      updateCommentary(if (wicket) "BOWLED! You missed the ball and lost your wicket." else "DOT BALL ? the ball passed the bat.")
      afterDelivery()
    }

    private def resolveCpuBatting(): Unit = {
      ballActive = false
      ballsThisInnings += 1
      var wicketChance = 8
      if (bowlLine == "MIDDLE") wicketChance += 5
      if (bowlLine == "OFF") wicketChance += 3
      if (bowlLength == "YORKER") wicketChance += 13
      if (bowlLength == "GOOD") wicketChance += 7
      if (bowlLength == "SHORT") wicketChance -= 2
      if (bowlType == "OFF SPIN" || bowlType == "LEG SPIN") wicketChance += 8
      if (bowlType == "SWING") wicketChance += 5
      if (fieldPreset == "ATTACKING") wicketChance += 7
      if (fieldPreset == "SPIN TRAP" && (bowlType == "OFF SPIN" || bowlType == "LEG SPIN")) wicketChance += 8
      val roll = Random.nextInt(100)
      if (roll < wicketChance && opponentWickets < 10) {
        opponentWickets += 1
        updateCommentary("WICKET! " + bowlType + " " + bowlLength + " ? the stumps are hit!")
      } else {
        val runRoll = Random.nextInt(100)
        val runs = if (runRoll < 25) 0 else if (runRoll < 55) 1 else if (runRoll < 70) 2 else if (runRoll < 90) 4 else 6
        opponentRuns += runs
        updateCommentary(if (runs == 6) "CPU SIX!" else if (runs == 4) "CPU FOUR." else "Opponent scores " + runs + " run(s).")
      }
      afterDelivery()
    }

    private def afterDelivery(): Unit = {
      updateScore()
      if (target > 0 && userBatting && userRuns >= target) { completeMatch(userRuns > opponentRuns); return }
      if (target > 0 && !userBatting && opponentRuns >= target) { completeMatch(false); return }
      val inningsOver = ballsThisInnings >= maxBalls || (if (userBatting) userWickets >= 10 else opponentWickets >= 10)
      if (inningsOver) {
        if (inningsNo == 1) {
          if (userBatting) {
            target = userRuns + 1
            userBatting = false
          } else {
            target = opponentRuns + 1
            userBatting = true
          }
          inningsNo = 2
          ballsThisInnings = 0
          ballActive = false
          updateCommentary("INNINGS BREAK ? target is " + target + ". " + (if (userBatting) "You are batting now." else "You are bowling now."))
          updateControls()
          updateScore()
        } else {
          val won = userRuns >= opponentRuns && (userRuns > opponentRuns || target <= userRuns)
          completeMatch(won)
        }
      } else {
        updateControls()
        updateScore()
      }
      stadium.repaint()
    }

    private def completeMatch(won: Boolean): Unit = {
      if (matchFinished) return
      matchFinished = true
      ballActive = false
      timer.stop()
      updateControls()
      val summary = myTeam + " " + userRuns + "/" + userWickets + "  vs  " + opponent + " " + opponentRuns + "/" + opponentWickets
      app.showMatchResult(won, summary)
    }

    private def currentScoreSummary(): String = myTeam + " " + userRuns + "/" + userWickets + " vs " + opponent + " " + opponentRuns + "/" + opponentWickets

    private def updateScore(): Unit = {
      val oversText = (ballsThisInnings / 6).toString + "." + (ballsThisInnings % 6).toString
      scoreLabel.setText(myTeam + " " + userRuns + "/" + userWickets + "   vs   " + opponent + " " + opponentRuns + "/" + opponentWickets + "   OV " + oversText)
      targetLabel.setText("INNINGS " + inningsNo + (if (target > 0) "  TARGET " + target else "  " + oversLimit + " OVERS"))
    }

    private def togglePause(): Unit = {
      if (matchFinished) return
      if (!pauseState) commentaryBeforePause = lastCommentary
      pauseState = !pauseState
      pauseButton.setText(if (pauseState) "RESUME" else "PAUSE")
      commentary.setText(if (pauseState) "MATCH PAUSED ? press RESUME or P." else commentaryBeforePause)
      updateControls()
    }

    private def handleKey(code: Int): Unit = {
      if (code == KeyEvent.VK_P || code == KeyEvent.VK_ESCAPE) togglePause()
      else if (code == KeyEvent.VK_SPACE) {
        if (ballActive && userBatting) playShot("DRIVE") else if (!ballActive) startDelivery()
      } else if (code == KeyEvent.VK_1) playShot("DEFEND")
      else if (code == KeyEvent.VK_2) playShot("DRIVE")
      else if (code == KeyEvent.VK_3) playShot("LOFT")
      else if (code == KeyEvent.VK_4) playShot("SWEEP")
      else if (code == KeyEvent.VK_5) playShot("CUT")
      else if (code == KeyEvent.VK_LEFT) setAim(-1)
      else if (code == KeyEvent.VK_RIGHT) setAim(1)
      else if (code == KeyEvent.VK_UP) setAim(0)
    }

    private def tick(): Unit = {
      if (!pauseState && !matchFinished && ballActive) {
        ballProgress += 0.018
        if (ballProgress >= 1.0) {
          if (userBatting) missedShot() else resolveCpuBatting()
        } else stadium.repaint()
      }
    }

    def stopMatch(): Unit = timer.stop()

    private def updateControlsAfterRestart(): Unit = updateControls()

    private class StadiumCanvas extends JPanel {
      setBackground(new Color(9, 24, 41))
      setPreferredSize(new Dimension(900, 540))
      setFocusable(true)
      addMouseListener(new MouseAdapter {
        override def mousePressed(e: MouseEvent): Unit = {
          requestFocusInWindow()
          val ratio = e.getX.toDouble / Math.max(1, getWidth).toDouble
          if (ratio < 0.40) setAim(-1) else if (ratio > 0.60) setAim(1) else setAim(0)
          if (!userBatting) {
            if (e.getY < getHeight / 2) bowlLine = "OFF"
            else if (ratio < 0.43) bowlLine = "LEG"
            else if (ratio > 0.57) bowlLine = "OFF"
            else bowlLine = "MIDDLE"
            updateCommentary("Aim selected: " + bowlLine + " line. Choose line, length and spin, then BOWL DELIVERY.")
          }
        }
      })
      addMouseMotionListener(new MouseMotionAdapter {
        override def mouseDragged(e: MouseEvent): Unit = {
          cameraAngle += (e.getX - dragPointX).toDouble * 0.0025
          dragPointX = e.getX
          dragPointY = e.getY
          repaint()
        }
        override def mouseMoved(e: MouseEvent): Unit = { dragPointX = e.getX; dragPointY = e.getY }
      })
      addMouseWheelListener(new MouseWheelListener {
        override def mouseWheelMoved(e: MouseWheelEvent): Unit = {
          zoomFactor = Math.max(0.82, Math.min(1.25, zoomFactor - e.getWheelRotation.toDouble * 0.04))
          repaint()
        }
      })

      override def paintComponent(g0: Graphics): Unit = {
        super.paintComponent(g0)
        val g = g0.create().asInstanceOf[Graphics2D]
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
        val w = getWidth
        val h = getHeight
        g.setPaint(new GradientPaint(0, 0, new Color(22, 58, 91), 0, h, new Color(5, 19, 31)))
        g.fillRect(0, 0, w, h)
        drawStadiumLights(g, w, h)
        drawCrowd(g, w, h)
        val old = g.getTransform
        g.rotate(cameraAngle, w.toDouble / 2.0, h.toDouble * 0.62)
        drawGrass(g, w, h)
        drawBoundary(g, w, h)
        drawPitch(g, w, h)
        drawCreases(g, w, h)
        drawWickets(g, w, h)
        drawFielders(g, w, h)
        if (userBatting) {
          drawHuman(g, w.toDouble * 0.50, h.toDouble * 0.80, 1.02, new Color(37, 129, 205), "BATSMAN", true)
          drawHuman(g, w.toDouble * 0.50, h.toDouble * 0.35, 0.62, new Color(232, 122, 67), "BOWLER", false)
        } else {
          drawHuman(g, w.toDouble * 0.50, h.toDouble * 0.80, 1.02, new Color(37, 129, 205), "BOWLER", false)
          drawHuman(g, w.toDouble * 0.50, h.toDouble * 0.35, 0.62, new Color(232, 122, 67), "BATSMAN", true)
        }
        drawBall(g, w, h)
        g.setTransform(old)
        drawAimGuide(g, w, h)
        drawGroundLabels(g, w, h)
        g.dispose()
      }

      private def drawStadiumLights(g: Graphics2D, w: Int, h: Int): Unit = {
        g.setStroke(new BasicStroke(5f))
        g.setColor(new Color(105, 144, 174))
        g.drawLine(55, 18, 55, h / 2 - 30)
        g.drawLine(w - 55, 18, w - 55, h / 2 - 30)
        g.setColor(new Color(250, 246, 218, 220))
        var i = 0
        while (i < 7) {
          g.fillOval(34 + i * 7, h / 2 - 43, 6, 6)
          g.fillOval(w - 82 + i * 7, h / 2 - 43, 6, 6)
          i += 1
        }
      }

      private def drawCrowd(g: Graphics2D, w: Int, h: Int): Unit = {
        g.setPaint(new GradientPaint(0, h / 5, new Color(48, 79, 112), 0, h / 2, new Color(13, 30, 49)))
        g.fillOval(-w / 7, h / 5, w * 9 / 7, h * 3 / 5)
        val random = new Random(42)
        var i = 0
        while (i < 520) {
          val px = random.nextInt(Math.max(1, w))
          val py = h / 3 + random.nextInt(Math.max(1, h / 6))
          val choice = random.nextInt(5)
          val c = if (choice == 0) new Color(245, 189, 76) else if (choice == 1) new Color(75, 190, 204) else if (choice == 2) new Color(219, 99, 117) else new Color(175, 190, 208)
          g.setColor(c)
          g.fillOval(px, py, 3, 3)
          i += 1
        }
      }

      private def drawGrass(g: Graphics2D, w: Int, h: Int): Unit = {
        g.setPaint(new GradientPaint(0, h / 2, new Color(76, 165, 108), 0, h, new Color(14, 91, 61)))
        g.fillOval(-w / 8, h / 2 - 5, w * 5 / 4, h)
      }

      private def drawBoundary(g: Graphics2D, w: Int, h: Int): Unit = {
        g.setColor(new Color(229, 243, 217, 190))
        g.setStroke(new BasicStroke(2.5f))
        g.drawOval(w / 9, h / 2 + 4, w * 7 / 9, h * 3 / 5)
        g.setColor(new Color(234, 196, 104, 180))
        var i = 0
        while (i < 32) {
          val x = w / 8 + i * (w * 3 / 4) / 31
          g.fillOval(x, h * 5 / 6, 3, 3)
          i += 1
        }
      }

      private def drawPitch(g: Graphics2D, w: Int, h: Int): Unit = {
        val poly = new Polygon()
        poly.addPoint(w / 2 - 43, h / 3)
        poly.addPoint(w / 2 + 43, h / 3)
        poly.addPoint(w / 2 + 105, h)
        poly.addPoint(w / 2 - 105, h)
        g.setPaint(new GradientPaint(w / 2, h / 3, new Color(196, 164, 119), w / 2, h, new Color(130, 96, 67)))
        g.fillPolygon(poly)
        g.setColor(new Color(246, 230, 195, 180))
        g.setStroke(new BasicStroke(2f))
        g.drawLine(w / 2 - 49, h / 3 + 10, w / 2 - 107, h - 4)
        g.drawLine(w / 2 + 49, h / 3 + 10, w / 2 + 107, h - 4)
      }

      private def drawCreases(g: Graphics2D, w: Int, h: Int): Unit = {
        g.setColor(new Color(255, 245, 220, 220))
        g.setStroke(new BasicStroke(2.5f))
        g.drawLine(w / 2 - 48, h * 36 / 100, w / 2 + 48, h * 36 / 100)
        g.drawLine(w / 2 - 90, h * 74 / 100, w / 2 + 90, h * 74 / 100)
        g.drawLine(w / 2 - 55, h * 32 / 100, w / 2 - 85, h * 32 / 100)
        g.drawLine(w / 2 + 55, h * 32 / 100, w / 2 + 85, h * 32 / 100)
      }

      private def drawWickets(g: Graphics2D, w: Int, h: Int): Unit = {
        g.setColor(new Color(244, 235, 213))
        g.setStroke(new BasicStroke(4.2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND))
        var i = -1
        while (i <= 1) {
          g.drawLine(w / 2 + i * 10, h * 76 / 100, w / 2 + i * 10, h * 76 / 100 - 41)
          i += 1
        }
        g.drawLine(w / 2 - 13, h * 76 / 100 - 41, w / 2 + 13, h * 76 / 100 - 41)
        i = -1
        while (i <= 1) {
          g.drawLine(w / 2 + i * 5, h * 35 / 100, w / 2 + i * 5, h * 35 / 100 - 23)
          i += 1
        }
        g.drawLine(w / 2 - 8, h * 35 / 100 - 23, w / 2 + 8, h * 35 / 100 - 23)
      }

      private def drawFielders(g: Graphics2D, w: Int, h: Int): Unit = {
        val positions = if (fieldPreset == "ATTACKING") Vector((0.34, 0.56), (0.66, 0.56), (0.40, 0.44), (0.60, 0.44), (0.50, 0.51))
          else if (fieldPreset == "BOUNDARY DEFENCE") Vector((0.13, 0.62), (0.87, 0.62), (0.20, 0.43), (0.80, 0.43), (0.50, 0.27), (0.10, 0.45), (0.90, 0.45))
          else if (fieldPreset == "SPIN TRAP") Vector((0.36, 0.56), (0.64, 0.56), (0.28, 0.43), (0.72, 0.43), (0.50, 0.48), (0.50, 0.25))
          else Vector((0.20, 0.59), (0.80, 0.59), (0.27, 0.43), (0.73, 0.43), (0.50, 0.26), (0.12, 0.45), (0.88, 0.45))
        positions.foreach { pos => drawHuman(g, w.toDouble * pos._1, h.toDouble * pos._2, 0.39, new Color(62, 157, 117), "FIELDER", false) }
      }

      private def drawHuman(g: Graphics2D, centerX: Double, baseY: Double, scale: Double, jersey: Color, role: String, withBat: Boolean): Unit = {
        val cx = centerX.toInt
        val fy = baseY.toInt
        val head = Math.max(8, (21.0 * scale).toInt)
        val bodyW = Math.max(11, (31.0 * scale).toInt)
        val bodyH = Math.max(17, (43.0 * scale).toInt)
        val leg = Math.max(15, (34.0 * scale).toInt)
        val shadowW = Math.max(12, (31.0 * scale).toInt)
        g.setColor(new Color(0, 0, 0, 75))
        g.fillOval(cx - shadowW / 2, fy - 3, shadowW, Math.max(4, (8.0 * scale).toInt))
        g.setStroke(new BasicStroke(Math.max(2.0, 6.0 * scale).toFloat, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND))
        g.setColor(new Color(28, 35, 43))
        g.drawLine(cx - bodyW / 4, fy - leg, cx - bodyW / 3, fy - 2)
        g.drawLine(cx + bodyW / 4, fy - leg, cx + bodyW / 3, fy - 2)
        g.setColor(new Color(23, 30, 39))
        g.drawLine(cx - bodyW / 3, fy - 2, cx - bodyW / 2, fy)
        g.drawLine(cx + bodyW / 3, fy - 2, cx + bodyW / 2, fy)
        g.setPaint(new GradientPaint(cx - bodyW / 2, fy - leg - bodyH, jersey.brighter(), cx + bodyW / 2, fy - leg, jersey.darker()))
        g.fill(new RoundRectangle2D.Double(cx.toDouble - bodyW.toDouble / 2.0, fy - leg - bodyH, bodyW, bodyH, 12.0 * scale, 12.0 * scale))
        g.setColor(new Color(255, 255, 255, 85))
        g.fill(new RoundRectangle2D.Double(cx.toDouble - bodyW.toDouble / 3.0, fy - leg - bodyH + 4.0 * scale, bodyW.toDouble / 3.0, bodyH.toDouble * 0.48, 5.0 * scale, 5.0 * scale))
        g.setStroke(new BasicStroke(Math.max(2.0, 5.0 * scale).toFloat, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND))
        g.setColor(new Color(190, 137, 102))
        g.drawLine(cx - bodyW / 2, fy - leg - bodyH + (10.0 * scale).toInt, cx - bodyW, fy - leg - (5.0 * scale).toInt)
        g.drawLine(cx + bodyW / 2, fy - leg - bodyH + (10.0 * scale).toInt, cx + bodyW, fy - leg - (11.0 * scale).toInt)
        g.setColor(new Color(220, 174, 139))
        g.fill(new Ellipse2D.Double(cx.toDouble - head.toDouble / 2.0, fy - leg - bodyH - head + 3.0 * scale, head, head))
        g.setColor(new Color(69, 43, 31))
        g.fill(new Ellipse2D.Double(cx.toDouble - head.toDouble / 2.0 - 1.0 * scale, fy - leg - bodyH - head, head.toDouble + 2.0 * scale, head.toDouble * 0.36))
        g.setColor(new Color(34, 39, 44))
        g.fillOval(cx - (4.0 * scale).toInt, (fy - leg - bodyH - head.toDouble * 0.46).toInt, Math.max(2, (2.5 * scale).toInt), Math.max(2, (2.5 * scale).toInt))
        g.fillOval(cx + (2.0 * scale).toInt, (fy - leg - bodyH - head.toDouble * 0.46).toInt, Math.max(2, (2.5 * scale).toInt), Math.max(2, (2.5 * scale).toInt))
        g.setColor(new Color(120, 67, 58))
        g.drawArc(cx - (3.0 * scale).toInt, (fy - leg - bodyH - head.toDouble * 0.30).toInt, Math.max(3, (6.0 * scale).toInt), Math.max(2, (3.0 * scale).toInt), 190, 150)
        if (withBat) {
          g.setColor(new Color(175, 121, 65))
          g.setStroke(new BasicStroke(Math.max(3.0, 5.0 * scale).toFloat, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND))
          g.drawLine(cx + bodyW / 2, fy - leg - bodyH + (7.0 * scale).toInt, cx + (47.0 * scale).toInt, fy - leg - bodyH - (24.0 * scale).toInt)
          g.setColor(new Color(229, 198, 142))
          g.setStroke(new BasicStroke(Math.max(5.0, 9.0 * scale).toFloat, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND))
          g.drawLine(cx + (47.0 * scale).toInt, fy - leg - bodyH - (24.0 * scale).toInt, cx + (56.0 * scale).toInt, fy - leg - bodyH - (57.0 * scale).toInt)
        }
        if (role == "BOWLER") {
          g.setColor(new Color(230, 230, 240, 160))
          g.drawArc(cx - bodyW, fy - leg - bodyH, bodyW * 2, bodyH, 30, 130)
        }
      }

      private def drawBall(g: Graphics2D, w: Int, h: Int): Unit = {
        if (ballActive) {
          val startX = w.toDouble * 0.50
          val endX = w.toDouble * 0.50 + shotAim.toDouble * 95.0
          val startY = if (userBatting) h.toDouble * 0.34 else h.toDouble * 0.78
          val endY = if (userBatting) h.toDouble * 0.78 else h.toDouble * 0.34
          val px = startX + (endX - startX) * ballProgress
          val curve = Math.sin(ballProgress * Math.PI) * (if (bowlType == "OFF SPIN" || bowlType == "LEG SPIN") 62.0 else 34.0)
          val py = startY + (endY - startY) * ballProgress - curve
          val size = (5.0 + 8.0 * ballProgress).toInt
          g.setColor(new Color(0, 0, 0, 70)); g.fillOval(px.toInt - size, py.toInt + size, size * 2, Math.max(2, size / 2))
          g.setColor(new Color(187, 35, 48)); g.fillOval(px.toInt - size / 2, py.toInt - size / 2, size, size)
          g.setColor(new Color(255, 233, 224)); g.drawArc(px.toInt - size / 2, py.toInt - size / 2, size, size, 15, 150)
        }
      }

      private def drawAimGuide(g: Graphics2D, w: Int, h: Int): Unit = {
        g.setColor(new Color(255, 255, 255, 75))
        g.setStroke(new BasicStroke(1.5f))
        val y = h * 78 / 100
        val x = w / 2 + shotAim * 95
        g.drawLine(w / 2, y, x, y - 65)
        g.setColor(GOLD)
        g.fillOval(x - 5, y - 70, 10, 10)
      }

      private def drawGroundLabels(g: Graphics2D, w: Int, h: Int): Unit = {
        g.setFont(new Font("SansSerif", Font.BOLD, 12))
        g.setColor(new Color(255, 255, 255, 210))
        g.drawString("LEG SIDE", 22, h - 24)
        g.drawString("STRAIGHT", w / 2 - 30, h - 24)
        g.drawString("OFF SIDE", w - 92, h - 24)
        g.setColor(GOLD)
        g.drawString("CLICK LEFT / CENTER / RIGHT TO AIM", w / 2 - 125, 24)
        if (!userBatting) {
          g.setColor(CYAN)
          g.drawString("BOWLING: " + bowlType + "  ?  " + bowlLine + "  ?  " + bowlLength, 20, 46)
        }
      }
    }
  }

  class StadiumPreview extends JPanel {
    setOpaque(true)
    setBackground(new Color(13, 35, 58))
    setPreferredSize(new Dimension(760, 290))
    override def paintComponent(g0: Graphics): Unit = {
      super.paintComponent(g0)
      val g = g0.create().asInstanceOf[Graphics2D]
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
      val w = getWidth
      val h = getHeight
      g.setPaint(new GradientPaint(0, 0, new Color(29, 90, 126), 0, h, new Color(6, 24, 40)))
      g.fillRect(0, 0, w, h)
      g.setColor(new Color(38, 74, 99)); g.fillOval(-w / 10, h / 4, w * 6 / 5, h)
      g.setColor(new Color(27, 120, 77)); g.fillOval(w / 12, h / 2, w * 5 / 6, h)
      g.setColor(new Color(216, 180, 128))
      val pitch = new Polygon()
      pitch.addPoint(w / 2 - 18, h / 2); pitch.addPoint(w / 2 + 18, h / 2); pitch.addPoint(w / 2 + 43, h); pitch.addPoint(w / 2 - 43, h)
      g.fillPolygon(pitch)
      g.setColor(GOLD); g.setFont(new Font("SansSerif", Font.BOLD, 25)); g.drawString("BIXUU CRICKET LEAGUE", 22, 39)
      g.setColor(WHITE); g.setFont(new Font("SansSerif", Font.PLAIN, 13)); g.drawString("TOSS  ?  CAPTAIN  ?  FIELD SETUP  ?  BAT / BOWL  ?  TAKE WICKETS", 24, 63)
      g.dispose()
    }
  }
}
BixuuCricketLeague.main(Array[String]())