3

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);
Svante
  • 50,694
  • 11
  • 78
  • 122

2 Answers2

4

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

Çağdaş
  • 993
  • 1
  • 12
  • 33
  • I completely agree with this answer, it is definitely the AI bible. A good document which focuses on greedy algorithms specifically is [this](http://www.cs.berkeley.edu/~vazirani/algorithms/chap5.pdf). – phuibers May 03 '11 at 11:22
0

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)

hugomg
  • 68,213
  • 24
  • 160
  • 246
  • hi missingno..why i shuffle the deck twice,,because the game rule use 2 deck of card,54 cards each deck,include 2 joker..so loop 1 is for first deck and loop 2 for second deck.. – Selalu_Ingin_Belajar May 04 '11 at 09:34