【发布时间】:2018-11-11 13:23:04
【问题描述】:
我正在为 Manille 游戏实现比较方法 (IComparer),我需要相互比较某些卡片(枚举值)。
我想以某种方式排列它们,以便 10 号是最大的牌,而 Ace 是第二大的牌。
还有一个特定的符号总是高于其他牌(例如红心)
问题:
我不知道如何判断 Nummer.Tien 比 B、D、H 大
Ace 也必须是第二高的牌,但算法将他放在第一位。
public class ManilleComparer : IComparer<Kaart>
{
private Kleur symbol; // the symbol that is higher
public ManilleComparer(Kleur symbol)
{
this.symbol = symbol;
}
public int Compare(Kaart x, Kaart y)
{
int compareTo = x.Kleur.CompareTo(y.Kleur); //check symbols against each other
if (compareTo == 0) // if value is 0 they have the same symbol
{
compareTo = x.Nummer.CompareTo(y.Nummer); // order them
return compareTo;
}
return x.Nummer.CompareTo(y.Nummer); // else compare values
}
}
public enum Nummer { Aas, Twee, Drie, Vier, Vijf, Zes, Zeven, Acht, Negen, Tien, Boer, Dame, Heer } // Ace, Two, Three, Four, Five, Six, Zeven, Eight, Nine, Ten, 11, 12, 13
public enum Kleur { Schoppen, Harten, Klaveren, Ruiten }
我有一个排序方法,可以按照正确的顺序对所有卡片进行排序,这些单词很好:
public int CompareTo(object obj)
{
Kaart dezeKaart = this;
Kaart andereKaart = obj as Kaart;
int compareTo = dezeKaart.Kleur.CompareTo(andereKaart.Kleur);
if(compareTo == 0)
{
compareTo = dezeKaart.Nummer.CompareTo(andereKaart.Nummer);
return compareTo;
}
return compareTo;
}
这种排序方法的结果是:
// ♠A - ♠2 - ♠3 - ♠4 - ♠5 - ♠6 - ♠7 - ♠8 - ♠9 - ♠10 - ♠B - ♠D - ♠H
// ♥A - ♥2 - ♥3 - ♥4 - ♥5 - ♥6 - ♥7 - ♥8 - ♥9 - ♥10 - ♥B - ♥D - ♥H
// ♣A - ♣2 - ♣3 - ♣4 - ♣5 - ♣6 - ♣7 - ♣8 - ♣9 - ♣10 - ♣B - ♣D - ♣H
// ♦A - ♦2 - ♦3 - ♦4 - ♦5 - ♦6 - ♦7 - ♦8 - ♦9 - ♦10 - ♦B - ♦D - ♦H
I now want to implement Icompare
to have this as an outcome:
// ♦7 - ♦8 - ♦9 - ♦B - ♦D - ♦H - ♦A - ♦10
// ♣7 - ♣8 - ♣9 - ♣B - ♣D - ♣H - ♣A - ♣10
// ♠7 - ♠8 - ♠9 - ♠B - ♠D - ♠H - ♠A - ♠10
// ♥7 - ♥8 - ♥9 - ♥B - ♥D - ♥H - ♥A - ♥10
【问题讨论】:
-
问题出在哪里?
-
抱歉,更新了我的帖子
-
好吧,给你的枚举成员值以强制卡值层次结构。你知道你能做到,对吧?
enum MyEnum { One = 1, Three = 3, //etc. } -
我知道,但这会弄乱我的其他排序方法,结果必须是: // ♠A - ♠2 - ♠3 - ♠4 - ♠5 - ♠6 - ♠7 - ♠ 8 - ♠9 - ♠10 - ♠B - ♠D - ♠H // ♥A - ♥2 - ♥3 - ♥4 - ♥5 - ♥6 - ♥7 - ♥8 - ♥9 - ♥10 - ♥B - ♥D - ♥H ... 这种排序方法必须是: // ♦7 - ♦8 - ♦9 - ♦B - ♦D - ♦H - ♦A - ♦10 // ♣7 - ♣8 - ♣ 9 - ♣B - ♣D - ♣H - ♣A - ♣10 // ♠7 - ♠8 - ♠9 - ♠B - ♠D - ♠H - ♠A - ♠10 // ♥7 - ♥8 - ♥ 9 - ♥B - ♥D - ♥H - ♥A - ♥10
-
只创建两张卡(那些不起作用的卡)来测试您的代码并调试您的代码。看看逻辑错在哪里,改正。
标签: c# enums icomparable icomparer