模拟斗地主发牌
具体步骤
买牌 洗牌 发牌 看牌
注意点
通过循环嵌套造牌 大王为最后一张牌,所以num不需要自增 利用Collections.shuffle()方法洗牌,洗的是牌的编号 先把底牌发出,其他人的牌通过%3的余数发给其他人 创建一个printPoker()方法打印发出来的牌 通过Collections.sort()对每个人的牌进行排序 用StringBuilder装牌,用toString()方法拼接牌
整体代码
import java. util. *;
public class SendPokers {
public static void main ( String[ ] args) {
Map< Integer, String> pokers = new HashMap < > ( ) ;
List< Integer> list = new ArrayList < > ( ) ;
String[ ] colors = { "♠" , "♥" , "♣" , "♦" } ;
String[ ] numbers = { "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" , "J" , "Q" , "K" , "A" , "2" } ;
int num = 0 ;
for ( String number : numbers) {
for ( String color : colors) {
String poker = color + number;
pokers. put ( num, poker) ;
list. add ( num) ;
num++ ;
}
}
pokers. put ( num, "小王" ) ;
list. add ( num++ ) ;
pokers. put ( num, "大王" ) ;
list. add ( num) ;
Collections. shuffle ( list) ;
List< Integer> JustinBieber = new ArrayList < > ( ) ;
List< Integer> TimDuncan = new ArrayList < > ( ) ;
List< Integer> Mashiwei = new ArrayList < > ( ) ;
List< Integer> dipai = new ArrayList < > ( ) ;
for ( int i = 0 ; i < list. size ( ) ; i++ ) {
Integer pokerNum = list. get ( i) ;
if ( i >= list. size ( ) - 3 ) {
dipai. add ( pokerNum) ;
} else if ( i % 3 == 0 ) {
JustinBieber. add ( pokerNum) ;
} else if ( i % 3 == 1 ) {
TimDuncan. add ( pokerNum) ;
} else if ( i % 3 == 2 ) {
Mashiwei. add ( pokerNum) ;
}
}
System. out. println ( "-----------------" ) ;
System. out. println ( "比伯:" + printPoker ( JustinBieber, pokers) ) ;
System. out. println ( "Tim:" + printPoker ( TimDuncan, pokers) ) ;
System. out. println ( "马思维:" + printPoker ( Mashiwei, pokers) ) ;
System. out. println ( "底牌:" + printPoker ( dipai, pokers) ) ;
}
public static String printPoker ( List< Integer> nums, Map< Integer, String> pokers) {
Collections. sort ( nums) ;
StringBuilder sb = new StringBuilder ( ) ;
for ( Integer num : nums) {
String poker = pokers. get ( num) ;
sb. append ( poker + " " ) ;
}
String str = sb. toString ( ) ;
return str. trim ( ) ;
}
}
运行结果