Battle-style Game
Version.1
三个类:
- 工具类 GameHelper()
- DotCom类 SimpleDotCom()
- Game类 SimpleDotComGame()
GameHelper():
package BattleGame;
import java.io.*;
public class GameHelper {
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt+" ");
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(System.in));
inputLine = is.readLine();
if(inputLine.length() == 0) return null;
} catch(IOException e) {
System.out.println("IOException: "+ e);
}
return inputLine;
}
}
SimpleDotCom()
package BattleGame;
public class SimpleDotCom {
int[] locationCells;
int numOfHits = 0;
public void setLocationCells(int[] locs) {
locationCells = locs;
}
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for(int cell : locationCells) {
if(guess == cell) {
result = "hit";
numOfHits++;
break;
}
}
if(numOfHits == locationCells.length) {
result = "kill";
}
System.out.println("result: "+result);
return result;
}
}
SimpleDotComGame()
package BattleGame;
public class SimpleDotComGame {
public static void main(String[] args) {
int numOfGuess = 0;
GameHelper helper = new GameHelper();
SimpleDotCom dc = new SimpleDotCom();
int randomNum = (int)(Math.random()*5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
dc.setLocationCells(locations);
boolean isAlive = true;
while(isAlive) {
String guess = helper.getUserInput("enter a number");
String returnResult = dc.checkYourself(guess);
numOfGuess++;
if (returnResult == "kill") {
isAlive = false;
System.out.println("You took "+numOfGuess+" guesses");
}
}
}
}