1. 程式人生 > >我也來開發2048之方塊設計

我也來開發2048之方塊設計

這次我們的任務是實現遊戲面板上的一個個小方塊,我們的主面板是一個GridLayout,我們把小方塊一個個加到GridLayout中,就形成了我們現在的這個遊戲面板。

小方塊還是比較簡單的,關鍵是,如何做才能最有效率呢?這是我們一直考慮的,也算是職業強迫症吧,我們的小方塊上其實就是顯示一個數字,所以,我們可以用一個TextView或者ImageView,這個隨意了,看以後的打算,是否需要自定義圖片呀等等,我們暫時就用一個TextView吧,簡單。

父佈局選擇什麼呢?其實因為我們就一個子View,所以什麼佈局都一樣的啦,但是,還是為了效率考慮,首選FrameLayout,這個是幾大佈局中最簡單,效率最高的了。

ok,我們還要為這個小方塊實現一些方法:

1、設定顯示的數字

2、根據數字設定背景顏色

3、一系列的get、set方法,這個可以在後面程式設計的時候再做

package com.xys.game2048.bean;

import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

public class GameItem extends FrameLayout {

    // Item顯示數字
    private int cardShowNum;
    // Item顯示顏色
    private int colorShow;
    // 數字Title
    private TextView tvNum;
    // 數字Title LayoutParams
    private LayoutParams params;

    public GameItem(Context context, int cardShowNum) {
	super(context);
	this.cardShowNum = cardShowNum;
	// 初始化Item
	initCardItem();
    }

    /**
     * 初始化Item
     * 
     * @param context
     * @param cardShowNum
     */
    private void initCardItem() {
	// 設定背景色
	setBackgroundColor(Color.GRAY);
	tvNum = new TextView(getContext());
	setNum(cardShowNum);
	tvNum.setTextSize(30);
	tvNum.setGravity(Gravity.CENTER);
	params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
	params.setMargins(5, 5, 5, 5);
	addView(tvNum, params);
    }

    public View getItemView() {
	return tvNum;
    }

    public int getNum() {
	return cardShowNum;
    }

    public void setNum(int num) {
	this.cardShowNum = num;
	if (num == 0) {
	    tvNum.setText("");
	} else {
	    tvNum.setText("" + num);
	}
	// 設定背景顏色
	switch (num) {
	case 0:
	    tvNum.setBackgroundColor(0x00000000);
	    break;
	case 2:
	    tvNum.setBackgroundColor(0xffeee4da);
	    break;
	case 4:
	    tvNum.setBackgroundColor(0xffede0c8);
	    break;
	case 8:
	    tvNum.setBackgroundColor(0xfff2b179);
	    break;
	case 16:
	    tvNum.setBackgroundColor(0xfff59563);
	    break;
	case 32:
	    tvNum.setBackgroundColor(0xfff67c5f);
	    break;
	case 64:
	    tvNum.setBackgroundColor(0xfff65e3b);
	    break;
	case 128:
	    tvNum.setBackgroundColor(0xffedcf72);
	    break;
	case 256:
	    tvNum.setBackgroundColor(0xffedcc61);
	    break;
	case 512:
	    tvNum.setBackgroundColor(0xffedc850);
	    break;
	case 1024:
	    tvNum.setBackgroundColor(0xffedc53f);
	    break;
	case 2048:
	    tvNum.setBackgroundColor(0xffedc22e);
	    break;
	default:
	    tvNum.setBackgroundColor(0xff3c3a32);
	    break;
	}
    }
}

以上,背景設定顏色還是自定義圖片,大家都可以自己修改啦

PS 需要原始碼的請留意,完善後會發給大家