View Single Post
Old Oct 31st, 2005, 4:31 AM   #1
coldDeath
Expert Programmer
 
coldDeath's Avatar
 
Join Date: Aug 2005
Location: UK
Posts: 862
Rep Power: 4 coldDeath is on a distinguished road
Send a message via AIM to coldDeath Send a message via Yahoo to coldDeath
Neatening some Python code

OK, I wrote a simple script that will deal you some cards.

Basically it takes an argument of how many cards you want to be drawn, and then it shows you those cards. It doesn't draw the same card twice. The cards can be put back into the pack by calling: shuffle().

It works fine, but what i am interested in is shortening the code and making it more efficient.

Here it is:
#! /usr/bin/python

#Card Dealer

import random
class cards:
	def __init__(self):
		self.suits = ["Hearts", "Diamonds", "Spades", "Clubs"]
		self.numbers = ["Ace", 2, 3, 4, 5 , 6, 7, 8, 9, 10, "Jack", "Queen", "King"] 
		self.pack = ["52 Card Pack"]
		for x in self.suits:
			for y in self.numbers:
				z = "%s of %s" % (y, x)
				self.pack.append(z)
		self.shuffle()
	
	def shuffle(self):
		self.choices = [1]
		for n in range(2,53): self.choices.append(n)
		
	def draw_a_card(self):
		a = random.choice(self.choices)
		card_drawn = self.pack[a]
		self.choices.remove(a)
		return card_drawn

	def deal(self, number_of_cards):
		b = self.draw_a_card()
		self.playercards = [b]
		for i in range(1, number_of_cards):
			b = self.draw_a_card()
			self.playercards.append(b)
		print "Your hand: %s" % (self.playercards)
	
newgame = cards()
deal = "y"
while deal == "y":
	newgame.deal(5)
	deal = raw_input("Deal again? (y/n)")

Its about 35 lines without comments. I can't think of any way that i could shorten this code, how would you go about shortening it?
__________________
Join us at #programmingforums @ irc.freenode.net!

My software never has bugs. It just develops random features.
coldDeath is offline   Reply With Quote