1.要实现的功能:
参考斗地主的游戏规则,完成一个发牌的功能(54张牌,考虑点数,花色;三名玩家,其中地主比其他玩家多3张牌)
随机地主,洗牌,发牌(发牌按照常规方式A-B-C-A-B-C-A...,不允许一次性随机17张给某个玩家),玩家手中牌的展示(要求按点数实现排序)
2.编辑代码的思路与过程:
根据斗地主的规则,要有纸牌和玩家,所以要建立玩家类(Player),扑克牌类(Poke)。玩家类包含的属性应该有:id,姓名(name)、扑克牌(ArrayList<Poke>),是否地主(boss);扑克牌类包含的属性应该有:花色(flower),点数(point),判断大小的索引(score),在测试类中编写方法并实现。
首先建立玩家类(Player),扑克牌类(Poke),在编写方法添加扑克和玩家,接着是随机地主和发牌方法,最后是显示玩家手中的牌。
3.通过代码实现功能:
玩家类和扑克牌类就不显示了,我直接展示测试类的方法:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class PokeGame {
static List<Player> players;
static ArrayList<Poke> list = new ArrayList<>();
static String[] flower = {"方块","梅花","黑桃","红心"};
static String[] point = {"3","4","5","6","7","8","9","10",
"J","Q","K","A", "2"};
static int bossIndex;
static {
// 初始化扑克
for (int i = 0; i < flower.length; i++) {
for (int j = 0; j < point.length; j++) {
// 生成一张扑克对象
Poke p = new Poke(flower[i], point[j], j);
list.add(p);
}
}
// 单独加大小王
list.add(new Poke("小", "王", 13));
list.add(new Poke("大", "王", 14));
System.out.println(list);
// 初始化玩家
players = Arrays.asList(new Player(1, "刘备"), new Player(2, "关羽"), new Player(3, "张飞"));
}
/** 随机地主 */
public void pushBoss() {
Random r = new Random();
int i = r.nextInt(players.size());
// 设置被随机到的玩家为地主
bossIndex = i;
players.get(bossIndex).setBoss(true);
}
/** 发牌 */
public void pushPoke() {
Random r = new Random();
//洗牌
Collections.shuffle(list);
int ind = 0;
for (int i = 0; i < 51; i++) {
int index = r.nextInt(list.size());
if (ind < 3) {
players.get(ind).getPokes().add(list.get(index));
} else {
ind = 0;
players.get(ind).getPokes().add(list.get(index));
}
ind++;
list.remove(index);
}
// 将最后三张牌发给地主
players.get(bossIndex).getPokes().addAll(list);
}
//按牌的大小展示牌
public ArrayList<Poke> show(Player p){
Collections.sort(p.getPokes(),(a,b)->{
return a.getSort() - b.getSort();
});
return p.getPokes();
}
public void start() {
pushBoss();
pushPoke();
for (Player p : players) {
System.out.println(p.getName() + ":" +show(p));
}
}
public static void main(String[] args) {
new PokeGame().start();
}
}