Java学习之路(Head First Java)--“Sink a DotCom”代码

  虽然代码是抄书,但是用注释的方式帮助自己尽力靠记忆和理解写代码是一个很好的方法,代码如下:DotComBust.java

package java1;

import  java.util.*;
public class DotComBust {
	//声明并初始化变量
	private GameHelper helper = new GameHelper();
	private ArrayList<DotCom> dotComList = new ArrayList<DotCom>();
	private int numOfGuesses = 0;		
	private void setUpGame() {
		//cerate 3 dot com and give them locations
		DotCom one1 = new DotCom();
		one1.setName("wang.com");
		DotCom two2 = new DotCom();
		two2.setName("zhi.com");
		DotCom three3 = new DotCom();
		three3.setName("cheng.com");
		
		dotComList.add(one1);
		dotComList.add(two2);
		dotComList.add(three3);
		//give prief notes
		System.out.println("Your goal is to sink three dot coms.");
		System.out.println("wang.zhi.cheng.com.");
		System.out.println("Try to sink all of them.");
		//repeat for every DotCom in list 
		for(DotCom dotComLocToSet:dotComList) {
			//call for location,placeDotCom 方法
			ArrayList<String> newLocations = helper.placeDotCom(3);
			dotComLocToSet.setLocationCells(newLocations);
		}
	}
	
	
	private void startPlaying() {
		//check if DotComList is empty
		while(!dotComList.isEmpty()) {
			//get player's input;
			String userGuess = helper.getUserInput("Enter a guess");
			//use checkUserGuess
			checkUserGuess(userGuess);
		}
		//use finishGame
		finishGame();
	}

	private void checkUserGuess(String userGuess) {
		//increase count of user guess
		numOfGuesses++;
		//assumpt miss
		String result = "miss";
		//repeat for every DotCom in list
		for(DotCom dotComToTest : dotComList) {
			//check if DotCom hitted
			result = dotComToTest.checkYourself(userGuess);
			//check if DotCom hitted
			if(result.equals("hit")) {
				break;
			}
			//if sunk 
			//DomCom dead,remove
			//jumo loop
			if(result.equals("kill")) {
				dotComList.remove(dotComToTest);
				break;
			}
		}
			
			
		System.out.println(result);
		//list result
	}

	
	private void finishGame(){
		System.out.println("All Dot Com are dead.");
		if(numOfGuesses<=18) {
			System.out.println("you took "+numOfGuesses+" times to guess,excellent.");
		}
		else {
			System.out.println("you took "+numOfGuesses+" times to guess,That's OK.");
		}
	}
	
	
	public static void main(String[] args) {
		DotComBust game = new DotComBust();
		game.setUpGame();
		game.startPlaying();
	}
}

DotCom.java

package java1;
import java.util.*;
public class DotCom {
	//arraylist to save location
	//dotcom name
	private ArrayList<String> locationCells;
	private String name;
	
	//setname setter
	//fresh location setter
	public void setName(String n) {
		this.name = n;
	}
	
	public void setLocationCells(ArrayList<String> loc) {
		locationCells = loc;
	}
	
	public String checkYourself(String userInput) {
		String result = "miss";
		//checkyouself method,ues indexof()
		int index = locationCells.indexOf(userInput);
		//if user guess right,delete elem. if wrong,return -1
		if(index >= 0) {
			locationCells.remove(index);
			if(locationCells.isEmpty()) {
				result = "kill";
			} else {
				result = "hit";
						
			}
		}
		return result;
		
	}
	

		//if sunk,return kill.or return hit.
}

GameHelper.java(摘自网络)

package java1;

/**
 * 2013.03.25
 * Michel
 * 鐢ㄤ簬鎺ユ敹鐢ㄦ埛杈撳叆
 */
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) {       
    ArrayList<String> alphaCells = new ArrayList<String>();
    //String [] alphacoords = new String [comSize];      // 淇濆瓨瀛楃涓�
    String temp = null;                                // 涓存椂瀛楃涓�
    int [] coords = new int[comSize];                  // 鐜版湁瀛楃涓�
    int attempts = 0;                                  // 鐩墠娴嬭瘯鐨勫瓧绗︿覆
    boolean success = false;                           // flag = 鎵惧埌浜嗗悎閫傜殑瀛楃鍚� ?
    int location = 0;                                  // 鐩墠璧风偣
    
    comCount++;                                      
    int incr = 1;                                       
    if ((comCount % 2) == 1) {                          
      incr = gridLength;                               
    }

    while ( !success & attempts++ < 200 ) {           
	location = (int) (Math.random() * gridSize);      
        //System.out.print(" try " + location);
	int x = 0;                                        
        success = true;                               
        while (success && x < comSize) {              
          if (grid[location] == 0) {                   
             coords[x++] = location;                   
             location += incr;                           
             if (location >= gridSize){                  
               success = false;                          
             }
             if (x>0 & (location % gridLength == 0)) {   
               success = false;                         
             }
          } else {                                     
              // System.out.print(" used " + location);  
              success = false;                           
          }
        }
    }                                                 

    int x = 0;                                          
    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;
   }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值