來(lái)源:《Head First Java》
package games;
public class SimpleDotCom {//僅限于一維空間;
int[] locationCells;//目標(biāo)的坐標(biāo)位置;
int numOfHits = 0;//目標(biāo)被擊中多少次, 擊中一次去掉對(duì)應(yīng)擊中的位置, 全部擊中則勝利;
public void setLocationCells(int[] location) {
locationCells = location;//設(shè)置目標(biāo)的坐標(biāo)集合;
}
public String checkYourself(String guess) {//檢測(cè)當(dāng)前是否被擊中;
int g = Integer.parseInt(guess);//將字符串轉(zhuǎn)換為數(shù)字;
String result = "miss";//最終結(jié)果, 初始化為"miss";
for (int cell : locationCells) {//加強(qiáng)版for循環(huán);
if (cell == g) {
result = "hit";//擊中;
++numOfHits;//當(dāng)前擊中的次數(shù);
break;//這一輪已經(jīng)找到被擊中的位置;
}
}
if (numOfHits == locationCells.length) {//所有位置均被擊中;
result = "kill";//擊沉;
}
System.out.println(result);
return result;
}
}
package games;
import java.io.*;
public class GameHelper {
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;
}
}
package games;
public class SimpleDotComTestDrive {
public static void main(String[] args) {
int numOfGuess = 0;//記錄玩家猜測(cè)次數(shù)的變量;
GameHelper h = new GameHelper();
SimpleDotCom dot = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);//用隨機(jī)數(shù)產(chǎn)生第一格的位置;//范圍0~4;
int[] local = {randomNum, randomNum+1, randomNum+2};//假設(shè)目標(biāo)的位置集合;
dot.setLocationCells(local);
boolean isAlive = true;//創(chuàng)建出記錄游戲是否繼續(xù)進(jìn)行的boolean變量;
while (isAlive == true) {
String userGuess = h.getUserInput("enter a number");//假設(shè)用戶命令攻擊的位置;
String result = dot.checkYourself(userGuess);//檢查是否擊中;
numOfGuess++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + numOfGuess + " guesses");
}
}
}
}
這個(gè)代碼做出來(lái)的簡(jiǎn)單游戲?qū)ι洗蔚倪M(jìn)行了改進(jìn)。
這次是利用隨機(jī)數(shù)確定每次目標(biāo)的位置集合,用戶可以通過(guò)鍵盤賦值來(lái)指定攻擊的位置,增加了統(tǒng)計(jì)用戶總共攻擊了多少次的變量。
不過(guò),這個(gè)程序有問(wèn)題:用戶始終輸入同一個(gè)位置,而那個(gè)位置恰好是目標(biāo)的一個(gè)位置,則不符合要求。