Fundamentals of Programming I More Data Modeling

Slides:



Advertisements
Similar presentations
Black Jack in Objective-C
Advertisements

Topics in Python Blackjack & TKinter
Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view class.
© Glenn Rowe AC Lab 2 A simple card game (twenty- one)
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Computer Science 112 Fundamentals of Programming II Queues and Priority Queues.
Classes 2 COMPSCI 105 SS 2015 Principles of Computer Science.
Top-Down Design CSC 161: The Art of Programming Prof. Henry Kautz 9/16/2009.
12 Pontoon1May Pontoon program CE : Fundamental Programming Techniques.
Fundamentals of Programming II Inheritance and Abstract Classes
Intro to Probability & Games
Chapter 5 Black Jack. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 5-2 Chapter Objectives Provide a case study example from problem statement.
AP Computer Science.  Not necessary but good programming practice in Java  When you override a super class method notation.
Lecture 05 – Classes.  A class provides the definition for the type of an object  Classes can store information in variables  Classes can provide methods.
VOCABULARY  Deck or pack  Suit  Hearts  Clubs  Diamonds  Spades  Dealer  Shuffle  Pick up  Rank  Draw  Set  Joker  Jack 
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
Fundamentals of Python: From First Programs Through Data Structures
Classes 2 COMPSCI 105 S Principles of Computer Science.
Classes 3 COMPSCI 105 S Principles of Computer Science.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
Computer Science 111 Fundamentals of Programming I More Data Modeling.
Guide to Programming with Python
Two Way Tables Venn Diagrams Probability. Learning Targets 1. I can use a Venn diagram to model a chance process involving two events. 2. I can use the.
More On Classes UW CSE 160 Spring Classes define objects What are objects we've seen? 2.
Computer Science 112 Fundamentals of Programming II Interfaces and Implementations.
Guide to Programming with Python Week 11 Chapter Nine Inheritance Working with multiple objects.
November 28, 2005ICP: Chapter 9: Object Oriented Programming 1 Introduction to Computer Programming Chapter 9: Object Oriented Programming Michael Scherger.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Draw 3 cards without replacement from a standard 52 card deck. What is the probability that: 1.They are all red ? 2.At least one is black ? 3.They are.
Lecture 09 – Classes.  At the end of this lecture, students should be able to:  Define a new class  Store state information about instances of the.
Week 8 : User-Defined Objects (Simple Blackjack Game)
Q and A for Sections 6.2, 6.3 Victor Norman CS106.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
COMP 14 Introduction to Programming Mr. Joshua Stough March 23, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Arrangements and Selections (and how they may be counted)
Section 5.5 Application: The Card Game of War. 5.5 Application: The Card Game of War A deck of cards is shuffled and dealt to two players The players.
Python programming - Defining Classes
COMPSCI 107 Computer Science Fundamentals
Guide to Programming with Python
More On Classes UW CSE 160 Winter
Combinations Problems
COMPSCI 107 Computer Science Fundamentals
CSSE 120—Rose Hulman Institute of Technology
Mathematical operators overload
Making Choices with if Statements
Software Development Java Classes and Methods
11/7/16 Entry 173 – Objective I will review and continue developing my understanding of uniform probability models, including the complement of an event.
The Addition Rule.
Chapter 5 Black Jack.
Fundamentals of Programming II Interfaces and Implementations
Computer Science 111 Fundamentals of Programming I
Fundamentals of Programming I More Data Modeling
Fundamentals of Programming I More Data Modeling
Probability.
A R R A Y ! for Multiplication!!
Computer Science 111 Fundamentals of Programming I
Fundamentals of Programming I Commonly Used Methods More Modeling
3rd/4th grade Family Math Night Games
Fundamentals of Programming I More Data Modeling
Task 2 Implementation help
Section 12.2 Theoretical Probability
Section 12.2 Theoretical Probability
Fundamentals of Python: First Programs Second Edition
Lecture 18 Python OOP.
Homework Due Friday.
CSC 221: Introduction to Programming Fall 2018
Introduction to Object-Oriented Programming (OOP) II
Section 12.2 Theoretical Probability
P(softball) = P(not a baseball) = P(golf ball) = A box contains 3 tennis balls, 7 softballs, and 11 baseballs. One ball is chosen at random. Find.
A R R A Y ! for Multiplication!!
Presentation transcript:

Fundamentals of Programming I More Data Modeling Computer Science 111 Fundamentals of Programming I More Data Modeling

Accessing Data in an Object >>> die = Die() >>> die.getValue() 1 >>> print(die.getValue()) An object’s data can be viewed or accessed by using its accessor methods

String Representation >>> die = Die() >>> str(die) # Same as die.__str__() '1' >>> print(str(die)) 1 Each class can include a string conversion method named __str__ This method is automatically called when the str function is called with the object as a parameter

String Representation >>> die = Die() >>> str(die) # Same as die.__str__() '1' >>> print(str(die)) 1 >>> print(die) # Better still Each class can include a string conversion method named __str__ print runs str if it’s given an object to print - way cool!

The __str__ Method class Die(object): """This class represents a savings account.""" def __init__(self): self.value = 1 def __str__(self): return str(self.value) As a rule of thumb, you should include an __str__ method in each new class that you define

Other Common Methods Python allows you to define other methods that are automatically called when objects are used with certain functions or operators Function or Operator Method Called len(obj) obj.__len__() obj1 in obj2 obj2.__contains__(obj1) obj1 + obj2 obj1.__add__(obj2) obj1 < obj2 obj1.__lt__(obj2) obj1 > obj2 obj1.__gt__(obj2) obj[index] obj.__getitem__(index) obj1[index] = obj2 obj1.__setitem__(index, obj2)

