import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MultiCraps extends JApplet implements ActionListener { Die die1 = new Die(); Die die2 = new Die(); int wins = 0; int losses = 0; int point = 0; final String WINNER = "WINNER"; final String LOSER = "CRAPS!"; String resultText = ""; JButton rollButton = new JButton("Roll Dice"); JButton nonstopButton = new JButton("Roll Nonstop"); DiceRoller roll; public void init() { Container pane = getContentPane(); FlowLayout flo = new FlowLayout(); setBackground(Color.green); rollButton.addActionListener(this); nonstopButton.addActionListener(this); pane.setLayout(flo); pane.add(rollButton); pane.add(nonstopButton); setContentPane(pane); } public void paint(Graphics screen) { super.paint(screen); Graphics2D screen2D = (Graphics2D) screen; die1.drawDie(screen2D, 5F, 50F); die2.drawDie(screen2D, 175F, 50F); screen2D.setColor(Color.black); Font f = new Font("Helvetica", Font.BOLD, 15); screen2D.setFont(f); if (point != 0) screen2D.drawString(point + " wins and 7 craps out.", 5, 200); else screen2D.drawString("7 or 11 win; 2, 3, or 12 crap out.", 5, 200); screen2D.drawString("Number of wins: " + wins, 5, 220); screen2D.drawString("Number of losses: " + losses, 5, 240); if (resultText != "") { f = new Font("Helvetica", Font.BOLD, 30); screen2D.setFont(f); screen2D.drawString(resultText, 85, 110); resultText = ""; } } public void actionPerformed(ActionEvent event) { String buttonHit = event.getActionCommand(); System.out.println(buttonHit); if (buttonHit.equals("Roll Dice") == true) { die1.rollValue(6); die2.rollValue(6); checkResult(die1, die2); } if (buttonHit.equals("Roll Nonstop") == true) { nonstopButton.setText("Stop Rolling"); roll = new DiceRoller(die1, die2, this); roll.start(); } if (buttonHit.equals("Stop Rolling") == true) { nonstopButton.setText("Roll Nonstop"); roll.stop(); } repaint(); } public void checkResult(Die d1, Die d2) { if (point == 0) { point = d1.value + d2.value; if ( (point == 7) | (point == 11) ) resultText = WINNER; if ( (point < 4) | (point == 12) ) resultText = LOSER; } else { if (d1.value + d2.value == point) resultText = WINNER; if (d1.value + d2.value == 7) resultText = LOSER; } if (resultText == WINNER) { wins++; point = 0; } if (resultText == LOSER) { losses++; point = 0; } } } class DiceRoller implements Runnable { Die die1; Die die2; Thread runner; MultiCraps main; DiceRoller(Die d1, Die d2, MultiCraps m) { die1 = d1; die2 = d2; main = m; } public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } public void stop() { if (runner != null) { runner = null; } } public void run() { Thread thisThread = Thread.currentThread(); while (runner == thisThread) { die1.rollValue(6); die2.rollValue(6); main.checkResult(die1,die2); main.repaint(); try { Thread.sleep(1000); } catch (InterruptedException e) { // Do nothing } } } }