Java斗地主部分功能实现:创建牌、发牌并按照牌id对其排序

Java斗地主部分功能实现

本文来自于一个斗地主程序编写的小练习,斗地主中,需要将牌打乱后将牌发给玩家,再按照从大到小的顺序发给各个玩家。考虑到卡牌的花色的数字并不能代表其在游戏规则中的大小,因此引入一个名为id的成员变量,用于标示牌的大小。

思路

  1. 创建一副牌:共54张,包括花色和数字;
  2. 打乱牌:Collections类中的shuffle方法;
  3. 发牌:count%3;
  4. 排序:Compare类与Collections.sort方法

代码

首先创建一个Card类用于生成Card对象

//编写一个Card类
public class Card implements Comparable<Card> {//实现一个Comparable类
	private String card;
	private int id;
	static private int count=0;
	
	public String getCard() {
		return card;
	}
	public void setCard(String card) {
		this.card = card;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	public Card() {
		super();
		count++;
	}
	public Card(String card) {
		super();
		count++;
		this.card = card;
		this.id = count;
	}
	@Override//重写compareTo方法
	public int compareTo(Card card) {
		return this.id-card.id;
	}
}

主程序

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class LandLordSort{

	public static void main(String[] args) {
		//创建54张牌
		Collection<Card> cardList=new ArrayList<>();
		Card cardBig=new Card("大王");
		cardList.add(cardBig);
		Card cardSmall=new Card("小王");
		cardList.add(cardSmall);	
		Collection<String> huase=new ArrayList<>();
		String[] hua= {"♥","♠","♦","♣"};
		String[] shu= {"2","A","K","Q","J","10","9","8","7","6","5","4","3"};
		for(String i:shu) {
			for(String j:hua) {
				cardList.add(new Card(i+j));
			}
		}
		printCard(cardList);

		//洗牌
		Collections.shuffle((List<?>) cardList);
		printCard(cardList);

		//发牌
		Collection<Card> player1=new ArrayList<>();
		Collection<Card> player2=new ArrayList<>();
		Collection<Card> player3=new ArrayList<>();
		Collection<Card> last=new ArrayList<>();
		int count=0;
		for (Card i:cardList) {
			if (count%3==0&&count<51) {
				player1.add(i);
			}else if (count%3==1&&count<51) {
				player2.add(i);
			}else if (count%3==2&&count<51) {
				player3.add(i);
			}else {
				last.add(i);
			}
			count++;
		}
		//排序并输出
		Collections.sort((List<Card>) player1);
		printCard(player1);
		Collections.sort((List<Card>) player2);
		printCard(player2);
		Collections.sort((List<Card>) player3);
		printCard(player3);
		printCard(last);
	}
	
	//printCard方法,用于打印输出Collection<Card>
	public static void printCard(Collection<Card> coll) {
		for(Card i:coll) {
			System.out.print(i.getCard()+",");
		}
		System.out.println("");
	}
}

最后输出结果为:

小王,A♦,K♠,J♠,J♦,J♣,10,10,9,9,8,8,7,5,4,4,3,
大王,2,2,K♦,Q♥,Q♠,10,8,8,7,6,6,6,5,5,5,3,
2,2,A♥,A♠,A♣,K♥,K♣,Q♣,J♥,9,9,7,7,4,4,3,3,
6,Q♦,10,
发布了2 篇原创文章 · 获赞 40 · 访问量 3164
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览