import java.awt.*; import java.applet.*; // A simple game in which each player can take 1, 2 or 3 matches at a time. // Whoever takes the last match wins. We play against the user. // Department of Computer Science, Monash University, Australia 3168 public class TwentyOne extends Applet { static final int MAXMATCHES = 21; static final int MATCHWIDTH = 10; static final int MATCHHEIGHT = 40; Image liveMatchImage, deadMatchImage; int liveMatches = MAXMATCHES; // Current position int deadMatches = 0; // Our most recent move int winner = 0; // 0=none; 1=us; 2=user // Load the graphics at the start. public void init() { liveMatchImage = getImage(getCodeBase(), "images/liveMatch.gif"); deadMatchImage = getImage(getCodeBase(), "images/deadMatch.gif"); } // Draw the applet whenever requested. public void paint(Graphics g) { g.setColor(Color.cyan); g.drawLine(0, MATCHHEIGHT+18, MAXMATCHES*MATCHWIDTH, MATCHHEIGHT+18); g.drawLine(0, MATCHHEIGHT+19, MAXMATCHES*MATCHWIDTH, MATCHHEIGHT+19); g.drawLine(0, MATCHHEIGHT+20, MAXMATCHES*MATCHWIDTH, MATCHHEIGHT+20); for (int r = 0 ; r < liveMatches ; r++) g.drawImage(liveMatchImage, r*MATCHWIDTH, 10, this); for (int r = 0 ; r < deadMatches ; r++) g.drawImage(deadMatchImage, (liveMatches+r)*MATCHWIDTH, 10, this); g.setColor(Color.black); if (winner == 1) g.drawString("I win!", 50, MATCHHEIGHT+10); if (winner == 2) g.drawString("You win!", 50, MATCHHEIGHT+10); } // The user has clicked in the applet. Show their move and our response. public boolean mouseUp(Event e, int x, int y) { if (liveMatches <= 0) { // Restart the game liveMatches = MAXMATCHES; deadMatches = 0; winner = 0; } else { int thisMatch = 1 + x / MATCHWIDTH; if (thisMatch < liveMatches-2 || thisMatch > liveMatches) play(getCodeBase(), "audio/beep.au"); // Illegal move else { play(getCodeBase(), "audio/return.au"); // Legal move liveMatches = thisMatch-1; // Record user's move if (liveMatches == 0) winner = 2; deadMatches = liveMatches%4; // Determine our move if (deadMatches == 0) deadMatches = 1 + (int)(Math.random() * 3); liveMatches -= deadMatches; if (liveMatches == 0) winner = 1; } } repaint(); return true; } } // Prof. L. Goldschlager, Department of Computer Science, // Monash University, Australia 3168 / 1996