1
package com.web;
2
3
public class Card
{
4
5
private String face; // A, K, Q, J, 10,
2
6
private String suit; // Spade, Heart, Club, Diamond
7
8
public Card()
{
9
10
}
11
12
//定义一个构造函数用于初始化点数2~A的牌
13
public Card(String suit, String face)
{
14
this.face = face;
15
this.suit = suit;
16
}
17
18
//定义一个构造函数用于初始化大王和小王
19
public Card(String suit)
{
20
this.face = ""; //如果不给face赋值的话,洗牌和切牌后的大小王前面会显示“null”
21
this.suit = suit;
22
}
23
24
protected String getFace()
{
25
return face;
26
}
27
28
protected String getSuit()
{
29
return suit;
30
}
31
32
public String toString()
{
33
return suit + " " + face;
34
}
35
36
public static void shuffle(Card[] deck, int startIndex, int size, int splitIndex)
{
37
if (splitIndex * 2 > size)
{
38
Card.swap(deck, startIndex, splitIndex, size - splitIndex);
39
shuffle(deck, size - splitIndex, splitIndex, size - splitIndex);
40
} else if (splitIndex * 2 < size)
{
41
Card.swap(deck, startIndex, size - splitIndex, splitIndex);
42
shuffle(deck, startIndex, size - splitIndex, splitIndex);
43
} else
{
44
Card.swap(deck, startIndex, splitIndex, splitIndex);
45
}
46
47
}
48
49
public static void swap(Card[] deck, int srcIndex, int dstIndex, int size)
{
50
String face = "";
51
String suit = "";
52
for (int i = 0; i < size; i++)
{
53
face = deck[srcIndex + i].face;
54
suit = deck[srcIndex + i].suit;
55
deck[srcIndex + i].face = deck[dstIndex + i].face;
56
deck[srcIndex + i].suit = deck[dstIndex + i].suit;
57
deck[dstIndex + i].face = face;
58
deck[dstIndex + i].suit = suit;
59
}
60
}
61
62
public static void main(String[] args)
{
63
Card[] deck = new Card[54];
64
String f[] =
{ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
65
// String s[] = {"Spade","Heart","Club","Diamond"};
66
String s[] =
{ "黑桃", "红桃", "梅花", "方块" };
67
for (int i = 0; i < s.length; i++)
{
68
for (int j = 0; j < f.length; j++)
{
69
deck[i * 13 + j] = new Card(s[i], f[j]);
70
}
71
deck[52] = new Card("小王");
72
deck[53] = new Card("大王");
73
}
74
int rnd = 0;
75
int numOfShuffle = 10;
76
for (int i = 0; i < numOfShuffle; i++)
{
77
rnd = (int) Math.abs(Math.random() * 52);
78
Card.shuffle(deck, 0, deck.length, rnd);
79
}
80
// Test
81
for (int i = 0; i < deck.length; i++)
{
82
System.out.println(deck[i]);
83
}
84
}
85
}
86
posted on 2011-09-01 17:46
kenzhang 阅读(2738)
评论(2) 编辑 收藏