Question

I need to know how to implement a greedy algorithm in a card game using C#. The game is a turn based game. When the AI should issue some cards, it must be based on the latest state of other cards that already are on the table. Does anyone have a solution for this, or maybe a reference for me to get started? Thanks in advance!

For now I only finished the code to shuffle the cards:

List<int> cards = new List<int>();

for (int j = 1; j <= 2; j++)
{
    for (int i = 1; i <= 54; i++)
    {
        cards.Add(i);
    }
}

List<int> ShuffledCards = new List<int>();
Random random = new Random();

int iterations = cards.Count;
int index = 0;
for (int j = 1; j <= 2; j++)
{
    for (int i = 0; i < iterations; i++)
    {
        index = random.Next(0, iterations - i);
        ShuffledCards.Add(cards[index]);
        cards.RemoveAt(index);
    }
    iterations = cards.Count;
    index = 0;
}

ShuffledCards.Reverse(0, ShuffledCards.Count);
ShuffledCards.RemoveRange(0, 8);
ShuffledCards.Reverse(0, ShuffledCards.Count);
Was it helpful?

Solution

This book is like a bible about AI. You can start with reading first 3 parts of this book.

OTHER TIPS

I don't get what you mean by greedy algorithm. You are not trying to have the dealer maximize some goal or find a good strategy for something are you?

This looks more like a matter of simulating a game of cards. We need to know what you actually want to do afterwards.

Pseudocode:

//Your deck state:
deck   //list of cards in the deck (in top->bottom order) (initially shuffled)
i;     //index of the card at the top of the deck

void dreshuffle(){
    shuffle(cards);
    i = 0;
}

int get_card(){
    if(i >= cards.length){
        //no cards left in pile
        reshuffle()    
    }
    return cards[i++];
}

Of course, this is just a simplistic example since it assumes the dealer has all the cards back when he reshuffles. Perhaps you might need to add a discard pile or similar to suit your game rules.


By the way, your shuffle method is strange. Why do you shuffle twice? A more normal approach would be

list;
n = list.count - 1 //last index in list
while(n >= 0){
    i = random integer in range [0,n] (inclusive)
    swap(list[i], list[n])
    n -= 1
}

(Or just use a library function)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top