脚本宝典收集整理的这篇文章主要介绍了【Java猫说】构建战舰类控制台游戏,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
阅读本文约 “7分钟”
我们将用基础Java来模拟实现大家熟悉的战舰游戏,目标是要猜想对方战舰坐标,然后开炮攻击,命中所有战舰后,游戏结束。接下来我们来分析一下具体的实现。
游戏目标:玩家输入坐标,打击随机生成的战舰,全部打掉时游戏通关
初始设置:创建随机战舰数组坐标,这里我们用Int类型的数组来表示,开始等待用户攻击
进行游戏:用户输入一个坐标后,游戏程序判断是否击中,返回提示“miss”、“hIT”,当全部击中时,返回“kill”,显示用户总共击杀次数并结束游戏。
UML设计
代码编程
由此我们大概需要三个类,一个主执行类,一个游戏设置与逻辑判断类,一个用户输入交互类
我们先看看用户交互类,其作用就是获取用户输入坐标
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,需要一个对数组的循环判断
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+"击杀"); } } } }
游戏效果
下次我们再实现一个更好的游戏吧。
本文已转载个人技术公众号:UncleCatMySelf
欢迎留言讨论与点赞
上一篇推荐:【Java猫说】实例变量与局部变量
下一篇推荐:【Java猫说】ArrayList处理战舰游戏BUG
以上是脚本宝典为你收集整理的【Java猫说】构建战舰类控制台游戏全部内容,希望文章能够帮你解决【Java猫说】构建战舰类控制台游戏所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。