Class demonstrations

Random circles in Turtle Grapics

import turtle
import random

MAX_COORD = 300
COLORS = ['yellow', 'blue', 'red', 'green']
RADIUS = 25

t = turtle.Turtle()

for i in range(20): # repeat
    t.fillcolor(COLORS[random.randint(0,3)])
    t.penup()
    t.goto(random.randint(-MAX_COORD,MAX_COORD), random.randint(-MAX_COORD,MAX_COORD))
    t.pendown()
    t.begin_fill()
    t.circle(RADIUS)
    t.end_fill()

Are you a horse?

import turtle

t = turtle.Turtle()

choice = input("Choose between square, circle or both: ")
if choice.lower() == "square" or choice.lower() == "both":
  turtle.forward(100)
  turtle.right(90)
  turtle.forward(100)
  turtle.right(90)
  turtle.forward(100)
  turtle.right(90)
  turtle.forward(100)
if choice.lower() == "circle" or choice.lower() == "both":
  turtle.circle(50)
  
print("Finished!")

Dog class

class Dog(): # definition of the class ("blueprint")
  
  max_age = 20
  
  def __init__(self, breed, age, color):
    self.breed = breed
    self.age = age
    self.color = color
    
  def eat(self):  # a method (NOTICE THAT IT IS INSIDE THE CLASS DEFINITION)
    pass  # using "pass" to write it as an empty function (to be filled later)
  
  def sleep(self):
    pass
  
  def sit(self):
    pass
  
  def average_color(c1, c2):
    return c1 + ' and ' + c2
  
  def crossbreed(self, dog):
    if self.breed == dog.breed:
      puppy = Dog(self.breed,0,Dog.average_color(self.color, dog.color))
    else:
      puppy = Dog('mutt',0,Dog.average_color(self.color, dog.color))
    return puppy

  def __str__(self):
    return f'breed: {self.breed}, age: {self.age}, color: {self.color}'
  
# testing
a = Dog('pug', 3, 'black')
b = Dog('boxer', 2, 'white')
print(a.crossbreed(b))
breed: mutt, age: 0, color: black and white

Bridge game

import random

class Game():
    
    def __init__(self, deck, teams):
        self.deck = deck
        self.teams = teams
        self.currentTurn = None
        
    def start(self):
        for t in self.teams:
            t.score = 0
        self.deck.shuffle()
        deal_number = len(self.deck.cards)//4 # 4 players
        # deal cards
        for t in self.teams:
                for p in t.players:
                    for i in range(deal_number):
                        p.hand.append(self.deck.deal())
    
    def end(self):
        pass
    
class Team():
    def __init__(self, players, score=0):
        self.players = players
        self.score = score
        
    def addScore(self, points):
        self.score += points
        
    def __str__(self):
        s = 'Team: ' + '/'.join([p.name for p in self.players]) + '\n'
        for p in self.players:
            s += str(p)
        return s
        
class Player():
    def __init__(self, name, hand=[], score=0):
        self.hand = hand.copy()  # needs to copy! otherwise it will be the same list for all players
        self.name = name
        self.score = score
        
    def playCard(self,card):
        if self.hand.index(card):
            played = self.hand.pop(self.hand.index(card))
            print(self.name + ' played a ' + str(played))
    
    def __str__(self):
        s = f'{self.name} has {self.score} points. Hand is:\n'
        for i in self.hand:
            s += str(i)+'\n'
        s += '\n'
        return s

class Card():
    
    suits = ['spades', 'clubs', 'hearts', 'diamonds']
    ranks = ['A','2','3','4','5','6','7','8','9','10','Q','J','K']
    
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit
    
    def __str__(self):
        return self.rank + ' of ' + self.suit
        
class Deck():
    def __init__(self):
        c = []
        for s in Card.suits:
            for r in Card.ranks:
                c.append(Card(r, s))
        self.cards = c
        
    def shuffle(self):
        random.shuffle(self.cards)
    
    def deal(self):
        return self.cards.pop()
    
    def __str__(self):
        s = 'Deck: '
        for i in self.cards:
            s += str(i)+' '
        s += '\n'
        return s

bob = Player('Bob')
jen = Player('Jen')
john = Player('John')
mary = Player('Mary')
team1 = Team((bob, jen))
team2 = Team((john, mary))
d = Deck()
g = Game(d, (team1, team2))
g.start()
print(team1)
print(team2)

Shapes and areas

import math

class Shape:
    def area(self):
        return 0
      
    def __eq__(self, other):
        return self.area() == other.area()

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius**2


# main chunk
rectangle = Rectangle(5, 10)
circle = Circle(3)

Reading a text file with names

names_file = open('names.txt', 'r')
names = []
for i in range(100):
    complete_name = names_file.readline()
    names.append(complete_name.split(' '))
for n in names:
    print(n[1])
names_file.close()