java洗牌2

import java.util.Collection;
import java.util.Collections;

public class Card {

	private String face; // A, K, Q, J, 10, ... 2
	private String suit; // Spade, Heart, Club, Diamond

	
	public Card(String suit, String face) {
		this.face = face;
		this.suit = suit;
	}

	protected String getFace() {
		return face;
	}

	protected String getSuit() {
		return suit;
	}

	public String toString() {
		return suit + " " + face;
	}

	public static void shuffle(Card[] deck, int startIndex, int size,
			int splitIndex) {
		if (splitIndex * 2 > size) {
			Card.swap(deck, startIndex, splitIndex, size - splitIndex);
			shuffle(deck, size - splitIndex, splitIndex, size - splitIndex);
		} else if (splitIndex * 2 < size) {
			Card.swap(deck, startIndex, size - splitIndex, splitIndex);
			shuffle(deck, startIndex, size - splitIndex, splitIndex);
		} else {
			Card.swap(deck, startIndex, splitIndex, splitIndex);
		}

	}

	public static void swap(Card[] deck, int srcIndex, int dstIndex, int size) {
		String face = "";
		String suit = "";
		for (int i = 0; i < size; i++) {
			face = deck[srcIndex + i].face;
			suit = deck[srcIndex + i].suit;
			deck[srcIndex + i].face = deck[dstIndex + i].face;
			deck[srcIndex + i].suit = deck[dstIndex + i].suit;
			deck[dstIndex + i].face = face;
			deck[dstIndex + i].suit = suit;
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Card[] deck = new Card[52];
		String f[] = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J",
				"Q", "K" };
		String s[] = { "Spade", "Heart", "Club", "Diamond" };
		for (int i = 0; i < s.length; i++) {
			for (int j = 0; j < f.length; j++) {
				deck[i * 13 + j] = new Card(s[i], f[j]);
			}
		}
		int rnd = 0;
		int numOfShuffle = 10;
		for (int i = 0; i < numOfShuffle; i++) {
			rnd = (int) Math.abs(Math.random() * 52);
			Card.shuffle(deck, 0, deck.length, rnd);
		}
		// Test
		for (int i = 0; i < deck.length; i++) {
			System.out.println(deck[i]);
		}
		
	}

}

阅读更多
文章标签: java string import class
个人分类: 数据结构和算法
想对作者说点什么? 我来说一句

<em>java洗牌</em>游戏

2018年05月08日 0B 下载

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

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