炸金花这段代码的形成使用了 get set方法 还有toString方法来来实现了返回花色和数字的表示
-
package 集合类;
-
public class Poker {
-
// TODO Auto-generated method stub
-
private String suit;//花色
-
private int rank;//数字
-
public Poker(String suit, int rank) {//参数为扑克牌的花色和大小的构造方法
-
this.suit = suit;//将参数suit的值赋给suit
-
this.rank = rank;
-
}
-
public String getSuit() {//使用get方法来读取
-
return suit;//返回
-
}
-
public void setSuit(String suit) {//使用set方法重写
-
this.suit = suit;
-
}
-
public int getRank() {//使用get方法来读取
-
return rank;
-
}
-
public void setRank(int rank) {//使用set方法重写
-
this.rank = rank;
-
}
-
@Override
-
public String toString() {//toSring方法重写
-
return "{ "+suit+" "+rank+"}";
-
}
- }
代码图:
然后再是创建一个类使用for循环来 模仿买牌 之前实现类里定义了两个类型 一个int 一个String 两个类型分别是花色和数字 然后再这个类里 使用for循环来牌数字不同大小的数量和花色 然后传入两个参数来模仿洗牌 再是new三个对象使用for循环来模仿三个人一起打牌 再是使用for循环来模仿揭牌 主要代码如下
揭牌 主要代码如下:
运行结果如下:
-
package 集合类;
-
// TODO Auto-generated method stub
-
import java.util.ArrayList;
-
import java.util.List;
-
import java.util.Random;
-
public class Game {
-
private static final String[] suits = {"♥","♣","♦","♠"};//花色
-
public List<Poker> buyPoker(){
-
List<Poker> pokers = new ArrayList<>();//创建集合类对象
-
for (int i = 0; i < 4; i++) {//遍历牌的花色
-
for (int j = 1; j <= 13; j++) {//遍历拍的每张牌的大小的数量
-
Poker poker = new Poker(suits[i], j);//创建对象
-
pokers.add(poker);
-
}
-
}
-
return pokers;//返回
-
}
-
public void shuffle(List<Poker> pokers){
-
for (int i = pokers.size()-1; i > 0; i--) {//交换两个元素的位置 模仿洗牌
-
Random random = new Random();//创建对象
-
int index = random.nextInt(i);//判断是否有下一个
-
swap(pokers,i,index);
-
}
-
}
-
private void swap(List<Poker> pokers, int i, int j){//传入两个参数 然后用于两个元素交换位置 然而达到洗牌的效果
-
Poker tmp = pokers.get(i);
-
pokers.set(i,pokers.get(j));
-
pokers.set(j,tmp);
-
}
-
public List<List<Poker>> game(List<Poker> pokers){
-
List<List<Poker>> hand = new ArrayList<>();
-
List<Poker> hand1 = new ArrayList<>();//创建模仿三个人一起打牌 hand1
-
List<Poker> hand2 = new ArrayList<>();//hand2
-
List<Poker> hand3 = new ArrayList<>();//hand3
-
hand.add(hand1);//添加
-
hand.add(hand2);
-
hand.add(hand3);
-
for (int i = 0; i < 5; i++) {//循环三个人打牌 外循环是每个人摸五张牌 内循环是三个人一起打牌
-
for (int j = 0; j < 3; j++) {
-
Poker removePoker = pokers.remove(0);
-
hand.get(j).add(removePoker);
-
}
-
}
-
return hand;
-
}
-
public static void main(String[] args) {
-
Game game = new Game();
-
List<Poker> pokers = game.buyPoker();
-
System.out.println(pokers);
-
//洗牌
-
game.shuffle(pokers);//洗牌
-
System.out.println("洗牌:");
-
System.out.println(pokers);
-
//揭牌
-
List<List<Poker>> hand = game.game(pokers);//揭牌
-
System.out.println("揭牌:");
-
for (int i = 0; i < hand.size(); i++) {
-
System.out.println("第 "+(i+1)+"个人的牌:"+hand.get(i));
-
}
-
System.out.println("剩下的牌");//然后计算剩余还没有被摸走的牌
-
System.out.println(pokers);
-
}
-
}