目录
代码gitee链接 20220711/src · 雷晓恒/Java - 码云 - 开源中国 (gitee.com)
1. 准备一张牌
一张扑克牌里面有点数和花色,
-
class
Card {
-
public
int rank;
//点数
-
public String suit;
//花色
-
-
public
Card
(int rank, String suit) {
-
this.rank = rank;
-
this.suit = suit;
-
}
-
-
@Override
-
public String
toString
() {
-
return suit+
" "+rank;
-
}
-
}
2. 拿一副牌出来
先搞一个数组存放牌的花色
public static final String [] suits = {"♥", "♠", "♣", "♦"};
再循环一副牌出来
-
public List<Card>
buyDeskCard
() {
-
List<Card> cards =
new
ArrayList<>();
-
for (
int
i
=
1; i <=
13; i++) {
-
for (
int
j
=
0; j <
4; j++) {
-
Card
card
=
new
Card(i,suits[j]);
-
cards.add(card);
-
}
-
}
-
return cards;
-
}
试着打印看一下
-
public
static
void
main
(String[] args) {
-
CardDemo
cardDemo
=
new
CardDemo();
-
List<Card> ret = cardDemo.buyDeskCard();
-
System.out.println(ret);
-
}
3.洗牌(打乱牌的顺序)
循环 让 i 存这个牌的数组从后到前开始循环,让 i 从 0 到 i-1 的某一个数组下标的牌交换,交换完成后i-- ,一直循环完成后,洗牌也就完成了、
洗牌
-
public
void
shuffle
(List<Card> cards) {
-
-
for (
int
i
= cards.size()-
1; i >
0; i--) {
-
//产生随机数
-
Random
random
=
new
Random();
-
int
index
= random.nextInt(i);
-
//交换
-
swap(cards,index,i);
-
}
-
}
交换
-
private
void
swap
(List<Card> cards, int i, int j) {
-
Card
tmp
= cards.get(i);
-
cards.set(i,cards.get(j));
-
cards.set(j,tmp);
-
}
洗牌的方法写好了,我们试着调用一下
-
public
static
void
main
(String[] args) {
-
CardDemo
cardDemo
=
new
CardDemo();
-
List<Card> ret = cardDemo.buyDeskCard();
-
cardDemo.shuffle(ret);
-
System.out.println(ret);
-
}
4.开始发牌
如果是三个人每个人拿五张牌,这样发牌的话
发牌也就是将洗好的牌从数组中删除
而且发牌也要考虑,这张牌发给了谁,要能对应上
-
public List<List<Card>>
test
(List<Card> cards) {
-
//new三个人出来
-
List<Card> hand1 =
new
ArrayList<>();
-
List<Card> hand2 =
new
ArrayList<>();
-
List<Card> hand3 =
new
ArrayList<>();
-
-
List<List<Card>> hands =
new
ArrayList<>();
-
hands.add(hand1);
-
hands.add(hand2);
-
hands.add(hand3);
-
//轮流拿五张牌
-
for (
int
i
=
0; i <
5; i++) {
-
for (
int
j
=
0; j <
3; j++) {
-
Card
card
= cards.remove(
0);
-
hands.get(j).add(card);
-
}
-
}
-
return hands;
-
}
写好发牌的方法,试着调用一下
-
public
static
void
main
(String[] args) {
-
CardDemo
cardDemo
=
new
CardDemo();
-
List<Card> ret = cardDemo.buyDeskCard();
-
System.out.println(ret);
-
System.out.println(
"洗牌:");
-
cardDemo.shuffle(ret);
-
System.out.println(ret);
-
System.out.println(
"发牌:");
-
List<List<Card>> ret2 = cardDemo.test(ret);
-
for (
int
i
=
0; i < ret2.size(); i++) {
-
System.out.println(
"第"+i+
"个人的牌:"+ ret2.get(i));
-
}
-
System.out.println(
"剩余的牌:");
-
System.out.println(ret);
-
}
转载:https://blog.csdn.net/m0_58761900/article/details/125720830
查看评论