如题:利用Java语言实现斗地主游戏
分析:
一共四步:
1.准备牌
2.洗牌
3.发牌
4.看牌
具体代码如下:
package cn.itcast.day13.demo04;
import java.util.ArrayList;
import java.util.Collections;
public class DouDiZhu {
public static void main(String[] args) {
// 1、准备牌
// 定义一个存储54张牌的ArrayList集合,泛型使用String
ArrayListpoker = new ArrayList<>();
// 定义两个数组,一个数组存储花色,一个数组存储序号
String[] colors = {"♠", "♥", "♣", "♦"};
String[] numbers = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
// 先把大王和小王存储到poker集合中
poker.add("大王");
poker.add("小王");
// 循环嵌套遍历两个数组,组装52张牌
for(String number : numbers){
for(String color : colors){
// System.out.print(color + number);
// 把组装好的牌存储到poker集合中
poker.add(color + number);
}
}
// System.out.print(poker);
/*
2、洗牌
使用集合的工具类Collections中的方法
static void shuffle(List> list) 使用默认随机源对指定列表进行置换
*/
Collections.shuffle(poker);
// System.out.println(poker);
/*
3、发牌
*/
// 定义4个集合,存储玩家的牌和底牌
ArrayListp1 = new ArrayList<>();
ArrayListp2 = new ArrayList<>();
ArrayListp3 = new ArrayList<>();
ArrayListdipai = new ArrayList<>();
/*
遍历poker集合,获取每一张牌
使用poker集合的索引%3给3个玩家轮流发牌
剩余3张给底牌
注意:得先判断底牌(i >= 51),否则就没底牌了
*/
for (int i = 0; i < poker.size(); i++) {
// 获取每一张牌
String p = poker.get(i);
// 轮流发牌
if (i >= 51){
// 给底牌
dipai.add(p);
}else if(i % 3 == 0){
// 玩家1的牌
p1.add(p);
}else if(i % 3 == 1){
// 玩家2的牌
p2.add(p);
}else if(i % 3 == 2){
// 玩家3的牌
p3.add(p);
}
}
// 4、看牌
System.out.println("张三" + p1);
System.out.println("李四" + p2);
System.out.println("王五" + p3);
System.out.println("底牌" + dipai);
}
}
实现结果如下:
人生若只如初见,何事秋风悲画扇。
等闲变却故人心,却道故人心易变。
-----------纳兰性德
小白寄语:学如逆水行舟,不进则退。