В настоящее время я создаю оценщика покера, который сравнивает руку с несколькими игроками и определяет, кто победитель. Однако метод фактического сравнения и тай-брейка оказывается намного более трудным, чем следовало бы. Есть ли способ упростить мой код? Поскольку я не размещаю весь исходный код, я обсужу функциональность некоторых методов, вызванных внутри:Нужна помощь в упрощении моего кода при оценке покера
int HandEval (Card [] hand) берет массив карт и возвращает int, который символизирует оценку (т. е. три вида будут иметь более высокий балл, чем одна пара)
int GetHighCard (Card [] hand) берет массив карт и возвращает ранг высокой карты, используемой для тай-ломания (т. е. . в случае тройка, ранг одного из этих трех видов будут возвращены)
public void FindWinner()
{
int maxScore = 0;
int maxRank = 0;
List<String> potentialWinners = new List<string>();
List<Card[]> candHand = new List<Card[]>();
Dictionary<string, Card[]> deckTable = new Dictionary<string, Card[]>();
Dictionary<string, int> scoreTable = new Dictionary<string, int>();
Dictionary<string, int> highTable = new Dictionary<string, int>();
//place each player to deckTable which holds the player name and their hand
//place each player to scoreTable which holds the player name and the score of their hand
for (int i = 0; i < players.Count; i++)
{
deckTable.Add(players[i].GetName(), players[i].GetSorted());
scoreTable.Add(players[i].GetName(), HandEval(players[i].GetSorted()));
}
//display the player name and the score of their hand
foreach (KeyValuePair<string, int> pair in scoreTable)
{
Console.WriteLine("{0}, {1}", pair.Key, +pair.Value);
}
//find the max score of the current game
foreach (var kvp in scoreTable)
{
if (kvp.Value > maxScore)
{
maxScore = kvp.Value;
}
}
//display the max score
Console.WriteLine("The maximum score is " + maxScore);
//for all players with the max score, add them to the potential winners list
foreach (var kvp in scoreTable)
{
if (kvp.Value == maxScore)
{
potentialWinners.Add(kvp.Key);
}
}
//if there are more than one potential winner, run the tie-break checks
if (potentialWinners.Count > 1)
{
Console.WriteLine("Potential winners include: ");
for (int i = 0; i < potentialWinners.Count(); i++)
{
Console.WriteLine("" + potentialWinners[i] + "");
}
//add the name of the potential winners and the rank of the high card as a key value pair to highTable
for (int i = 0; i < potentialWinners.Count(); i++)
{
if (deckTable.ContainsKey(potentialWinners[i]))
{
Card[] cHand = deckTable[potentialWinners[i]];
highTable.Add(potentialWinners[i], GetHighCard(cHand));
}
}
Console.WriteLine("Displaying potential winners with their high card rank.");
foreach (KeyValuePair<string, int> pair in highTable)
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}
//find the max rank of high card from all potential winners
foreach (var kvp in highTable)
{
if (kvp.Value > maxRank)
{
maxRank = kvp.Value;
}
}
Console.WriteLine("The final winner after tie-breaking is");
//display the winner(s) with the highest rank of card
foreach (var kvp in highTable)
{
if (kvp.Value == maxRank)
{
Console.WriteLine("" + kvp.Key + "");
}
}
}
//if there is only one potential winner, display the name
else
{
Console.WriteLine("The final winner is");
Console.WriteLine(potentialWinners[0]);
}
}
}
Любая помощь или советы будут весьма признателен!
Это было бы лучше на CodeReview –
Необычно удалить свой вопрос из переполнения стека. Идея состоит в том, чтобы создать какую-то базу данных, темы которой легко найти в поисковых системах. Не стесняйтесь или что-нибудь подобное для какого-то старого кода, никто не родился как опытный кодер.Каждый раз, когда я смотрю на какой-то старый код - может быть, только на год - я нахожу массу вещей, которые я бы сделал намного лучше сейчас. – Aziuth