java 52张 扑克牌 问题
给了card 类(一张拍的花色和点数). 在此基础上做一个DECK 和CARDDRIVER.CARDDRIVER 里有六个项目 (发牌,显示当前还剩几张,在剩下的牌里拿,输入一个牌的花色和点数(判断是否在剩余牌中,若在拿出,不在,显示拿拍者名字),剩余多少张,退出)
给出JAVA程序
答案:识别类:
一张牌:public class Card{};
一副牌:public class Poker{};
带main方法的类用于实现洗牌和切牌:public class Shuffle{};
识别属性:
class Card:
一张牌应该具有花色和点数这两个属性:
private color; //花色
private value; //点数
class Poker:
一副牌有54张牌,四种花色,每种花色都有2~A的点数:
static Card[] cards=new Card[54];// 每副扑克都有54张牌;
static String[] colors={"红桃","黑桃","方块","梅花"}; //每副牌都有四种花色;
static String values[]={"2","3","4","5","6","7","8","9","10","J","Q","K","A"};//每个花
色的点数
定义类:
public class Card{
String color;
String value;
//定义一个构造函数用于初始化点数2~A的牌
public Card(String color,String value){
this.color = color;
this.value = value;
}
//定义一个构造函数用于初始化大王和小王
public Card(String value){
this.color=""; //如果不给color赋值的话,洗牌和切牌后的大小王前面会显示“null”
this.value = value;
}
// 取一张牌的花色
public String getcolor() {
return color;
}
// 取一张牌的值
public String getvalue() {
return value;
}
}
public class Poker{
static Card[] cards=new Card[54];
static String[] colors={"红桃","黑桃","方块","梅花"};
static String values[]={"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
//构造方法Poker()用于初始化这副扑克
public Poker() {
for (int i = 0; i < colors.length; i++) {
for (int j = 0; j < values.length; j++) {
cards[i * 13 + j] = new Card(colors[i], values[j]);
}
}
cards[52] = new Card("小王");
cards[53] = new Card("大王");
}
//方法getCard()用于获取一张牌的花色和点数
public Card[] getCard() {
return Poker.cards;
}
//方法Show()用于显示一副新的扑克
public void Show() {
……………………
}
public class Shuffle {
static Poker poker = new Poker();
static Card[] cards = new Card[54];
//方法random用于返回一个不重复的数组
public static int[] random(int length) {
int[] a = new int[length];
for (int i = 0; i < length; i++) {
a[i] = (int) (Math.random() * length);//产生一个0到length的随机数
for (int j = 0; j < i; j++) {
if (a[j] == a[i]) {//比较是否相等,如果相等则重新产生
i--;
break;
}
}
}
return a;
}
//方法xipai()用于将所得的随机数组的值赋值给牌的下标
public static void xipai() {
int[] b = new int[54];
b = random(54);//调用random方法产生一个长度为54的不重复的随机数组
cards = poker.getCard();
Card temp = null;
for(int i = 0; i < b.length; i++){ //开始遍历数组实现重新排列
int k = b[i];
temp = cards[k];
cards[i] = cards[k];
cards[k] = temp;}
//输出洗牌后的扑克
……………………
……………………
}
//方法qiepai()实现扑克的切牌操作
public static void qiepai(int length) {
int number = (int) (Math.random() * length);//产生一个随机数
System.out.println("随机数为:" + number);//显示随机数是多少
Card[] temp = new Card[length];
int start = number;//设置切牌后的起点位置
for (int i = 0; i < length - number; i++) {
temp[i] = cards[start++];//将切点后面的牌暂时放入temp数组中
}
for (int j = 0; j < number; j++) {
temp[length - number + j] = cards[j];//将切点前面的牌加入temp数组中
}
for (int k = 0; k < length; k++) {
cards[k] = temp[k];}
//输出切牌后的扑克
……………………
……………………
}
//main方法
public static void main(String[] args) {
Poker newpoker = new Poker();
newpoker.Show();//调用Show()方法显示一副新扑克
xipai();//调用xipai()方法显示洗牌过后的扑克
qiepai(54);//调用qiepai()方法显示切牌以后的扑克
}
}
参考资料: http://greenchen84.spaces.live.com/blog/cns!7aa735406579b132!111.entry