@Senl
2017-03-21T16:45:52.000000Z
字数 2002
阅读 1205
技术学习
//战舰生成和玩家猜测类//主要是生成一个一维9个格子的战场,有一个长度为两格的战舰,玩家需要猜测它的位置并击中它public class SimpleDot {int[] locationCells;int num_Hits = 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";num_Hits ++;break;}}// break for loopsif(num_Hits == locationCells.length){result= "kill";}System.out.println(result);return result;}}//处理玩家输入的类(搬书上的砖的,大概理解就是如果成功输入就将结果传入,如果不是就为异常,并暂停运行,然后还有异常处理状态这个东西)import java.io.*;public class GameHelper {public String getUserInput(String prompt){String inputLine = null;System.out.println(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;}}//游戏启动类,处理是否击中和修改战舰是否存活这样的东西//其实游戏中存在一个很重大的bug,连续两次击中已知的战舰格子,战舰也会死...//没有限制用户输入的格子数,万一输入的格子数是999怎么办//明天尝试在Helper那里修一下,或者在Drive那public class SimpleDotDrive {public static void main (String[] args){int num_Guess = 0;GameHelper helper = new GameHelper();SimpleDot theDot = new SimpleDot();int randomNum = (int) (Math.random()*8 )+1;int[] locations = {randomNum,randomNum+1};theDot.setLocationCells(locations);boolean isAlive = true ;while(isAlive == true) {String guess = helper.getUserInput("enter a number");String result = theDot.checkYourself(guess);num_Guess ++;if(result.equals("kill")){isAlive = false;System.out.println("YOU took "+num_Guess+" times to guess");}}}}