Home > Programming > Learning Python and Ruby – Card Object

Learning Python and Ruby – Card Object

Let’s work on a personal favorite of mine – Card and Deck objects. This will be the first time I will make an object in Python and Ruby.

The Card object represents a playing card. It has a rank value, a suit value, and a string representation. This will be used later with a Deck object.

JavaScript

function card(rank, suit) {
    this.rank = validateNumber(rank, 12);
    this.suit = validateNumber(suit, 3);
    this.value = cardToString(this.rank, this.suit);
};

function validateNumber(nb, max) {
    if (!isNaN(nb) && nb >= 0 && nb <= max) {
        return nb;
    }

    return Math.floor(Math.random() * (max + 1));
};

function cardToString(rank, suit) {
    var ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'];
    var suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds'];

    return ranks[rank] + ' of ' + suits[suit];
};

Python

import random

class Card:
    """ Defines a Card object """
    def __init__(self, rank=None, suit=None):
        self.rank = validateNumber(rank, 12)
        self.suit = validateNumber(suit, 3)
        self.value = cardToString(self.rank, self.suit)

def validateNumber(nb, maximum):
    """ Validates a number from 0 up to a specified maximum, or a random one """
    try:
        if nb >= 0 and nb <= maximum:
            return nb
    except:
        pass

    return random.randint(0, maximum)

def cardToString(rank, suit):
    """ Returns the string representation of the specified rank and suit """
    ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
    suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds']

    return '{0} of {1}'.format(ranks[rank], suits[suit])

Ruby

class Card
    def initialize(rank=nil, suit=nil)
        @rank = validateNumber(rank, 12)
        @suit = validateNumber(suit, 3)
    end

    def value
	cardToString(@rank, @suit)
    end
end

def validateNumber(nb, maximum)
    if nb.is_a?(Numeric) and nb >= 0 and nb <= maximum
        return nb
	end

    rand(maximum)
end

def cardToString(rank, suit)
    ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
    suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds']

    "#{ranks[rank]} of #{suits[suit]}"
end

As you can see from the code, you can create a new random card by specifying no argument, or create a specific card with the appropriate arguments (if you know the code). The code handles invalid argument values, in which case it generates a random value. This is probably a bad practice, as it would not yield the expected result, but it’s a pretty simple example, and I’m not into error-handling yet. To create a Card object, you can use new card() in JavaScript, Card() in Python, and Card.new() in Ruby.

Writing the code in JavaScript was pretty straightforward, but I had to do a bit of research in order to implement the Card object in Python and Ruby. I learned that in Python, you usually don’t check for type, but use a try-except to catch the error if the variable wasn’t of the type you wanted. In Ruby, there is a difference between a single-quote string, and a double-quote string – double-quotes are for string that could get some modifications inside, such as the #{} formatting. And, although I am not completely sure why, I had to take the Card’s value property and take it out of the initialize() method. Finally, I noticed that Python and Ruby are more object-oriented than JavaScript.

Categories: Programming Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.