洗牌
发牌前先洗牌,洗牌的要求:均匀、随机、不重复。我怎么做呢?怎么去写出满足此要求的测试?看来我只能写了一个简单的测试。
在TestPlayCard类中增加的测试代码:
public void testShuffle(){
PlayCard playCard=new PlayCard();
List<Card> cardList1=playCard.ready(1,true);
playCard.shuffle(cardList1);
assertNotSame("1","1",cardList1.get(0).toString());
List<Card> cardList2=playCard.ready(2,false);
playCard.shuffle(cardList2);
assertNotSame("2","1",cardList2.get(0).toString());
assertEquals("3",false,cardList2.get(10).toString().equals(cardList1.get(10).toString()));
}
在PlayCard类中增加洗牌函数shuffle():
public void shuffle(List<Card> cardList) {
if(cardList==null||cardList.size()<2){
return;
}
List<Card> list=new ArrayList<Card>(cardList);
cardList.clear();
int count=list.size();
Random random=new Random();
for(int i=count;i>0;i--){
int randomInt=random.nextInt();
int absInt=Math.abs(randomInt);
int modulus=absInt%i;
cardList.add(list.remove(modulus));
}
}
运行测试通过,洗牌也暂到此。
要得到锄大地玩法洗好的牌,就如此如此:
PlayCard playCard=new PlayCard();
List<Card> cardList=playCard.ready(1,false);
playCard.shuffle(cardList);