Head first java 第五章(一)

Dotcom游戏

实现一个战舰类的棋牌游戏
1.0 首先写出一个测试代码SimpleDotComTestDrive(该版本为最简易版本,无需输入)

public class SimpleDotComTestDrive {
    public static void main (String[] args){
        SimpleDotCom dot = new SimpleDotCom();  //创建实例对象
        int [] locations = {2,3,4};  //假设目标坐标
        dot.setLocationCells(locations);  //为实例对象设置坐标
        String userGuess = "2";  //假设游戏者输入坐标2
        String result = dot.checkYourself(userGuess);   //使用checkYourself方法检查
    }
}

根据测试码可知运行该游戏后,输出为hit

真实码

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);  //Sting转换为int
        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;
    }
}

2.0 仍然保留SimpleDotCom类,删除SimpleDotComTestDrive类,另外加入SimpleDotComGame类,该类代码如下:

package game;

public class SimpleDotComGame {
    public static void main (String[] args){

    int numOfGuesses = 0;
    GameHelper helper = new GameHelper();

    SimpleDotCom theDotCom = new SimpleDotCom();
    int radomNum = (int) (Math.random()*5);

    int[] locations = {radomNum,radomNum+1,radomNum+2};
    theDotCom.setLocationCells(locations);
    boolean isAlive = true;

    while (isAlive == true){
        String guess = helper.getUserInput("你猜");
        String result = theDotCom.checkYourself(guess);
        numOfGuesses++;
        if(result.equals("kill")){
            isAlive = false;
            System.out.println("你猜了"+numOfGuesses);
        }
    }
}
}

以及GameHelper类:(该部分代码为copy,暂且不管)

package game;

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 19
    ArrayList<String> alphaCells = new ArrayList<String>();
    String [] alphacoords = new String [comSize];      // holds 'f6' type coords
    String temp = null;                                // temporary String for concat
    int [] coords = new int[comSize];                  // current candidate coords
    int attempts = 0;                                  // current attempts counter
    boolean success = false;                           // flag = found a good location ?
    int location = 0;                                  // current starting location

    comCount++;                                        // nth dot com to place
    int incr = 1;                                      // set horizontal increment
    if ((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 place
        success = true;                                 // assume success
        while (success && x < comSize) {                // look for adjacent unused spots
          if (grid[location] == 0) {                    // if not already used
             coords[x++] = location;                    // save location
             location += incr;                          // try 'next' adjacent
             if (location >= gridSize){                 // out of bounds - 'bottom'
               success = false;                         // failure
             }
             if (x>0 & (location % gridLength == 0)) {  // out of bounds - right edge
               success = false;                         // failure
             }
          } else {                                      // found already used location
              // System.out.print(" used " + location);  
              success = false;                          // failure
          }
        }
    }                                                   // end while

    int x = 0;                                          // turn good location into alpha coords
    int 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 value
      column = coords[x] % gridLength;                  // get numeric column value
      temp = String.valueOf(alphabet.charAt(column));   // convert to alpha

      alphaCells.add(temp.concat(Integer.toString(row)));
      x++;

      // System.out.print("  coord "+x+" = " + alphaCells.get(x-1));

    }
    // System.out.println("\n");

    return alphaCells;
   }
}

结果为该次改动能够实现输入的读取,进行互动化;
然而存在不足,为当命中目标后再次猜测统一坐标仍然有效,需要再改。

3.0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值