Java实例——DotCom击沉达康

2019-02-18
最近两个礼拜读完了head first java,但是实例没来得及实践,所以开坑学习实例。


游戏截图:


image.png

image.png

游戏介绍:在7*7(即49块)地图中随机生成3组DotCom,每一组是连续的三块区域,用户通过猜测坐标来达到击沉DotCom的目的,kill全部三组DotCom后,游戏结束。


游戏设计

  1. DotCom类——一组DotCom该如何存放,DotCom类中该有哪些状态和行动
  • DotCom每一组都要有个名字——Name
  • 每一组都占三块空间,所以需要ArrayList来存放——ArrayList locationCells
  • 需要一个函数实现用户输入的猜测与ArrayList中的三块空间进行比对—— checkYourself()
  1. DotComBust类——开始游戏+进行游戏+结束游戏
  • 建立对象并初始化+生成地图——setUpGame()
  • 主循环体+读入玩家猜测的字符+判断字符匹配度——startPlaying()+checkUserGuess()
  • 结束游戏——finishGame()
  1. GameHelper类——读入用户输入+创建7*7的棋盘
  • getUserInput()
  • placeDotCom()

主要代码

1. DotCom.java
import java.util.ArrayList;

public class DotCom {
    private String nameString; //这一组达康的名字
    private ArrayList locationCells; //一组达康的三块位置坐标
    
    public void setName(String n) //名字的setter
    {
        nameString = n;
    }
    
    public void setLocationCells(ArrayList loc) //坐标的setter
    {
        locationCells = loc;
    }
    
    public String checkYourself(String userInput) //startGame函数调用的函数
    {
        String result = "miss";
        int index = locationCells.indexOf(userInput);
        if(index >=0) { //只有index大于0才能往下走,否则判别为无击中
            locationCells.remove(index);
                if(locationCells.isEmpty())
                    {result = "kill";
                    System.out.print("OHHHHHH! You sunk" + " "+nameString+" " );
                    }
                else 
                    result = "hit";
                }
        
        return  result;
    }
}
2.DotComBust.java
import java.util.ArrayList;

public class DotComBust {
    //声明变量
    //【注:变量采用私有更加安全】
    private GameHelper helper = new GameHelper();
    private ArrayList dotComList = new  ArrayList();
    private int numOfGuesses = 0;
    //声明方法
    public void setUpGame()//生成地图
    {
        DotCom a1 = new DotCom();
        a1.setName("SaMuLuo1");
        dotComList.add(a1);
        DotCom a2 = new DotCom();
        a2.setName("SaMuLuo2");
        dotComList.add(a2);
        DotCom a3 = new DotCom();
        a3.setName("SaMuLuo3");
        dotComList.add(a3);
        //【注:loc要定义成DotCom类型才能从dotComList取出元素】
        for(DotCom loc:dotComList)
        {
            //【注:这里是要先生成一个三连的位置,然后将位置传入loc所引用的ArrayList中】
            ArrayList newlocationArrayList = helper.placeDotCom(3);
            loc.setLocationCells(newlocationArrayList);
        }
    }
    public void startPlaying()//主循环,读入数字判断效果,调用后面写的函数
    {
        while (!dotComList.isEmpty()) {
            String userGuessString = helper.getUserInput("Enter a guess");
            checkUserGuess(userGuessString);
            
        }
        finishGame();
        
    }
    public void checkUserGuess(String userGuess)//主循环中的函数,为增加可读性所以另起声明
    {
        numOfGuesses++;
        String result = "miss";
        for(DotCom dotComTest : dotComList)
        {
            result = dotComTest.checkYourself(userGuess);
            if(result.equals("hit"))
                break;
            if(result.equals("kill"))
            {
                dotComList.remove(dotComTest);
                break;
            }
        }
        System.out.print(result+'\n');
    }
    public void finishGame()//结束游戏并计算分数
    {
         System.out.println("All Dot Coms are dead!  Your stock is now worthless");
            if (numOfGuesses <= 18) {
                System.out.println("It only took you " + numOfGuesses + " guesses");
                System.out.println("You got out before your options sank.");
            }
            else
            {
                System.out.println("Took you long enough. " + numOfGuesses + " guesses.");
                System.out.println("Fish are dancing with your options.");
            }
    }
    
    public static void main(String[] args)
    {
        DotComBust gameCom = new DotComBust();
        gameCom.setUpGame();
        gameCom.startPlaying();
    }
}

3.GameHelper.java

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 placeDotCom(int comSize) {                 // line 19
    ArrayList alphaCells = new ArrayList();
    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;
   }
}

总结

通过这个程序,对ArrayList有了一个初步的认识,对于程序设计也有了一些见解。接着就是要学会融会贯通,加入自己的功能进去或者优化代码。

你可能感兴趣的:(Java实例——DotCom击沉达康)