cardset.py

#!/usr/bin/env python
#
# Author:  Yotam Medini  [email protected] -- Created: 2006/April/23
#
# Card-Set Game - Version 0.1
#

import random
import sys

# We assign constant numbers 0,1,2 to color, shape, texture

[Red, Green, Blue]         = range(3)  # Assign color numbers
[Diamond, Peanut, Oval]    = range(3)  # Assign shape numbers
[Contour, Filled, Stripes] = range(3)  # Assign texture numbers


# Choose random number from: {0, 1, 2}
def rand012():
    return random.randint(0,2)



# If good index, return name from list
def name012(names3, i):
    s = "?"
    if i != None and 0 <= i < 3:
        s = names3[i]
    return s


class CardSet:

    def __init__(self):
        # Start with undefined values
        self.n = 0
        self.color = None
        self.shape = None
        self.texture = None


    def random(self):
        self.n       = rand012() + 1
        self.color   = rand012()
        self.shape   = rand012()
        self.texture = rand012()


    def color_name(self):
        return name012(["Red", "Green", "Blue"], self.color)


    def shape_name(self):
        return name012(["Diamond", "Peanut", "Oval"], self.shape)


    def texture_name(self):
        return name012(["Contour", "Filled", "Stripes"], self.texture)


    # This special function is called when formatting to string via "%s"
    def __str__(self):
        s = "<%d/%s/%s/%s>" % (
            self.n, self.color_name(), self.shape_name(), self.texture_name())
        return s


# Test 10 random cards
card = CardSet()
sys.stdout.write("Undefined card=%s\n" % card)
for n in range(0, 10):
    card.random()
    sys.stdout.write("[%d] random card=%s\n" % (n, card))
sys.exit(0)

Generated by GNU enscript 1.6.4.