Lecture 5: CandyLand and Exam Solutions
We have discussed the solutions to the review exam.
We then discussed the game (CandyLand) and the code for the prototype:
import BreezyGUI.*; import java.awt.*; public class CandyLand1 extends GBFrame { Button bMove = addButton ( "Go", 1, 1, 1, 1); Button bStartGame = addButton ( "reStart", 1, 2, 1, 1); TextArea tArea = addTextArea ( "", 2, 1, 2, 10); boolean gameOver = false, gameStarted = false; int currentPlayer = 0, numberOfPlayers = 4; String[] board = { "red", "green", "red", "gumdrop", "yellow", "candycane", "yellow", "blue", "yellow", "green", "purple", "blue" }; Player[] players; String[] colors = {"red", "green", "gumdrop", "yellow", "candycane", "blue", "purple"}; public void buttonClicked (Button buttonObj) { if (buttonObj == bStartGame) startGame(); else moveOnce(); } void startGame() { gameStarted = true; gameOver = false; players = new Player[numberOfPlayers]; for (int i = 0; i < numberOfPlayers; i++) players[i] = new Player("P" + i); currentPlayer = 0; showBoard(); } void moveOnce() { if (! gameStarted) messageBox("Please start the game first."); else if (gameOver) messageBox("The game is over, please restart it."); else { players[currentPlayer].location += 1; if (players[currentPlayer].location == (board.length - 1)) gameOver = true; else currentPlayer = (currentPlayer + 1) % numberOfPlayers; showBoard(); } } void showBoard() { tArea.setText(""); for (int i = board.length - 1; i >= 0; i--) { tArea.append(i + " " + board[i] + ": "); for (int j = 0; j < players.length; j++) { if (i == players[j].location) tArea.append(players[j].name + " "); } tArea.append("\n"); } } public static void main(String[] args) { Frame f = new CandyLand1(); f.setSize(300, 400); f.setVisible(true); } } class Player { String name; int location; Player(String givenName) { name = givenName; location = 0; } }