模拟游戏斗地主
斗地主 : 准备牌, 洗牌,发牌,看牌
功能分析 : 准备牌 (图片) 字符串替代
定义54个字符串 (否)
牌的规律 : 4个花色和13个点数构成 4 * 13 = 52
一个花色,和13个点数组合 : 外循环是花色,内循环点数,形成了52个字符串
容器,存储52个字符串
功能分析 : 洗牌
本质是将集合中保存的字符串的顺序打乱
Collections类, 静态方法 shuffle(集合) 集合元素随机排列
功能分析 : 发牌
集合的操作 : 存储54个字符串的容器中,取出一个字符串,存储到玩家的集合保存
利用集合元素的索引, %3, 决定发到哪个玩家的集合中
功能分析 : 看牌
遍历集合 : 遍历4个集合
方法抽取 : 定义方法,实现遍历,需要遍历哪个集合传递
package poker;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Poker {
public static void main(String[] args) {
ArrayList<String> arrayPoker = new ArrayList<String>();
String[] colors = {"♠","♣","♥","♦"};
//数组存储点数
String[] number = {"A","2","3","4","5","6","7","8","9","10","j","q","k"};
for (int i = 0; i < colors.length; i++) {
for (int j = 0; j < number.length; j++) {
arrayPoker.add(colors[i]+number[j]);
}
}
//add添加王牌
arrayPoker.add("😀");
arrayPoker.add("👴");
//Collection类,集合元素的随机排列
Collections.shuffle(arrayPoker);
//System.out.println(arrayPoker);
//定义4个集合,存储3个玩家的牌,存储底牌
ArrayList<String> play1 = new ArrayList<String>();
ArrayList<String> play2 = new ArrayList<String>();
ArrayList<String> play3 = new ArrayList<String>();
ArrayList<String> bottom = new ArrayList<String>();
for (int i = 0; i < arrayPoker.size(); i++) {
//先把牌盒中的前三张,放底牌
if(i<3) {
bottom.add(arrayPoker.get(i));
}else if (i%3==0) {
play1.add(arrayPoker.get(i));
}else if(i%3==1){
play2.add(arrayPoker.get(i));
}else if (i%3==2) {
play3.add(arrayPoker.get(i));
}
}
look("周星驰", play1);
look("周润发", play2);
look("刘德华", play3);
look("底牌", bottom);
}
public static void look(String name,ArrayList<String> array) {
System.out.print(name+":");
for (int i = 0; i < array.size(); i++) {
System.out.print(array.get(i)+" ");
}
System.out.println(" ");
}
}