Contents

  1. bug.py
  2. card.py
  3. deck.py

bug.py 1/3

[
top][prev][next]
from graphics import *
from time import sleep
from math import * 

class Bug:
    "Represents a graphical bug."
    
    def __init__(self, center, radius):
        """ 
        Create a new bug 
        input:
        center: The center Point of the largest Circle in the bug
        radius: The radius of the largest Circle in the bug
        """
        c1 = Circle(center, radius)
        c1.setFill("red")
    
        dX = center.getX()
        dY = center.getY()
        p1 = Point((dX+radius/5.0), dY+radius)
    
        eye = Circle(p1,radius/5)
        eye.setFill("yellow")
    
        eye1 = eye.clone()
        eye1.move(-radius/2.5,0)
        eyeball = Circle(p1, radius/10)
        eyeball.setFill("black")
    
        eyeball1 = eyeball.clone()
        eyeball1.move(-radius/2.5, 0)
    
        self.bugComponents = [c1, eye, eye1, eyeball, eyeball1]

    
    def draw(self, window):
        """
        Draw the bug in a given window
        Parameter:
        window: A GraphWin object in which to draw the bug
        """
        for comp in self.bugComponents:
            comp.draw(window)
      

    def move(self, dx, dy):
        """ 
        Move a bug by a specified amount 
        Parameters:
        dx: The distance to move in the x direction
        dy: The distance to move in the y direction
        """
        for comp in self.bugComponents:
            comp.move(dx,dy)


    def walk(self, dx, dy, seconds):
        """
        Move a bug by a specified amount in a specified time
        Parameters -
        dx: The total distance to move in the x direction
        dy: The total distance to move in the y direction
        steps: the number of total steps to take
        """
        STEPS_PER_SECOND=20
        
        steps = seconds*STEPS_PER_SECOND # total number of steps
        for i in range(steps):
            self.move(dx/steps, dy/steps)
            # need to reduce the sleep; otherwise, sleeps too long;
            # the reduction helps to account for the move time 
            sleep(seconds/steps*.1) 

    def rotate(self, degrees):
        """
        Rotate a bug a specified number of degrees
        Parameters - 
        degrees: the number of degrees to rotate the bug
        """
    
        r = radians(degrees)
    
        circX1 = self.bugComponents[0].getCenter().getX()
        circY1 = self.bugComponents[0].getCenter().getY()
    
        for i in self.bugComponents:
            circX2 = i.getCenter().getX()
            circY2 = i.getCenter().getY()
            dx = circX2 - circX1
            dy = circY2 - circY1
            mx = dx*(cos(r)-1) - dy*sin(r)
            my = dx* sin(r) + dy*(cos(r)-1)
            i.move(mx,my)


    def setColor(self, color):
        """
        Change the color of the bug during the animation
        Parameters - 
        color: desired color change
        """
        # we know the first item in the list is the largest segment
        self.bugComponents[0].setFill(color)


def main():
    # create a window for the bugs
    window = GraphWin("Busy Bugs!",600,600)
    window.setBackground("black")
    window.setCoords(0,0,600,600)
    
    # create 4 bugs at various places in the window (using an appropriate
    # function)
    # put the bugs in a list

    bug1 = Bug(Point(50,60),30)
    bug2 = Bug(Point(200,350), 50)
    bug3 = Bug(Point(350,50), 20)
    bug4 = Bug(Point(350,300), 60)

    bugs = [bug1, bug2, bug3, bug4] # bug is defined as a list of the 4 bugs
    
    # draw the bugs (using an appropriate function)
    
    for n in range(4):
        bugs[n].draw(window)

    window.getMouse()

    # rotate one bug, pause

    for i in range(5):
        bug2.rotate(30)
        sleep(0.05)
        
        
    # change the color of one bug    
    for i in range(4):
        bugs[i].setColor(color_rgb(i*255/4, 255, 255))
        
    bugs[3].move(10, 10)
        
    bugs[0].walk(100, 100, 2)
    
    # wait for the user to click, then close the window
    window.getMouse()
    window.close()
   
main()



card.py 2/3

