Monday, May 18, 2015

Make Java Games

Java games are computer games written in the computer programming language "Java." Java games can be as complex as the shoot-'em-up three dimensional games written in other languages, or as simple as a traditional jigsaw or word puzzle. Regardless of the type of games they ultimately want to create, game programmers can begin learning Java game programming by copying existing, simple programs such as the following word game.


Instructions


1. Download and install the Java Development Kit (JDK) from java.sun.com. Begin creating the wordGame program by opening up NotePad and entering the following code for the game's main class:


import java.io.*;


public class wordGame


{


/**


* Constructor for objects of class wordGame


*/


public wordGame()


{


}


public static void main (String args[])


{


String strGuess;


QuizMaster qm = new QuizMaster();


qm.chooseWord();


//Open console for input


Console c = System.console();


if (c == null) {


System.err.println("No console.");


System.exit(1);


}


//Loop until game is over


while (!qm.gameOver()) {


qm.showGameboard();


System.out.format("You have %d attempts remaining.\n", qm.getRemainingAttempts() );


strGuess = c.readLine("Enter your guess: ");


qm.evaluateGuess(strGuess);


}// end main loop


if (qm.playerWon() ) {


System.out.format("You Won! It took you %d attempts.\n", qm.nGuessesNeeded());


System.out.format( qm.getWord());


}// if player won


else {


System.out.format("You lost. The word was %s\n", qm.getWord());


}// if player won


}//end of main


}


Save the file with the filename "wordGame.java" in a folder called WordGame. Be sure to match the case of each letter to that given here because Java is case sensitive.


2. Create the QuizMaster class, which represents a QuizMaster who chooses words at random, compares the player's guess to the chosen word and reports when the player has won or lost. Enter the following program code in a file called QuizMaster.java and save it in the WordGame folder that contains the wordGame.java file:


import java.util.*;


public class QuizMaster


{


private final int MAX_GUESSES_ALLOWED = 15;


private String GameWords[]= {"computer", "thoroughbred", "exceptional", "helicopter", "flugelhorn" };


private String targetWord;


private int nTriesLeft;


private gameBoard gb;


public QuizMaster()


{


nTriesLeft = MAX_GUESSES_ALLOWED;


return;


}


public void chooseWord()


{


Random obRand = new Random();


int i = obRand.nextInt(GameWords.length);


targetWord = GameWords[i];


gb = new gameBoard(targetWord);


}


public boolean gameOver() {


//There are two end conditions: the player wins or the nTriesLeft goes to 0


if (gb.blnMatch()) return true;


if (nTriesLeft ==0) return true; else return false;


}


public boolean playerWon() {


return (gb.blnMatch() );


}//player won


public int getRemainingAttempts(){


return nTriesLeft;


}//showAttempts


public String getWord () {


return targetWord;


}//showWord


public void showGameboard() {


gb.showBoard();


}//showGameboard


public int nGuessesNeeded () {


return MAX_GUESSES_ALLOWED - nTriesLeft;


}//nGuessesNeeded


public void evaluateGuess(String strGuess) {


nTriesLeft -=1;


gb.uncoverLetters(strGuess);


}


};// end of QuizMaster class


3. Create the class that uncovers the letters in the word chosen by the QuizMaster that match the letters entered by the player: in a file called gameBoard.java, enter the following text and save it in the same folder containing the other wordGame files:


import java.io.*;


public class gameBoard


{


private String strGameboard;


private String strTarget;


private String lettersTested; // these are all the individual letters player has tried to match with


/**


* Constructor for objects of class gameBoard


*/


public gameBoard(String str)


{


strTarget = str;


strGameboard = new String(str);


lettersTested = new String("");


strGameboard = strGameboard.replaceAll(".", "_");


return;


}


public void uncoverLetters(String str)


{


String strRE;


//For guesses of one char long, uncover all letters in target that match


//But treat guesses longer than 1 char as a word against word. Uncover all or no letters


if (str.length() == 1) {


// concatenate new letter with letters already tested


lettersTested = lettersTested + str;


strRE = "[^" + lettersTested + "]";


// hide all non-matching chars: replace all letters in target that do NOT match pattern with the underscore


strGameboard = strTarget.replaceAll(strRE, "_");


}


else {


if (str.compareToIgnoreCase(strTarget) == 0) {


strGameboard = strTarget;


}


}


return;


}


public boolean blnMatch() {


return ( strTarget==strGameboard );


}


public void showBoard() {


int i;


for (i=0; icmd), and type PATH=" C:\Program Files\Java\jdk1.6.0_14\." This folder should contain your java compiler (javac.exe). If it does not, locate javac.exe using a Windows Explorer search, then enter its path with the PATH=... statement just given.


At the command prompt, use the "cd" command to navigate to the folder that contains the wordGame folder. Compile all files with this statement: javac *.java.


5. Run the game by typing "java wordGame". Play the game by entering one letter at a time, until you run out of guesses or you guess the word. If you enter more than one letter at once, the gameBoard class thinks you're trying to guess the whole word and won't uncover any letters unless you match them all.


6. Memorize and modify the game to begin creating your own games. You can easily change the words the QuizMaster chooses from, by noticing how the "GameWords =..." statement is structured. You can easily change the number of tries the player has to guess the word with the statement containing the MAX_GUESSES_ALLOWED constant.

Tags: private String, public void, System format, import java, public boolean