All pastes #44726 Raw Edit

Bridge Dealer

public ruby v1 · immutable
#44726 ·published 2006-03-06 23:55 UTC
rendered paste body
class Card	# define static array 'class variables' to use to dereference value integers	@@values = %w{ A 2 3 4 5 6 7 8 9 T J Q K }	@@suits = %w{ Hearts Dimonds Clubs Spades }	# constructor	def initialize( numeric )		raise( argumentError, "Cards must be initialized between 0 and 52" ) if !numeric === 0..52		@numeric = numeric	end		# setters	attr_reader :numeric			# getters		def value		@numeric % 13		end		def suit		@numeric / 13	end		# For some unfortunate reason you can't use attr_ for class variables	def self.suits		@@suits	end		def self.values		@@values	end		# Create string conversion methods		def s_value		@@values[value]	end		def s_suit		@@suits[suit]	end	# Overload the standard to_s		def to_s		puts s_value + " of " + s_suit	end	endclass Deck	def initialize( size = nil )		@deck = Array.new		size ||= 1		if size.kind_of?( Integer )			raise( arguementError, "Cannot have a negative number of decks" ) if size < 0			if size == 0				size = 1			end			size.times { (0..52).each { |numeric| @deck.push( Card.new( numeric ) ) } }		end	end	def deal( cards = nil )		cards ||= @deck.size		raise( argumentError, "You must pass an integer or nil to Deck.deal") if !cards.kind_of?( Integer )		raise( argumentError, "Passing negative value to Deck.deal is illegal" ) if cards < 0		if cards > @deck.size			STDERR.puts "Warning, tried to deal more cards than are available in the deck."			cards = @deck.size		end		cards.times { yield @deck.delete_at( rand( @deck.size ) ) }	end		def draw		return deal( 1 ) { |x| x }	endendclass Player	@@nextid = 0	def initialize( name )		@@nextid += 1		@name = name || @@nextid.to_s		@id = @@nextid		@hand = Array.new	end		attr_reader :name		def give( card )		raise( argumentError, "Tried to give a player a non-card" ) if !card.kind_of?( Card )		@hand.push( card )	end		def showhand		score = 0		sort		$, = nil		for i in 0..3			suitcount = 0			suit = @hand.find_all { |card| card.suit == i }			print Card.suits[i], ": "			suit.each do				|card|				print card.s_value				suitcount += 1				if( card.value === 10..12 )					score += card.value - 9				elsif( card.value == 0 )					score += 4				end			end			print "\n"			if suitcount < 3				score += (3 - suitcount)			end		end		print "Score: ", score, "\n"	end		def sort		@hand.sort_by { |card| card.numeric }	end	endclass RotatingArray < Array	def initialize(*params)		super(*params)		@rotated = -1	end	def rotate		@rotated += 1		return self[@rotated % size]	endenddeck = Deck.newplayerList = RotatingArray.new%w{ North South East West }.each { |name| playerList.push( Player.new( name ) ) }deck.deal { |card| playerList.rotate.give( card ) }playerList.each	do	|player|	print player.name, "\n"	player.showhand	print "\n"end