我正在制作卡片游戏“战争”的模拟,我遇到了在两个卡片对象之间找到更大价值卡的问题。例如,如果player1拥有10个心脏且player2拥有9个球杆,则player1应赢得该手牌。但是,由于这些卡包含字符串变量,我不知道如何比较它们以确定哪个卡具有更大的值。我有三个类,一个持有两个字符串数组的卡片类,一个卡片集合,一个卡片集合和一个主类。
import java.util.ArrayList;
import java.util.Collections;
public class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
for(int i = 0; i <=3; i++) {
for(int j = 0 ; j <= 12; j++) {
cards.add(new Card(i,j));
}
}
}
public void shuffle() {
Collections.shuffle(cards);
}
public Card deal() {
if (isEmpty() == true) {
return null;
}
else {
return cards.remove(0);
}
}
public Card playCard() {
return cards.remove(0);
}
public void getCard (Card newCard) {
cards.add(newCard);
}
public void clearDeck() {
cards.removeAll(cards);
}
public boolean isEmpty() {
return cards.isEmpty();
}
public int cardCount() {
return cards.size();
}
public String toString() {
String result = "Cards remaining in deck: " + cards;
return result;
}
}
public class Card
{
private int type, value;
protected String[] cardType = {"Clubs", "Spades", "Diamonds", "Hearts"};
protected String[] cardValue = {"Ace", "King", "Queen", "Jack", "10",
"9", "8", "7", "6", "5", "4", "3", "2"};
public Card() {
}
public Card(int types, int values)
{
type = types;
value = values;
}
public String toString()
{
String resultCard = cardValue[value] + " of " + cardType[type];
return resultCard;
}
}
public class Main
{
public static void main(String[] args)
{
Deck deck = new Deck();
Deck player1 = new Deck();
Deck player2 = new Deck();
Deck pile = new Deck();
pile.clearDeck();
deck.shuffle();
dealCards(deck, player1, player2);
addToPile(player1, player2, pile);
}
public static void dealCards(Deck deck, Deck p1, Deck p2) {
for (int i=0; i <26; i++) {
p1.getCard(deck.deal());
p2.getCard(deck.deal());
}
p1.shuffle();
p2.shuffle();
}
public static void addToPile(Deck p1, Deck p2, Deck deckPile) {
Card p1Card;
Card p2Card;
p1Card = p1.playCard();
p2Card = p2.playCard();
deckPile.getCard(p1Card);
deckPile.getCard(p2Card);
}
}
答案 0 :(得分:0)
您可以在Card
课程中创建一个比较2 Cards
的方法。
由于我不知道这里的游戏规则是一个具有以下规则的例子
1.俱乐部&gt;黑桃&gt;钻石&gt;心
2.最高牌胜利
可能是这样的:
// 1 -> This card is greater
// 0 -> both cards are equal
// -1 -> This card is lesser
public int isGreater(Card cardToCompare) {
// Check the cardType
if (this.type < cardToCompare.type) {
return 1;
}
if (this.type == cardToCompare.type) {
if (this.value < cardToCompare.value) {
return 1;
}
if (this.value == cardToCompare.value) {
return 0;
}
if (this.value > cardToCompare.value) {
return -1;
}
}
if (this.type > cardToCompare.type) {
return -1;
}
}
请注意,value
或type
的较低数字等于数组中较大的卡片。
编辑: 由于卡片类型在这个游戏中无关紧要(所以我被告知),你也可以这样做:
// positive result -> this card is greater
// 0 -> cards are equal
// negative result -> cardToCompare is greater
public int isGreater(Card cardToCompare) {
return cardToCompare.value - this.value;
}