Re: [問題] 判別撲克牌問題

看板java作者 (Alien)時間17年前 (2009/01/02 12:37), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/3 (看更多)
※ 引述《ogamenewbie (._.)》之銘言: : ※ 引述《infinity7519 (富貴險中求)》之銘言: : : public class Card { : : private String face; : : private String suit; : : public Card( String cardFace, String cardSuit ){ : : face = cardFace; : : suit = cardSuit; : : } : : public String toString(){ : : return face + " of " + suit; : : } : : } : : 請問板上前輩 要如何增加一個功能 : : 讓它能夠判別所發的牌是否有葫蘆或twopair等等 : : 一次發五張牌 : 先作 getter 讓你可以取得 face 跟 suit, : 最好是取得一個適合比較的數值而非 string 本身 : 然後另外寫一個程式去 random 產生五張 Card : 再根據那個 getter 去比較五張卡的情況 : 可以傻傻的統計 cardFace 每種有幾張, cardSuit 每種有幾張. : 再根據那兩個陣列依照優先順序比對牌組的組合下來. : 例如說先看看有沒有哪個 cardFace 有 5 個的, 且 cardSuit 有依序 : 然後再檢查 cardSuit 裡面哪個有 4 個的, : 然後再 blahblah... 如果是我寫的話, 我會這樣寫 (半 psuedo code): class Card { Suit suit; int number; // ctor, getter etc } class Deck { // 一副牌 // 內容自己想 public void shuffle(); public Card deal(); } class HandOfCards { // 手牌 List<Card> cards; //ctor, getter etc public void add(Card card); public void sort(Comparator<Card> comparator); } interface CardPattern { boolean match(HandOfCards hand); } class FlushPattern { // 同花順 boolean match(HandOfCards hand) { hand.sort(new BySuitComparator()); // 適當的 comparator // 令手牌先用花再用點數 sort // sort 好後再檢查就很簡單了吧? } } class FullHousePattern { boolean match(HandOfCards hand) { hand.sort(new ByNumberComparator()); // 用點數 sort 好, 再檢查 full house 應該也簡單得多了吧? } } main() { Deck deck = new Deck(); Hand = new Hand(); CardPatterns supportedPatterns = { new FlushPattern(), new FullHousePattern(), new StraightPattern(), new FourOfAKindPattern() } for (int i = 0; i < 4; i++) { // 發五張牌到手牌 hand.add(deck.deal()); } for (CardPatterns pattern: supportedPatterns) { if (pattern.match(hand)) { System.out.println("Match Pattern! " + pattern.getClass().getName()); break; } } } 把 Card (個別的牌), Deck (副牌), Hand (手牌) 都以物件代表, 加上 CardPattern 來代表不同的牌面, 這樣以後要新增 牌面 (比如三條, two pair 等), 就新增新的 card pattern 就好了, 這樣的寫法, 以後也比較好 reuse. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 202.155.236.82
文章代碼(AID): #19NPeVPe (java)
文章代碼(AID): #19NPeVPe (java)