Example: Rational Numbers from rational import Rational oneHalf = Rational(2, 4) oneThird = Rational(1, 3) print(oneHalf) # Prints 1/2 print(oneThird < oneHalf) # Prints True theSum = oneHalf + oneThird print(theSum) # Prints 5/6

Example: Rational Numbers class Rational(object): """This class represents a rational number.""" def __init__(self, numerator = 1, denominator = 1): self.numer = numerator self.denom = denominator self.reduce() def __str__(self): return str(self.numer) + "/" + str(self.denom) The __init__ and __str__ methods should always be defined first; then you can test the class to verify that its objects are appropriately instantiated.

Addition of Rational Numbers class Rational(object): """This class represents a rational number.""" def __add__(self, other): """Returns the sum of self and other.""" numerSum = self.numer * other.denom + \ other.numer * self.denom denomSum = self.denom * other.denom return Rational(numerSum, denomSum) nsum / dsum = (n1* d1 + n2 * d1) / (d1* d2)

Comparison of Rational Numbers class Rational(object): """This class represents a rational number.""" def __lt__(self, other): """Returns True if self < other or False otw.""" extremes = self.numer * other.denom means = other.numer * self.denom return means < extremes Operator Method Implementation r1 < r2 __lt__ means < extremes r1 > r2 __gt__ means > extremes r1 == r2 __eq__ means == extremes r1 <= r2 __le__ means <= extremes r1 >= r2 __ge__ means >= extremes

Printing in the Shell >>> oneHalf = Rational(1, 2) >>> print(oneHalf) 1/2 >>> oneHalf <__main__.Rational object at 0x106166f28>

Printing in the Shell >>> oneHalf = Rational(1, 2) >>> print(oneHalf) 1/2 >>> oneHalf <__main__.Rational object at 0x106166f28> def __repr__(self): """Returns a string for shell printing.""" return str(self) Python runs the __repr__ method to obtain the print reprensentation of an object in the IDLE shell.

Modeling Card Games Used in card games, such as War, Blackjack, Poker, and Crazy Eights A standard deck consists of 52 cards Each card has a rank (a number from 1-13, where Ace is 1 and face cards are 11-13) Each card has a suit (Spades, Hearts, Diamonds, Clubs)

A Card: State and Behavior a rank a suit Behavior: examine the values of the state variables, but don’t ever modify them

Using the Card Class >>> Card card = Card(3, 'Spades') >>> print(str(card.rank) + ' of ' + card.suit) 3 of Spades >>> print(card) A Card object contains two data values, and these are never changed Thus, there is no need for accessor or mutator methods Just reference the card’s variables to get their values

Defining the Card Class class Card(object): SUITS = ('Spades', 'Hearts', 'Diamonds', 'Clubs') RANKS = tuple(range(1, 14)) def __init__(self, rank, suit): self.rank = rank self.suit = suit The Card class can specify the ranges of ranks and suits as class variables

Class Variables An instance variable refers to storage owned by a single instance A class variable refers to storage owned by the class, and thus available to all of its instances For example, each card owns a separate rank and suit, so theyshould be a instance variables But all cards have the same lists of ranks and suits, so they should be class variables

Create and Print all 52 Cards for suit in Card.SUITS: for rank in Card.RANKS: card = Card(rank, suit) print(card) print automatically runs str to obtain an object’s string representation

String Representation class Card(object): … def __str__(self): """Returns the string representation of a card.""" if self.rank == 1: rank = 'Ace' elif self.rank == 11: rank = 'Jack' elif self.rank == 12: rank = 'Queen' elif self.rank == 13: rank = 'King' else: rank = self.rank return str(rank) + ' of ' + self.suit

A Deck: State and Behavior A deck initially contains 52 cards The user can shuffle the deck deal a single card from its top check to see if there are more cards to deal 0..52 Card

The Deck Interface and Its Use shuffle() deal() # Removes and returns the top card isEmpty() str(aDeck)

The Deck Interface and Its Use shuffle() deal() # Removes and returns the top card isEmpty() Use from cards import Deck deck = Deck() deck.shuffle() while not deck.isEmpty(): card = deck.deal() print(card)

Application: The Game of War A simplified version with two players and a single war pile Each player has 2 piles of cards: An unplayed pile A winnings pile

Playing the Game of War Deal 26 cards to each player’s unplayed pile While both unplayed piles are not empty Each player moves the topmost card from the unplayed pile to the top of the game’s war pile If these cards do not have the same rank Move the cards from the game’s war pile to the winner’s winnings pile The player with the largest winnings pile wins

Additional Classes Player contains 2 piles of cards WarGame contains a deck, two players, and a single pile of cards; allows the user to step through the game On each step, the cards are drawn and the war pile is shifted if there is a winner

Classes and Relationships Deck WarGame 0..52 2 Card Player cards.py: Card, Deck wargame.py: Player, WarGame

The WarGame Interface WarGame() # Creates a deck and 2 players deal() # Deals 26 cards to each player step() # Draws the cards and shifts the piles winner() # Returns None if the game is not over, # or the results as a string otherwise str(aGame) # The current state of the game as a string

Playing the Game WarGame() # Creates a deck and 2 players deal() # Deals 26 cards to each player step() # Draws the cards and shifts the piles winner() # Returns None if the game is not over, # or the results as a string otherwise str(aGame) # The current state of the game as a string def main(): game = WarGame() game.deal() while not game.winner(): game.step() print(game) print(game.winner())

For Wednesday More data modeling