[
top][prev][next]
class Card:
    """
    A class to represent a standard playing card. The ranks are ints:
    2-10 for numbered cards, 11=Jack, 12=Queen, 13=King, 14=Ace.
    The suits are strings: 'clubs', 'spades', 'hearts', 'diamonds'.
    """
    
    def __init__(self, rank, suit):
        "Constructs a new Card object with the given rank (an int) and suit (a string)."
        self._rank = rank
        self._suit = suit

    def __str__(self):
        "Returns a string describing the card as 'rank of suit'."
        result = ""
        if self._rank == 11:
            result += "Jack"
        elif self._rank == 12:
            result += "Queen"
        elif self._rank == 13:
            result += "King"
        elif self._rank == 14:
            result += "Ace"
        else:
            result += str(self._rank)
        result += " of " + self._suit
        return result
        
    def getRank(self):
        "Returns rank."	
        return self._rank

    def getSuit(self):
        "Returns suit."
        return self._suit
        
    def rummyValue(self):
        "Returns the value of the card in the game of Rummy."
        if self._isFaceCard(): # handles face cards
            return 10
        elif self.rank == 14: # handles Ace
            return 15
        elif self.rank == 10: # handles 10
            return 10
        else:
            return 5
            
    def __eq__(self, other):
        """Returns true if this object and other are equivalent
        based on their rank and suit"""
        
        # verify that self and other are the same type
        if type(self) != type(other):
            return False
        # do comparison
        return self._rank == other._rank and self._suit == other._suit
        
    def __lt__(self, other):
        """ Compares Card objects by their rank"""
        
        # verify that self and other are the same type
        if type(self) != type(other):
            return False
            
        # do comparison
        return self._rank < other._rank
        
    def _isFaceCard(self):
        "Returns True iff the card is a face card."
        if self.rank > 10 and self.rank < 14:
            return True
        return False

        
def main():
    c1 = Card(14, "spades")
    print(c1)
    c2 = Card(13, "hearts")
    print(c2)
    c3 = Card(2, "diamonds")
    print(c3)
    
    # testing rummyValue() method
    testCases = [c1, c2, c3]
    expected = [15, 10, 5]

    for pos in range(len(testCases)):
        testCase = testCases[pos] # what data type is this?
        actualVal = testCase.rummyValue()
        if actualVal == expected[pos]:
            print("Success for rummyVal on", testCase, "-->", actualVal)
    
    # test equals
    result = c1 == "a string"
    print(result, "should be False")
    
    result = c1 == c2
    print(result, "should be False")
    
    result = c1 < c2
    print(result, "should be False")
    # 
    result = c2 < c1
    print(result, "should be True")
    
    print("\nTested cards in sorted order:")
    testCases.sort()
    for card in testCases:
        print(card)
    
# Since I am probably going to import this script into another script,
# I only want to call main() when it's *not* imported 
if __name__ == '__main__':
    main()

deck.py 3/3

[
top][prev][next]
# Implementation of a deck of cards.
# by CSCI 111, 03/19/2012

from card import *
from random import shuffle

class Deck:
    """ A class to represent a deck of playing cards."""
    
    def __init__(self):
        """Creates a new Deck object, filled with one of each
        unique card."""
        
        self._listOfCards = []
        for suit in ["clubs","hearts","diamonds","spades"]:
            for rank in range(2,15):
                self._listOfCards.append(Card(rank, suit))

    def __str__(self):
        """Returns a string representing the cards that are
        in the deck."""
        
        deckRep= ""
        for c in self._listOfCards:
            deckRep += str(c) + "\n"
        return deckRep

    def numRemaining(self):
        """Returns the number of cards left in the deck."""
        return len(self._listOfCards)
        
    def shuffle(self):
        """Shuffles the deck of cards"""
        shuffle(self._listOfCards)
        
    def isEmpty(self):
        """Returns True, iff the deck is empty."""
        return len(self._listOfCards) == 0
        
    def draw(self, numCards):
        """Returns the hand--a list of Cards drawn from the top of the deck."""
        hand = []
        for x in range(numCards):
            card = self._listOfCards.pop(0)
            hand.append(card)
        return hand
        
    def deal(self, numPlayers, numCards):
        listOfHands = []
        for x in range(numPlayers):
            listOfHands.append(self.draw(numCards))
        return listOfHands
        
    def burn(self, numCards):
        """ 'Burns' the first card, and then deals out and returns numCards"""
        self.draw(1) # burn the first card
        return draw(numCards)
        
def main():
    d = Deck()
    d.shuffle()
    print(d)
    print("The number of cards remaining in the deck is", d.numRemaining())
    myHand = d.draw(1)
    print("Draw the top card: ", myHand[0])
    myHand = d.draw(3)
    print("Drawn hand: ")
    for card in myHand:
        print(card)
        
    playersHands = d.deal(3, 4)
    
    for i in range(len(playersHands)):
        print("\nPlayer", i+1, ":")
        for card in playersHands[i]:
            print(card)
    
    print("\nThe number of cards remaining in the deck is", d.numRemaining())
    
    print("\nAre there cards left?", d.isEmpty())
    
# Since I am probably going to import this script into another script,
# I only want to call main() when it's *not* imported
if __name__ == "__main__":
    main()

Generated by GNU Enscript 1.6.6.