Black Jack in Objective-C

Slides:



Advertisements
Similar presentations
Natalia Sivackova. Events that cannot happen together (e.g. cant a card that is both red and black in a card deck) P(A B) = P(A) + P(B)
Advertisements

6 Hearts in North North: S: A 9 4 H: A J 10 5 D: A 5 C: K South: S: K 8 H: K Q D: Q C: A 3 IMPs 29 hcpts Bidding: N: 1N S: 2D N: 3H S:
Lecture 3 - Writing Initializers A correct initializer must comply with the following: The initializer name should begin with init The initializer returns.
Probability and Conditional Probability. Probability Four balls What is the probability of choosing the ball in the red box? Since there are four balls.
1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure Definitions 10.3Initializing Structures 10.4Accessing.
Minibridge Cowbridge Comprehensive July 2007 Patrick Jourdain.
Combinations Examples
Lecture 18 Dr. MUMTAZ AHMED MTH 161: Introduction To Statistics.
Probability: Mutually Exclusive Events 1. There are 3 red, 4 black and 5 blue cubes in a bag. A cube is selected at random. What is the probability of.
Case Study: Focus on Structures Math 130 Lecture 21 B Smith: 10/04: Required 35 minutes to complete. 15 minutes was spent returning test 2 and completing.
2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
1 Greg Wilson BA 4234 CSC407: Software Architecture Fall 2006 Refactoring.
1 / / / /. 2 (Object) (Object) –, 10 (Class) (Class) –, –, – (Variables) [ Data member Field Attribute](, ) – (Function) [ Member function Method Operation.
C9, a case study: Solitaire
New features in JDK 1.5 Can these new and complex features simplify Java development?
Programming in C Chapter 10 Structures and Unions
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 7.9Arrays of Pointers Arrays can contain pointers For.
2000 Deitel & Associates, Inc. All rights reserved. Chapter 16 – Bits, Characters, Strings, and Structures Outline 16.1Introduction 16.2Structure Definitions.
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.
Mock Objects. Unit-testing and TDD are challenging They require some effort to: – Write a test for a small functionality – Refactor production code and.
Object Oriented Programming with Java
15.7 Probability Day 3. There are 2 nickels, 3 dimes, and 5 quarters 1.) Find the probability of selecting 1 nickel, 1 dime, and 1 quarter in that order.
Whiteboardmaths.com © 2004 All rights reserved
Counting Techniques 1. Sequential Counting Principle Section
Index Student Activity 1: Questions to familiarise students with the
Objects, Variables & Methods Java encapsulates data and action modules that access the data in one container, called an object. Object members that.
1 Bridge for Scholars 2009 Presentation 01 2 The deck The deck has 52 cards There are four suits: Clubs , Diamonds , Hearts, Spades  The lowest card.
Playing Cards Deck of 52 uniquely designed playing cards.
CS 3800 Su 11 Beg. IOS Dev L4 Obj C part 1 CS 3800 Introduction to IOS programming Summer 2011 G. Zimmerman.
Intro to Probability & Games
CS 106 Introduction to Computer Science I 11 / 08 / 2006 Instructor: Michael Eckmann.
Chapter 5 Black Jack. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 5-2 Chapter Objectives Provide a case study example from problem statement.
o Simulate a deck of playing cards o Shuffle the deck o Deal (5) cards into the hand o Turn over the first card o The user must guess whether the next.
o Simulate a deck of playing cards o Shuffle the deck o Deal 5 cards into the hand o Turn over the first card o The user must guess whether the next card.
VOCABULARY  Deck or pack  Suit  Hearts  Clubs  Diamonds  Spades  Dealer  Shuffle  Pick up  Rank  Draw  Set  Joker  Jack 
Refreshing Your Skills for Chapter 10.  If you flip a coin, the probability that it lands with heads up is 1/2.  If you roll a standard die, the probability.
CSS446 Spring 2014 Nan Wang.  To learn how to choose appropriate classes for a given problem  To understand the concept of cohesion  To minimize dependencies.
Classes CMPS Overview Terms Class vs instance Class definitions in various languags Access modifiers Methods Constants Separating definition and.
Black Jack MVC By Jeremy DiPaolo. Introduction Goal: To create a Black Jack game that takes advantage of the MVC framework. Uses many of the components.
Algorithms. What is an algorithm?  An algorithm is a clear, concise, and correct step- by-step sequence of actions.
Poker UML and ADT design plan.
Computer Science 111 Fundamentals of Programming I More Data Modeling.
Compound Probability Pre-AP Geometry. Compound Events are made up of two or more simple events. I. Compound Events may be: A) Independent events - when.
A Semantic Error in Google last weekend! Someone in Google typed an extra ‘/’ character into their URL List Link to CNN video report posted on Collab.
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.
Object Oriented Design. Object-Oriented Design Method for designing computer programs –Useful for thinking about large problems Consider “objects” interacting.
Poker. Basic card terminology Suits: Hearts, diamonds, clubs, spades Deuce, face cards.
15.3 Counting Methods: Combinations ©2002 by R. Villar All Rights Reserved.
Chapter 7 Arrays. A 12-element array Declaring and Creating Arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[]
What is the Purpose of This Class
Objective C. Основан на C Объектно-ориентированный Использует сообщения Динамический Протоколы Интроспекция.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
A Casino Simulator Program Using Advanced C++ Concepts Thomas H. Hand July 25 th, 2005 Software/Hardware Integration.
C Lecture Notes 1 Structures & Unions. C Lecture Notes Introduction Structures –Collections of related variables (aggregates) under one name Can.
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.
OBJECTIVE C Kurt Ladendorf. General Knowledge  Super set of C  Smalltalk  Mainly used for iOS and other Apple development.
CS 61B Data Structures and Programming Methodology July 8, 2008 David Sun.
 2000 Prentice Hall, Inc. All rights reserved Introduction Structures –Collections of related variables (aggregates) under one name Can contain.
