zier45 zier45 - 7 months ago 21
Python Question

Card Game Python, Saving a shuffled deck

I am writing a program in Python where the user has to guess if the next card in a pack of playing cards is bigger or smaller than the previous card.
I've got the whole program to work except for one function.

I have two ways of playing this game. One way is to shuffle the deck of cards and the other way is to play with an un-shuffled deck of cards (some random order I put them in when making a text file). What I want to do is when the user selects to play with a shuffled deck, the shuffled deck is saved and overwrites the un-shuffled deck's text file.

The cards in the text file are saved as two or three digit numbers.

Each suit is numbered as follows:



  • 1 - Clubs

  • 2 - Diamonds

  • 3 - Hearts

  • 4 - Spades




As far as card numbers go:



  • 1 - Ace

  • 2 - Two

  • ...

  • 11 - Jack

  • 12 - Queen

  • 13 - King




So the 5 of hearts would be saved as 35, and the jack of clubs would be saved as 110

Here is my code so far.

This is my attempt at saving:



def SaveShuffledDeck(Deck):
CurrentFile = open('deck.txt', 'w')
Count = 1

for Count in range(1,52+1):
CardtoaddtoFile = str(Deck[Count].Suit) + str(Deck[Count].Rank) + '\n'
CurrentFile.write(CardtoaddtoFile)

CurrentFile.close()


If you would like to see the rest of the code for the deck, check out this pastebin link

Answer Source

Might want to give this a good read: http://docs.python.org/2.7/library/functions.html#open

open('deck.txt', 'w') # will overwrite it

And then do something like this...

import random
f = open('deck.txt', 'w') # op
l = [i for i in range(1,111)] # list from 1 to 110
random.shuffle(l) # shuffle that list
for i in l:
    f.write(str(i))
    f.write('\n')

EDIT: Sorry, did not use your functions. You could modify this though.