【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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值