今天要來分享使用RecyclerView設計記憶牌遊戲的過程,延續上一次RecyclerView的部分,首先會產生12張隨機的牌,點擊相同便刪除,不同的便蓋回紙牌。
要產生12張不同的圖片,首先需要產生兩兩相對的數列像是1,1,2,2。
//產生亂數表元素
int reItemSize = 2; //圖片重複數
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= reItemSize; j++) {
randomList.add(String.valueOf(i));
}
}
在完成牌組後,接下來要將該組數列打亂。
//產生隨機亂數表_data
RandomSize = randomList.size();
for (int i = 1; i <= RandomSize; i++) {
r2 = random.nextInt(randomList.size());
reList.add(String.valueOf(randomList.get(r2)));
randomList.remove(r2);
}
這樣子便完成了生成牌組的前置動作,之後在顯示圖示時會依據這張表來判斷要顯示的圖片是什麼,接下來還需要產生一組與隨機亂數表相同數量的數列來記憶點擊狀態。
//產生選擇狀態表_selectList
int[] selectRegister = new int[RandomSize];
for (int i = 0; i <= RandomSize - 1; i++) {
selectRegister[i] = 1;
}
生成完成了以後便能夠在recyclerView的建構子中傳入需要的數列,在adapter中的data、selectRegister便是前面產生的兩組數列。
//設置recyclerView
RecyclerView recyclerView = findViewById(R.id.card_list);
int numberOfColumns = 3;
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
adapter = new MyRecyclerViewAdapter(this, data, selectRegister);
adapter.setClickListener(this);
recyclerView.setItemViewCacheSize(6 * reItemSize - 15);
recyclerView.setAdapter(adapter);
總結code
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener{
private MyRecyclerViewAdapter adapter;
private TextView passTextView;
private ArrayList<String> randomList;
private ArrayList<String> reList;
private ArrayList<String> randomImgList;
private int r1;
private int r2;
private int RandomSize;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
randomList = new ArrayList<>();
reList = new ArrayList<>();
randomImgList = new ArrayList<>();
Random random = new Random();
r1 = random.nextInt(8 - 2) + 2;//1~7
//產生亂數表元素
int reItemSize = 2; //圖片重複數
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= reItemSize; j++) {
randomList.add(String.valueOf(i));
}
}
//產生隨機亂數表_data
RandomSize = randomList.size();
for (int i = 1; i <= RandomSize; i++) {
r2 = random.nextInt(randomList.size());
reList.add(String.valueOf(randomList.get(r2)));
randomList.remove(r2);
}
Object list[] = reList.toArray();
String[] data = Arrays.copyOf(list, list.length, String[].class);
//產生選擇狀態表_selectList
int[] selectRegister = new int[RandomSize];
for (int i = 0; i <= RandomSize - 1; i++) {
selectRegister[i] = 1;
}
//設置recyclerView
RecyclerView recyclerView = findViewById(R.id.card_list);
int numberOfColumns = 3;
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
adapter = new MyRecyclerViewAdapter(this, data, selectRegister);
adapter.setClickListener(this);
recyclerView.setItemViewCacheSize(6 * reItemSize - 15);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position, int score) {
}
}
明天會進入到recyclerView的部分,來處理顯示圖示與動畫撥放的部分。