編輯:關於 Android 程式設計
邊學 Android 邊做個小專案,是熟悉控制項與事件模型最有效率的方式。這次挑選大家最熟悉的經典遊戲——掃雷,因為它剛好涵蓋了幾個很值得練習的技術點:動態生成控制項、二維陣列建模、遞迴展開空白區域,以及 OnClickListener 與 OnLongClickListener 的搭配使用。
掃雷的資料結構其實非常單純,一個 10×10 的二維陣列就能搞定:
-1 代表地雷0 代表周圍沒有雷的空白格1~8 代表周圍八個方向的地雷數量畫面上則用兩層重疊的布局:底層放 100 個 TextView 顯示真正的內容,上層蓋 100 個 Button 遮住它。點擊時把 Button 設為 INVISIBLE,底下的數字就露出來了——這招雖然樸素,但省去大量重繪的麻煩。
public class MainActivity extends Activity implements OnClickListener, OnLongClickListener {
// 最外層布局
LinearLayout textviews;
LinearLayout buttons;
int[][] map = new int[10][10];
// 用來隱藏所有 Button
List<Button> buttonList = new ArrayList<Button>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textviews = (LinearLayout) findViewById(R.id.textviews);
buttons = (LinearLayout) findViewById(R.id.buttons);
initData();
initView();
}
Set<Integer> random地雷;
private void initData() {
// 10 個地雷,陣列中存 -1;雷的邊上是數字,其他是空白 0
// 100 個數字中隨機取走 10 個當作地雷位置
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
map[i][j] = 0;
}
}
random地雷 = getRandom();
// 丟入 map
for (Integer integer : random地雷) {
int hang = integer / 10;
int lie = integer % 10;
// 所有的地雷用 -1 代替
map[hang][lie] = -1;
}
// 為所有非地雷的格子計算周圍雷數
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (map[i][j] == -1) continue;
int sum = 0;
// 左上角
if (i != 0 && j != 0) {
if (map[i - 1][j - 1] == -1) sum++;
}
// 上面
if (j != 0) {
if (map[i][j - 1] == -1) sum++;
}
// 右上角
if (j != 0 && i != 9) {
if (map[i + 1][j - 1] == -1) sum++;
}
// 左邊
if (i != 0) {
if (map[i - 1][j] == -1) sum++;
}
// 右邊
if (i != 9) {
if (map[i + 1][j] == -1) sum++;
}
// 左下角
if (j != 9 && i != 0) {
if (map[i - 1][j + 1] == -1) sum++;
}
if (j != 9) {
if (map[i][j + 1] == -1) sum++;
}
if (j != 9 && i != 9) {
if (map[i + 1][j + 1] == -1) sum++;
}
map[i][j] = sum;
}
}
// 除錯用:印出棋盤
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
}
private Set<Integer> getRandom() {
// 使用 Set 天然去重
Set<Integer> set = new HashSet<Integer>();
while (set.size() != 10) {
int random = (int) (Math.random() * 100);
set.add(random);
}
return set;
}
// 建立視圖
private void initView() {
int width = getResources().getDisplayMetrics().widthPixels / 10;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width);
for (int i = 0; i < 10; i++) {
// 每一列的布局
LinearLayout tvs = new LinearLayout(this);
tvs.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout btns = new LinearLayout(this);
btns.setOrientation(LinearLayout.HORIZONTAL);
// 加入 100 個按鈕與文字方塊
for (int j = 0; j < 10; j++) {
// 底層的 TextView
TextView tv = new TextView(this);
tv.setBackgroundResource(R.drawable.textview_bg);
tv.setLayoutParams(params);
tv.setGravity(Gravity.CENTER);
if (map[i][j] == -1) tv.setText("*");
else if (map[i][j] != 0) tv.setText(map[i][j] + "");
tvs.addView(tv);
// 上層的 Button
Button btn = new Button(this);
btn.setBackgroundResource(R.drawable.button);
btn.setLayoutParams(params);
btn.setTag(i * 10 + j);
btn.setOnClickListener(this);
btn.setOnLongClickListener(this);
buttonList.add(btn);
btns.addView(btn);
}
textviews.addView(tvs);
buttons.addView(btns);
}
}
@Override
public void onClick(View v) {
int id = (Integer) v.getTag();
int hang = id / 10;
int lie = id % 10;
// 隱藏按鈕,露出底下的資料
v.setVisibility(View.INVISIBLE);
isOver(hang, lie);
// 若點到空白格,開始遞迴展開
if (map[hang][lie] == 0) {
顯示周圍所有的空白(hang, lie);
}
if (isWin()) {
Toast.makeText(this, "遊戲勝利", Toast.LENGTH_SHORT).show();
}
}
// 顯示周圍所有的空白
public void 顯示周圍所有的空白(int i, int j) {
// 先顯示自己
buttonList.get(i * 10 + j).setVisibility(View.INVISIBLE);
// 左上角
if (i != 0 && j != 0) {
if (map[i - 1][j - 1] == 0) {
if (判斷是否需要遞歸(i - 1, j - 1)) 顯示周圍所有的空白(i - 1, j - 1);
} else {
隱藏button(i - 1, j - 1);
}
}
// 上面
if (j != 0) {
if (map[i][j - 1] == 0) {
if (判斷是否需要遞歸(i, j - 1)) 顯示周圍所有的空白(i, j - 1);
} else {
隱藏button(i, j - 1);
}
}
// 右上角
if (j != 0 && i != 9) {
if (map[i + 1][j - 1] == 0) {
if (判斷是否需要遞歸(i + 1, j - 1)) 顯示周圍所有的空白(i + 1, j - 1);
} else {
隱藏button(i + 1, j - 1);
}
}
// 左邊
if (i != 0) {
if (map[i - 1][j] == 0) {
if (判斷是否需要遞歸(i - 1, j)) 顯示周圍所有的空白(i - 1, j);
} else {
隱藏button(i - 1, j);
}
}
// 右邊
if (i != 9) {
if (map[i + 1][j] == 0) {
if (判斷是否需要遞歸(i + 1, j)) 顯示周圍所有的空白(i + 1, j);
} else {
隱藏button(i + 1, j);
}
}
// 左下角
if (j != 9 && i != 0) {
if (map[i - 1][j + 1] == 0) {
if (判斷是否需要遞歸(i - 1, j + 1)) 顯示周圍所有的空白(i - 1, j + 1);
} else {
隱藏button(i - 1, j + 1);
}
}
if (j != 9) {
if (map[i][j + 1] == 0) {
if (判斷是否需要遞歸(i, j + 1)) 顯示周圍所有的空白(i, j + 1);
} else {
隱藏button(i, j + 1);
}
}
if (j != 9 && i != 9) {
if (map[i + 1][j + 1] == 0) {
if (判斷是否需要遞歸(i + 1, j + 1)) 顯示周圍所有的空白(i + 1, j + 1);
} else {
隱藏button(i + 1, j + 1);
}
}
}
private void 隱藏button(int i, int j) {
int 位置 = i * 10 + j;
buttonList.get(位置).setVisibility(View.INVISIBLE);
}
boolean 判斷是否需要遞歸(int hang, int lie) {
// 已經顯示過的就不用再遞歸
int 位置 = hang * 10 + lie;
if (buttonList.get(位置).getVisibility() == View.INVISIBLE) return false;
else return true;
}
private boolean isOver(int hang, int lie) {
if (map[hang][lie] == -1) {
Toast.makeText(this, "GameOver", Toast.LENGTH_SHORT).show();
for (int i = 0; i < buttonList.size(); i++) {
buttonList.get(i).setVisibility(View.INVISIBLE);
}
return true;
}
return false;
}
// 最多 10 個旗子
List<Integer> 旗子 = new ArrayList<Integer>();
@Override
public boolean onLongClick(View v) {
// 插旗子:有旗子就取消,沒旗子就插上
Button btn = (Button) v;
int tag = (Integer) v.getTag();
if (旗子.contains(tag)) {
btn.setText("");
// ArrayList.remove(int) 是按下標刪除,必須轉型成 Integer
旗子.remove((Integer) tag);
} else {
if (旗子.size() != 10) {
旗子.add(tag);
btn.setText("✓ " + 旗子.size());
btn.setTextColor(Color.RED);
} else {
Toast.makeText(this, "沒有旗子了", Toast.LENGTH_SHORT).show();
}
}
// 消耗事件
return true;
}
// 是否勝利:90 格非地雷全部掀開即獲勝
public boolean isWin() {
int sum = 0;
for (int i = 0; i < buttonList.size(); i++) {
if (buttonList.get(i).getVisibility() == View.INVISIBLE) sum++;
}
if (sum == 90) return true;
return false;
}
}
用 FrameLayout 讓兩層 LinearLayout 完全重疊,是這個做法的關鍵:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/textviews"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
<LinearLayout
android:id="@+id/buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</FrameLayout>
</LinearLayout>
這個版本以「能跑、好懂」為優先,所以有幾處實務上會想優化:一是遞迴展開在極端情況下可能觸發堆疊溢位,改用 BFS 佇列會更穩;二是 onLongClick 的旗子數量上限寫死為 10,可改成依地雷總數帶入;三是每次點擊都呼叫 isWin() 遍歷 100 個 Button,資料量大時可改用計數器維護剩餘格數。
以上就是這個小遊戲的完整實作,歡迎動手改一改,加上計時器與難度選擇會更好玩。
Android 自定義控件(二)——onLayout 詳解
先講個笑話:一個乞丐看程序員寫程式,程序員遇到一個怎麼都解決不了的問題,乞丐說「你少打了個分號」,程序員照做,問題果然解決了,於是問:「你怎麼知道?」乞丐笑笑說:「我以前
Android 基礎之使用 Fragment 適配不同螢幕與解析度
最近工作繁忙,一個新專案急著上線,很多功能都得重做,一路埋頭寫程式、除錯。今天因為新程式要用 Fragment 來做,雖說以前也用過 Fragment,卻沒仔細研究,於是
《Android 從入門到精通》第 17 篇:ProgressBar 進度條完全解析
凡是需要「讓使用者等一等」的場景,幾乎都離不開進度條。本文延續《Android 從入門到精通》的系列進度,把 ProgressBar 的類別結構、常用方法與一個可直接跑起
Android 官方文件翻譯:把 Eclipse 專案遷移到 Android Studio
翻譯耗時費神,如果你覺得這份譯文還算通順,歡迎按個「推」;若有錯漏之處,也請不吝指正。 Eclipse 專案遷移 把 Eclipse 專案轉成 Android Stud