在本篇文章里小编给各位分享的是关于Java实现斗地主最简代码实例,有兴趣的朋友们可以参考下。
案例说明:使用Java实现简单的斗地主洗牌发牌的操作;
具体规则:
共有54张牌,顺序打乱;
三个玩家参与游戏,三人交替摸牌,每人17张牌,最后留三张为底牌(地主牌)。
具体代码实现步骤:
扑克牌准备操作
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class PokerGame { public static void main(String[] args) { //定义扑克牌的花色以及数字的数组 String[] flower = {"♥️","♠️","♣️","♦️"}; String[] numbers = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; //创建牌组集合 List poker = new ArrayList(); //组合扑克牌样式 //拿出每一个花色,然后跟每一个数字进行结合,储存在牌组中 for (int i = 0; i 50) { dizhupai.add(poker.get(k)); } else if (k % 3 == 0) { player1.add(poker.get(k)); } else if (k % 3 == 1) { player2.add(poker.get(k)); } else if (k % 3 == 2) { player3.add(poker.get(k)); } } //最终看牌操作 System.out.println("玩家一的牌"+player1); System.out.println("玩家二的牌"+player2); System.out.println("玩家三的牌"+player3); System.out.println("地主牌"+dizhupai); } }
结果展示
玩家一的牌:[♥️9, ♠️A, ♠️5, ♥️A, ♥️2, ♥️10, ♠️7, ♣️J, ♥️3, ♠️2, ♣️5, ♦️2, ♠️6, ♥️7, ♦️K, ♣️9, 大王]
玩家二的牌:[♦️9, ♠️4, ♣️4, ♣️10, ♥️J, ♦️4, ♥️8, ♥️5, ♦️A, ♣️A, ♦️7, ♦️3, ♦️Q, ♣️K, ♥️6, ♣️3, ♠️Q]
玩家三的牌:[♣️Q, ♣️2, ♣️8, ♣️7, ♥️Q, ♦️10, ♠️8, ♣️6, ♥️4, ♠️10, 小王, ♥️K, ♠️3, ♦️8, ♦️6, ♠️K, ♠️J]
地主牌:[♠️9, ♦️5, ♦️J]
实例补充:
package itcast.demo6; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; public class DouDiZhu { public static void main(String[] args) { //1、组合牌 //创建Map集合,键:编号 值:牌 HashMap pooker = new HashMap(); //创建List集合,存储编号 ArrayList pookerNumber = new ArrayList(); //定义13个点数的数组 String[] numbers = {"2","A","K","Q","J","10","9","8","7","6","5","4","3"}; //定义4个花色组合 String[] colors = {"♠","♣","♥","♦"}; //定义一个整数变量,作为Map的键 int index = 2; //遍历数组,用花色+点数的组合,存储到Map集合中 for(String number : numbers) { for(String color : colors) { pooker.put(index, color + number); pookerNumber.add(index); index++; } } //System.out.println(pooker); //System.out.println(pookerNumber); //单独存储大王和小王 pooker.put(0, "大王"); pookerNumber.add(0); pooker.put(1, "小王"); pookerNumber.add(1); //洗牌,将牌的编号打乱 Collections.shuffle(pookerNumber); //System.out.println(pookerNumber); //发牌,将牌编号,发给3个玩家集合+1个底牌集合 ArrayList player1 = new ArrayList(); ArrayList player2 = new ArrayList(); ArrayList player3 = new ArrayList(); ArrayList buttom = new ArrayList(); //发牌,采用的是集合的索引%3 for(int i = 0; i player,HashMap pooker) { //遍历ArrayList集合,获取元素,作为键,到集合Map中找值 System.out.print(name+" "); for(Integer key : player) { String value = pooker.get(key); System.out.print(value+" "); } System.out.println(); } }
包身工 大王 ♣2 ♥2 ♦2 ♦A ♦K ♣J ♥10 ♠9 ♣9 ♥9 ♦9 ♣5 ♦5 ♦4 ♠3 ♦3
清洁工 小王 ♠K ♥K ♠Q ♣Q ♦Q ♦J ♠10 ♦10 ♥8 ♠7 ♥7 ♦7 ♥5 ♠4 ♣3 ♥3
洗碗工 ♠2 ♥A ♣K ♥Q ♠J ♥J ♣10 ♠8 ♦8 ♣7 ♠6 ♣6 ♥6 ♦6 ♠5 ♣4 ♥4
底牌 ♠A ♣A ♣8