Sergei
Sergei

Reputation: 605

Simple solitaire

I'm trying to make a simple solitaire in wich you get a random number of card heaps with a random number of cards in ex. heap1: 4 cards, heap2 5 cards and so on. Lets say we have four heaps with values 4, 5, 7, 1. Now what is done is that one card is removed from each heap to create a new one. So the next step would look like this 4, 5, 7, 1 -> 3, 4, 6, 4. The solitaire is finished when it reaches a stable number ex. 5, 3, 2 -> 4, 2, 1, 3 -> 3, 1, 2 ,4... now we will always get the same four values if the numbers are sorted.

How would this be done in the best way? I have some basic knowledge in programming but nothing advanced.

So far i have tried this but it does not work out well, i don't know how to make the loop stop at a stable number.

while len(y) > 1:
    for i in range(len(y)):
        y[i] -= 1
    y = [x for x in y if x != 0]
    y.append(len(y))
    y.sort()
    print(y)

Upvotes: 2

Views: 3199

Answers (2)

Bogdan
Bogdan

Reputation: 8246

What about this:

def step(list):
    new_list = [x-1 for x in list if (x-1) > 0] #You remove one from each heap
    new_list.append(len(list)) #Now add the new heap
    if sorted(new_list) == sorted(list):
        return new_list, True
    else:
        return new_list, False

Then you can call the method like:

new_config, is_done = step(list)

until is_done is true. I hope you understand my ideea.

Upvotes: 0

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67197

So the actual cards (colors, faces) do not matter at all since all you model is a number of heaps?

Use a list for the setup, integers to represent the heaps, and the random module to generate the initial configuration. Programming the game logic should be rather straight-forward.


UPDATE

You're code is a good start. To make things easier, consider breaking it up into separate functions. E.g.:

def next_configuration(y):
    """Take a configuration of heaps and remove one card from each
    heap to create a new heap.
    """
    new_y = [x - 1 for x in y if x > 1]
    new_y.append(len(y))
    new_y.sort(reverse=True)
    return new_y

Now you can test if the function does what it is supposed to do:

>>> next_configuration([5, 1, 3, 2])
[4, 4, 2, 1]

To play it to the end, generate the next configuration until the current configuration does not change any more:

config = generate_initial_configuration()
for i in range(max_rounds):
    new_config = next_configuration(config)
    if new_config == config:
        break
    config = new_config

Upvotes: 3

Related Questions