StructureStructure. Outline Introduction Structure Definitions Initializing Structures Accessing Members of Structures Using Structures with Functions.
Introduction to Enumerations CMSC 202. Enumerated Values Enumerated values are used to represent a set of named values. Historically in Java (and other.
The Addition Rule.
Chapter 5 Black Jack.
Fundamentals of Programming I More Data Modeling
Fundamentals of Programming I More Data Modeling
Task 2 Implementation help
Homework Due Friday.
HOW TO PLAY POKER.
Presentation transcript:

Black Jack in Objective-C CS 355

Cards 52 cards in a standard poker deck Each card has a suit heart  spade  diamond  club  and a rank A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K

Card Interface (Card.h) #import <Foundation/Foundation.h> enum {HEART, SPADE, CLUB, DIAMOND}; enum {ACE=1, JACK=11, QUEEN=12, KING=13}; @interface Card : NSObject { @private int suit; // HEART, SPADE, DIAMOND, CLUB int rank; // ACE, 2, 3, …, 10, JACK, QUEEN, KING } -(id)init; -(id)initWithSuit:(int)s AndRank:(int)r; -(int) suit; -(int) rank; @end

Card Implementation (Card.m) #import "Card.h" @implementation Card -(id)init {return [self initWithSuit: SPADE AndRank: ACE];} -(id)initWithSuit:(int)s AndRank:(int)r { if ((self = [super init]) != nil) { suit = s; rank = r; } return self; -(int)suit {return suit;} -(int)rank {return rank;} @end

Designated Initializer -(id)initWithSuit:(int)s AndRank:(int)r { if ((self = [super init]) != nil) { suit = s; rank = r; } return self; Most specialized (has most parameters) Called by other initializers Proper chaining of initializers: First call parent class’s designated initializer, then initialize new instance variables

Accessors Note that instance variables are private. -(int)suit {return suit;} -(int)rank {return rank;} Note that instance variables are private. A card’s suit and rank are retrieved via getter methods Usually have the same name as instance variable. Note that Card’s are immutable since we do not provide any setter methods.

Creating a new card id card = [[Card alloc] init]; We first send an alloc message to the Card class object which creates a new instance. Then we send an init message to this newly created instance. It is important to capture the return value of the init method call, since it may return a different object then was created via alloc. The newly created card has a reference count of 1.

Black Jack Shoe In blackjack, a shoe is a device that can hold one to eight decks of cards from which the dealer can draw one card at time. When the shoe becomes sufficiently low, it is restocked and reshuffled.

Shoe.h #import <Foundation/Foundation.h> @interface Shoe : NSObject { @private int numDecks; id cards; // mutable array } -(id)initWithDeckCount:(int)n; -(id)init; -(void)dealloc; -(void)shuffle; -(id)deal; -(int)cardsLeft; -(void)reload; @end

Shoe initialization (id)initWithDeckCount:(int)n { if ((self = [super init]) != nil) { numDecks = n; cards = [[NSMutableArray alloc] initWithCapacity: n*52]; [self reload]; } return self;

Shoe destruction Release cards array. (void)dealloc { [cards release]; [super dealloc]; } Release cards array. Array releases each card Ends with call to superclass’s dealloc method.

Dealing cards from Shoe -(id)deal { if ([cards count] <= 0) return nil id card = [[cards lastObject] retain]; [cards removeLastObject]; return [card autorelease]; } Note that we retain the last card before we release it! We autorelease the card to safely perform the hand-off back to the caller!

Shuffling the Shoe -(void)shuffle { const int n = [cards count]; for (int i = 0; i < n; i++) { int j = (int) (drand48()*n); if (i != j) [cards exchangeObjectAtIndex: i withObjectAtIndex: j]; }

Hand A hand is the set of cards held by a player. A hand is valued by the sum of its cards: Aces worth 1 or 11 Face cards (Jack, Queen, King) are worth 10. A blackjack is a hand containing exactly two cards worth 21.

Hand.h #import <Foundation/Foundation.h> #import "card.h" @interface Hand : NSObject { @private id cards; } -(id)init; -(void)dealloc; -(void)empty; -(void)insertCard:(Card *)card; -(unsigned)numCards; -(unsigned)softCount; -(unsigned)hardCount; -(unsigned)count; -(BOOL)busted; -(BOOL)blackjack; -(NSEnumerator *)cardEnumerator; @end

Hand init and dealloc -(id)init { self = [super init]; if (self != nil) { cards = [[NSMutableArray alloc] initWithCapacity: 10]; } return self; -(void)dealloc { [cards release]; [super dealloc];

Inserting cards into and emptying a hand -(void)insertCard:(Card *)card { [cards addObject: card]; } -(void)empty { [cards removeAllObjects]; -(unsigned)numCards { return [cards count];

Soft Count Aces = 1 -(unsigned)softCount { NSEnumerator *e = [cards objectEnumerator]; id card; unsigned c = 0; while ((card = [e nextObject]) != nil) { int r = [card rank]; c += (r <= 10) ? r : 10; } return c;

Hard Count Aces = 11 -(unsigned)hardCount { NSEnumerator *e = [cards objectEnumerator]; id card; unsigned c = 0; while ((card = [e nextObject]) != nil) { int r = [card rank]; if (r == ACE) c += 11; else if (r <= 10) c += r; else // face card c += 10; } return c;

Count closest to 21 without busting -(unsigned)count { NSEnumerator *e = [cards objectEnumerator]; id card; unsigned c = 0; unsigned numAces = 0; while ((card = [e nextObject]) != nil) { int r = [card rank]; if (r == ACE) { c += 11; numAces++; } else c += (r <= 10) ? r : 10; } while (c > 21 && numAces > 0) { c -= 10; numAces--; return c;

Busted or Blackjack? -(BOOL)busted { return [self softCount] > 21; } -(BOOL)blackjack { return [cards count] == 2 && [self hardCount] == 21;

Plays by a fixed set of rules Player Hierarchy NSObject Player abstract base class Dealer Plays by a fixed set of rules Human Plays using human I/O Cyborg Plays using AI

Player Base Class typedef enum {HIT, STAY} Action; @interface Player : NSObject { @protected int bank; id hand; } -(id)initWithBank:(int)amount; -(void)dealloc; -(int)betAmount; -(int)bank; -(void)bankCredit:(int)amount; -(void)bankDebit:(int)amount; -(Action)action; -(void)insertCard:(Card *)card; -(int)score; -(BOOL)busted; -(BOOL)blackjack; -(void)empty; -(NSEnumerator *) cardEnumerator; @end

Player init and dealloc -(id)initWithBank:(int)amount { self = [super init]; if (self != nil) { bank = amount; hand = [[Hand alloc] init]; } return self; -(void)dealloc { [hand release]; [super dealloc];

Default player strategy -(int)betAmount {return bank;} // bet it all! -(Action)action { // mimic dealer return ([hand hardCount] < 17) ? HIT : STAY; }

Other default behavior -(int)bank {return bank;} -(void)bankCredit:(int)amount {bank += amount;} -(void)bankDebit:(int)amount {bank -= amount;} -(void)insertCard:(Card *)card { [hand insertCard: card]; } -(int)score {return [hand count];} -(BOOL)busted {return [hand busted];} -(BOOL)blackjack {return [hand blackjack];} -(void)reset {[hand empty];} -(NSEnumerator *) cardEnumerator { return [hand cardEnumerator];

The Dealer @interface Dealer : Player { @protected id shoe; } -(id)initWithDeckCount:(int)num; -(id)deal:(id)player; -(int)cardsLeft; -(void)reload; -(void)shuffle; @end

Dealer init and dealloc -(id)initWithDeckCount:(int)num { self = [super initWithBank: 0]; // has no bank if (self != nil) { shoe = [[Shoe alloc] initWithDeckCount: num]; } return self; -(void)dealloc { [shoe release]; [super dealloc];

Dealer methods -(id)deal:(id)player { id card = [shoe draw]; if (player != nil) // player == nil => burn card [player insertCard: card]; return card; } -(int)cardsLeft {return [shoe cardsLeft];} -(void)restock {[shoe restock];} -(void)shuffle {[shoe shuffle];} // inherits action strategy (and other behavior) from Player

Table Dealer Is a player Has shoe 1 to 7 Players

Table.m Dealer and 1 to 7 Players @interface Table : NSObject { @private id dealer; id players; // mutable array } -(id)initWithDeckCount:(int)num; -(void)dealloc; -(int)numPlayers; -(void)addPlayer:(id)player; -(void)removePlayer:(id)player; -(id)dealer; -(NSEnumerator *)playerEnumerator; @end

Cyborg.h An Example Player AI @interface Cyborg : Player { // no new instance vars } -(int)betAmount; -(Action)action; @end

Cyborg method overrides -(int)betAmount { int amount = (int) (50*drand48()); if (amount > bank) amount = bank; return amount; } -(Action)action { return ([hand softCount] < 18) ? HIT : STAY;

Human.h Human Player @interface Human : Player { // no new instance vars } -(int)betAmount; // get from user -(Action)action; // get from user @end