@Senl
2017-03-23T11:58:17.000000Z
字数 6016
阅读 1267
技术学习
if(guess>=1 && guess<=9)和if(guess>=10 && guess <=0){result = "Out of Range input again";}//检测用户输入的值是否存在于战场域中,如果输入越界则将提醒用户输入越界//用户输入不越界才进行检测//并定义了一个实例变量check,当第一次击中时候,check=guess以保护这个方块//再次击中则不算入击中数中if(guess>=1 && guess<=9){for (int cell : locationCells){if (guess == cell){//增加一个check变量防止多次击中同一个部位造成Killif(check==guess){result= "You have already hit it ";}if(check != guess){result = "hit";check = guess;num_Hits ++;}break;}}// break for loops}
//战舰游戏简版游戏类// 优化版的游戏战舰设计类import java.util.ArrayList;/*ArrayList 一些方法@ add(Object) 向List中加入对象参数@ remove(int) 在索引参数中删除对应的对象@remove(Object) 移除该对象@contains(Object) 如果和对象参数匹配返回“true”@isEmpty() 如果list中没有元素返回true@index(Object) 返回对象参数的索引或-1@size 返回list元素中的一个数@get(int) 返回当前索引参数的对象*/public class Dotc {private ArrayList<String> locationCells;public void setLocationCells(ArrayList<String> loc){locationCells = loc;}public String checkYourself (String stringGuess){String result = "miss";int index = locationCells.indexOf(userInput);if(index >= 0){locationCells.remove(index);if(locationCells.isEmpty()) {result = "kill";}else{result = " hit";}}return result ;}}
//战舰类,创造三个战舰并为他们命名package Test; //好像不加这个就过不编译 但是不懂原理import java.util.ArrayList;public class DotCom {private ArrayList<String> locationCells;public void setLocationCells(ArrayList<String> loc){locationCells = loc;}public String checkYourself(String userInput){String result = "miss";int index = locationCells.indexOf(userInput);if (index >= 0) {locationCells.remove(index);if (locationCells.isEmpty()) {result = "kill";}else{result = "hit";}}return result;}//TODO: all the following code was added and should have been included in the bookprivate String name;public void setName(String string) {name = string;}}
//游戏主类,定义了创造游戏(创造对象并放入ArrayList),开始游戏(检查战舰是否存活,输入和检查),检查输入,和结束游戏4个方法 并且是作为main方法入口package Test;import java.util.*;public class DotComBust {private GameHelper helper = new GameHelper();private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();private int numOfGuesses = 0;private void setUpGame() {DotCom one = new DotCom();one.setName("Pets.com");DotCom two = new DotCom();two.setName("eToys.com");DotCom three = new DotCom();three.setName("Go2.com");dotComsList.add(one);dotComsList.add(two);dotComsList.add(three);System.out.println("Your goal is to sink three dot coms.");System.out.println("Pets.com, eToys.com, Go2.com");System.out.println("Try to sink them all in the fewest number of guesses");for (DotCom dotComSet : dotComsList) {ArrayList<String> newLocation = helper.placeDotCom(3);dotComSet.setLocationCells(newLocation);}}private void startPlaying() {while (!dotComsList.isEmpty()) {String userGuess = helper.getUserInput("Enter a guess");checkUserGuess(userGuess);}finishGame();}private void checkUserGuess(String userGuess){numOfGuesses++;String result = "miss";for (DotCom dotComToTest : dotComsList){result = dotComToTest.checkYourself(userGuess);if (result.equals("hit")){break;}if (result.equals("kill")){dotComsList.remove(dotComToTest);break;}}System.out.println(result);}private void finishGame() {System.out.println("All Dot Coms are dead! Your stock is now worthless");if (numOfGuesses <= 18) {System.out.println("It only took you " + numOfGuesses + " guesses");System.out.println("You got out before your options sank.");}else{System.out.println("Took you long enough. " + numOfGuesses + " guesses.");System.out.println("Fish are dancing with your options.");}}public static void main(String[] args) {DotComBust game = new DotComBust();game.setUpGame();game.startPlaying();}}
//GameHelper类 处理输入,设置战舰位置//搬的砖头,有些不太理解,日后回头再改package Test;import java.io.*;import java.util.*;public class GameHelper {private static final String alphabet = "abcdefg";private int gridLength = 7;private int gridSize = 49;private int [] grid = new int[gridSize];private int comCount = 0;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.toLowerCase();}public ArrayList<String> placeDotCom(int comSize) { // line 19ArrayList<String> alphaCells = new ArrayList<String>();String [] alphacoords = new String [comSize]; // holds 'f6' type coordsString temp = null; // temporary String for concatint [] coords = new int[comSize]; // current candidate coordsint attempts = 0; // current attempts counterboolean success = false; // flag = found a good location ?int location = 0; // current starting locationcomCount++; // nth dot com to placeint incr = 1; // set horizontal incrementif ((comCount % 2) == 1) { // if odd dot com (place vertically)incr = gridLength; // set vertical increment}while ( !success & attempts++ < 200 ) { // main search loop (32)location = (int) (Math.random() * gridSize); // get random starting point//System.out.print(" try " + location);int x = 0; // nth position in dotcom to placesuccess = true; // assume successwhile (success && x < comSize) { // look for adjacent unused spotsif (grid[location] == 0) { // if not already usedcoords[x++] = location; // save locationlocation += incr; // try 'next' adjacentif (location >= gridSize){ // out of bounds - 'bottom'success = false; // failure}if (x>0 & (location % gridLength == 0)) { // out of bounds - right edgesuccess = false; // failure}} else { // found already used location// System.out.print(" used " + location);success = false; // failure}}} // end whileint x = 0; // turn good location into alpha coordsint row = 0;int column = 0;// System.out.println("\n");while (x < comSize) {grid[coords[x]] = 1; // mark master grid pts. as 'used'row = (int) (coords[x] / gridLength); // get row valuecolumn = coords[x] % gridLength; // get numeric column valuetemp = String.valueOf(alphabet.charAt(column)); // convert to alphaalphaCells.add(temp.concat(Integer.toString(row)));x++;// System.out.print(" coord "+x+" = " + alphaCells.get(x-1)); //将注释去掉就可以获得三个战舰的位置}//System.out.println("\n");//获得三个战舰位置前取消去掉注释可以使格式更好看return alphaCells;}}