阅读本文约 “7分钟”java
咱们将用基础Java来模拟实现你们熟悉的战舰游戏,目标是要猜测对方战舰坐标,而后开炮攻击,命中全部战舰后,游戏结束。接下来咱们来分析一下具体的实现。编程
游戏目标:玩家输入坐标,打击随机生成的战舰,所有打掉时游戏通关
初始设置:建立随机战舰数组坐标,这里咱们用Int类型的数组来表示,开始等待用户攻击
进行游戏:用户输入一个坐标后,游戏程序判断是否击中,返回提示“miss”、“hit”,当所有击中时,返回“kill”,显示用户总共击杀次数并结束游戏。segmentfault
由此咱们大概须要三个类,一个主执行类,一个游戏设置与逻辑判断类,一个用户输入交互类数组
咱们先看看用户交互类,其做用就是获取用户输入坐标dom
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; } }
接下来看看游戏设置类与逻辑处理,须要一个数组set,须要一个对数组的循环判断spa
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); return result; } }
看到这里你应该也能写出主执行方法了吧设计
public class Main { public static void main(String[] args) { //记录玩家猜想次数的变量 int numOfGuesses = 0; //获取玩家输入的对象 GameHelper helper = new GameHelper(); //建立dotCom对象 SimpleDotCom dotCom = new SimpleDotCom(); //用随机数产生第一格的位置,而后以此制做数组 int randomNum = (int)(Math.random()*5); int[] locations = {randomNum,randomNum+1,randomNum+2}; //赋值位置 dotCom.setLocationCells(locations); //记录游戏是否继续 boolean isAlive = true; while (isAlive == true){ //获取玩家输入 String guess = helper.getUserInput("请输入一个数字"); //检查玩家的猜想并将结果存储在String中 String result = dotCom.checkYourSelf(guess); numOfGuesses++; //击杀完成,退出,打印击杀次数 if (result.equals("kill")){ isAlive = false; System.out.println("你执行了"+numOfGuesses+"击杀"); } } } }
下次咱们再实现一个更好的游戏吧。code
本文已转载我的技术公众号:UncleCatMySelf
欢迎留言讨论与点赞
上一篇推荐:【Java猫说】实例变量与局部变量
下一篇推荐:【Java猫说】ArrayList处理战舰游戏BUG对象