Lecture P9: WAR Card Game

Similar documents
UNDERGROUND TONK LEAGUE

CmpSci 187: Programming with Data Structures Spring 2015

POKER LOTTO LOTTERY GAME CONDITIONS These Game Conditions apply, until amended or revised, to the POKER LOTTO lottery game.

recursion, O(n), linked lists 6/14

Mathematical Card Tricks

Poker. 10,Jack,Queen,King,Ace. 10, Jack, Queen, King, Ace of the same suit Five consecutive ranks of the same suit that is not a 5,6,7,8,9

There are a number of superb online resources as well that provide excellent blackjack information as well. We recommend the following web sites:

Combinatorics 3 poker hands and Some general probability

The cloth covering a Three Card Poker 6 Card Bonus table (the layout) shall have wagering areas for eight players.

Math 728 Lesson Plan

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

1. Shuffling Machine: Cards used to play Casino War shall be dealt from an automatic card shuffling device ( shuffler ).

Ready, Set, Go! Math Games for Serious Minds

Acing Math (One Deck At A Time!): A Collection of Math Games. Table of Contents

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Current California Math Standards Balanced Equations

players on one side of the table and a place for the dealer on the opposite side.

(b) You draw two balls from an urn and track the colors. When you start, it contains three blue balls and one red ball.

Texas Hold em. From highest to lowest, the possible five card hands in poker are ranked as follows:

1 Bet Threat Texas Hold Em Gaming Equipment Rules of the Games Temporary Amendments: N.J.A.C. 19:40-1.2; and 19: , 1.18 and 1.

Lecture 12 Doubly Linked Lists (with Recursion)

LECTURE 3. Probability Computations

Stacks. Linear data structures

CARD RPG ADVANCED. Based on CardRPG originally created by Ray of Ash Edited by Stephen A. Rogers

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

Fundamentals of Probability

How to Play. Player vs. Dealer

C ontents. Introduction

9 Video Poker Paytables in 1 Game Ultimate X Ten Play Draw Poker provides a rich selection of the most popular video poker paytables:

Queues. Manolis Koubarakis. Data Structures and Programming Techniques

Worldwide Casino Consulting Inc.

Lecture Notes on Binary Search Trees

Clock Arithmetic and Modular Systems Clock Arithmetic The introduction to Chapter 4 described a mathematical system

Book One. Beginning Bridge. Supplementary quizzes and play hands edition

Bayesian Tutorial (Sheet Updated 20 March)

Practical Probability:

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

CS 341 Software Design Homework 5 Identifying Classes, UML Diagrams Due: Oct. 22, 11:30 PM

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Analysis of a Search Algorithm

Data Structures. Topic #12

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

Conditionals: (Coding with Cards)

Probabilities of Poker Hands with Variations

by Teresa Evans Copyright 2005 Teresa Evans. All rights reserved.

Lab 11. Simulations. The Concept

1. General Black Jack Double Deck Black Jack Free Bet Black Jack Craps Craps Free Craps...

Lecture Notes on Binary Search Trees

Fruit Machine. Level. Activity Checklist Follow these INSTRUCTIONS one by one. Test Your Project Click on the green flag to TEST your code

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

The temporary new rules and amendments authorize casino licensees to. offer a supplemental wager in the game of three card poker known as the three

LIVE CASINO 1. ROULETTE GAME RULES. 1.1 Game Overview. 1.2 How to Play. 1.3 Bet Type Explanation

Linked Lists Linked Lists, Queues, and Stacks

DATA STRUCTURE - STACK

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Hoover High School Math League. Counting and Probability

CP Lab 2: Writing programs for simple arithmetic problems

Math Games For Skills and Concepts

Sequential lmove Games. Using Backward Induction (Rollback) to Find Equilibrium

$ ( $1) = 40

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

Sequential Data Structures

Champion Poker Texas Hold em

Discrete Mathematics and Probability Theory Fall 2009 Satish Rao, David Tse Note 10

Standards of play: Type of gaming table utilized for this game:

BEGINNER S BRIDGE NOTES. Leigh Harding

Sources: On the Web: Slides will be available on:

Curriculum Design for Mathematic Lesson Probability

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Special Notice. Rules. Weiss Schwarz Comprehensive Rules ver Last updated: October 15 th Outline of the Game

THE 101 CASINO BLACKJACK X with BUSTER BLACKJACK BONUS BET v1.2

8.3 Probability Applications of Counting Principles

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Lecture 2: Data Structures Steven Skiena. skiena

Contemporary Mathematics Online Math 1030 Sample Exam I Chapters No Time Limit No Scratch Paper Calculator Allowed: Scientific

Common Data Structures

Using games to support. Win-Win Math Games. by Marilyn Burns

PES Institute of Technology-BSC QUESTION BANK

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Ecology and Simpson s Diversity Index

Standard 12: The student will explain and evaluate the financial impact and consequences of gambling.

2.5 Conditional Probabilities and 2-Way Tables

14 Model Validation and Verification

The game also features three optional bonus bets.

Class Notes CS Creating and Using a Huffman Code. Ref: Weiss, page 433

Lecture Notes on Stacks & Queues

Introduction to Programming II Winter, 2014 Assignment 2

Math 141. Lecture 2: More Probability! Albyn Jones 1. jones/courses/ Library 304. Albyn Jones Math 141

10CS35: Data Structures Using C

COS 217: Introduction to Programming Systems

Casino Control (3 Card Poker) Approval 2006 (No 1)

Virtual Servers. Virtual machines. Virtualization. Design of IBM s VM. Virtual machine systems can give everyone the OS (and hardware) that they want.

Intro to Simulation (using Excel)

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Transcription:

Overview Lecture P9: WAR Card Game Write a program to play the card game "War." Goals. Practice with linked lists and pointers. Appreciate the central role played by data structures. Learn how to design a "large" program. Learn how to read a "large" program. 3 WAR Demo Before You Write Any Code Rules of the game. Each player is dealt half of the cards. Each player plays top card. whichever is higher captures both cards in event of tie, WAR Repeat until one player has all the cards. Determine a high-level view of the code you plan to write. Break it up into manageable pieces. Create the deck of cards. Shuffle the cards. Deal the cards. Play the game. WAR demo. Determine how you will represent the data. The cards. The deck. The hands. 4 5

Representing The Cards Represent 52 cards using an integer between 0 and 51. Representing The Cards Represent 52 cards using an integer between 0 and 51. War if (rank(c1) == rank(c2)) Clubs Diamonds Hearts Spades Card # 2 0 3 1 4 2.. K 11 A 12 Card # 2 13 3 14 4 15.. K 24 A 25 Card # 2 26 3 27 4 28.. K 37 A 38 Card # 2 39 3 40 4 41.. K 50 A 51 Card type typedef int Card; int rank(card c) { return c % 13; int suit(card c) { return (c % 52) / 13; 46 = 3 * 13 + 9 12 c % 52 to allow for multiple deck war 6 7 Representing The Cards Testing the Code void showcard(card c) { switch (rank(c)) { case 0: printf("deuce of "); break; case 1: printf("three of "); break; Card type case 12: printf("ace of " ); break; switch (suit(c)) { case 0: printf("clubs\n"); break; case 1: printf("diamonds\n"); break; case 2: printf("hearts\n"); break; case 3: printf("spades\n"); break; war.c (test code) #include <stdio.h> #define DECKSIZE 52 typedef int Card; int rank(card c) {... int suit(card c) {... void showcard(card c) {... int main(void) { Card c; for (c = 0; c < DECKSIZE; c++) showcard(c); return 0; % gcc war.c % a.out Deuce of Clubs Three of Clubs Four of Clubs Five of Clubs Six of Clubs Seven of Clubs Unix King of Spades Ace of Spades 8 9

Representing the Deck and Hands Representing the Deck and Hands Use a linked list to represent the deck and hands. Use a linked list to represent the deck and hands. standard linked list structure maintain pointer to first and last card in A s pile represent a pile of cards typedef struct node* link; struct node { Card card; link next; ; link Atop, Abot; link Btop, Bbot; Why use linked lists? Draw cards from the top, captured cards go to bottom. need direct access to top and bottom cards no need for direct access to middle cards Gain practice with linked lists. Atop Abot Atop Abot K 2 J Q 5 NULL K 2 J Q 5 NULL 10 11 Showing a Hand Showing a Hand Use printf() method for debugging. May need to build supplemental functions to print out contents of data structures. Print out contents of player s hand. Use printf() method for debugging. May need to build supplemental functions to print out contents of data structures. Print out contents of player s hand. Count number of cards in player s hand. showpile( ) countpile( ) standard linked list traversal void showpile(link pile) { link x; for (x = pile; x!= NULL; x = x->next) showcard(x->card); standard linked list traversal int countpile(link pile) { link x; int cnt = 0; for (x = pile; x!= NULL; x = x->next) cnt++; return cnt; 12 13

Creating the Deck Creating the Deck Goal: create a 52 card deck. Need to dynamically allocate memory. Good programming practice to write helper function to allocate memory and initialize it. needed for malloc() allocate memory malloc() failed initialize node NEWnode( ) #include <stdlib.h> link NEWnode(Card card, link next) { link x; x = malloc(sizeof *x); if (x == NULL) { printf("out of memory.\n"); exit(exit_failure); x->next = next; x->card = card; return x; Goal: create a 52 card deck. Need to dynamically allocate memory. x is link to top of pile add next card to top of pile link makepile(int N) { link x = NULL; Card c; for (c = N - 1; c >= 0; c--) x = NEWnode(c, x); return x; makepile( ) 14 15 Testing the Code Dealing #include <stdio.h> #include <stdlib.h> #define DECKSIZE 52 war.c typedef int Card; [ rank(), suit(), showcard() ] typedef struct node* link... link NEWnode(Card card, link next) {... link makepile(int N) {... link showpile(link pile) {... int main(void) { link deck; deck = makepile(decksize); showpile(deck); return 0; % gcc war.c % a.out Deuce of Clubs Three of Clubs Four of Clubs Five of Clubs Six of Clubs Seven of Clubs Unix King of Spades Ace of Spades Deal cards one at a time. Input: deck of cards (linked list). Creates: two new linked lists for players A and B. global variable Atop, Btop point to first node global variable Abot, Bbot point to last node Does not create (malloc) new nodes. K 2 J Q 5 NULL d 16 17

Dealing Code Testing the Code handle first card of each pile assumes deck has even # cards mark end of piles deal( ) void deal(link d) { Atop = d; Abot = d; d = d->next; Btop = d; Bbot = d; d = d->next; while (d!= NULL) { Abot->next = d; Abot = d; d = d->next; Bbot->next = d; Bbot = d; d = d->next; Abot->next = NULL; Bbot->next = NULL; war.c as before link Atop, Abot, Btop, Bbot; void deal(link d) {... int main(void) { link deck; deck = makepile(decksize); deal(deck); printf("player A\n"); showpile(atop); printf("\nplayer B\n"); showpile(btop); return 0; Unix % gcc war.c % a.out PLAYER A Deuce of Clubs Four of Clubs Six of Clubs King of Spades PLAYER B Three of Clubs Five of Clubs Seven of Clubs Ace of Spades 18 19 Shuffling the Deck Shuffle the deck. Disassemble linked list elements and put into an array. Shuffle array elements (using algorithm from Lecture P3). Reassemble linked list from shuffled array. 2 3 4 5 6 7 8 9 NULL Array index 0 1 2 3 4 5 6 7 Value 2 3 4 5 6 7 8 9 Array index 0 1 2 3 4 5 6 7 Value 4 6 9 2 8 7 5 3 4 6 9 2 8 7 5 3 NULL Shuffling the Deck link shufflepile(link pile) { int i, n; link x; link a[decksize]; for (x = pile, n = 0; x!= NULL; x = x->next, n++) a[n] = x; shuffle(a, n); for (i = 0; i < n - 1; i++) a[i]->next = a[i+1]; a[n-1]->next = NULL; return a[0]; shuffle pile of cards shuffle array elements reassemble linked list 20 21

Testing the Code Peace Code as before war.c int randominteger(int n) { void shufflepile(link pile) {... int main(void) { link deck; deck = makepile(decksize); deck = shufflepile(deck); deal(deck); printf("player A\n"); showpile(atop); printf("\nplayer B\n"); showpile(btop); return 0; Unix % gcc war.c % a.out PLAYER A Eight of Diamonds Ten of Hearts Four of Clubs Nine of Spades PLAYER B Jack of Hearts Jack of Clubs Four of Diamonds Ten of Clubs Until a player loses A wins B wins war.c void play (void) { int Aval, Bval; link Ttop, Tbot; while ((Atop!= NULL) && (Btop!= NULL)) { Aval = rank(atop->card); Bval = rank(btop->card); Ttop = Atop; Tbot = Btop; Atop = Atop->next; Btop = Btop->next; Ttop->next = Tbot; Tbot->next = NULL; if (Aval > Bval) { if (Atop == NULL) Atop = Ttop; else Abot->next = Ttop; Abot = Tbot; else { if (Btop == NULL) Btop = Ttop; else Bbot->next = Ttop; Bbot = Tbot; 22 24 "Peace" (war with no wars). Game Never Ends Starting point for implementation. Assume player B wins if a tie. What should happen?! Intuitively, B has an advantage, so should usually win. What actually happens?! Game "never" ends for many (almost all) deals. Why? 5 3 NULL 2 4 NULL What actually happens? One Bit of Uncertainty Game "never" ends for many (almost all) deals. Proper use of randomization is vital in simulation applications. Randomly exchange two cards in battle when picked up. if (randominteger(2) == 1) { Ttop = Atop; Tbot = Btop; else { Ttop = Btop; Tbot = Atop; exchange cards randomly Ten Typical Games B wins in 446 steps. A wins in 404 steps. B wins in 330 steps. B wins in 1088 steps. B wins in 566 steps. B wins in 430 steps. A wins in 208 steps. B wins in 214 steps. B wins in 630 steps. B wins in 170 steps. 25 30

Add code to handle ties. Add Code for War Insert in play() before if (Aval > Bval) while not if to handle multiple wars A s war card add WARSIZE cards to temporary pile B s war card while (Aval == Bval) { for (i = 0; i < WARSIZE; i++) { if (Atop == NULL) return; Tbot->next = Atop; Tbot = Atop; Atop = Atop->next; Aval = rank(tbot->card); for (i = 0; i < WARSIZE; i++) { if (Btop == NULL) return; Tbot->next = Btop; Tbot = Btop; Btop = Btop->next; Bval = rank(tbot->card); Tbot->next = NULL; Answer Q. "So how long does it take?" A. "About 10 times through deck (254 battles)." Q. "How do you know?" A. "I played a million games." Ten Typical Games B wins in 60 steps. A wins in 101 steps. B wins in 268 steps. A wins in 218 steps. B wins in 253 steps. A wins in 202 steps. B wins in 229 steps. A wins in 78 steps. B wins in 84 steps. A wins in 654 steps. 31 32 Steps 800 600 400 200 0 Answer Q. "That sounds like fun." A. "Let s try having bigger battles." Average # of Steps in War 0 1 2 3 4 5 6 7 8 9 War Size Problems With Simulation Doesn t precisely mirror game. Deal allocates piles in reversed order. People pick up cards differently. "Sort-of" shuffle prize pile after war? Separate hand and pile. could have war as pile runs out Our shuffling produces perfectly random deck. (modulo "randomness" of rand()) Tradeoffs. Convenience for implementation. Fidelity to real game. Such tradeoffs are typical in simulation. Try to identify which details matter. 33 34

War Using Queue ADT War Using Queue ADT Use first class queue ADT. Why queue?! Always draw cards from top, return captured cards to bottom. Queue A, B; deal( ) void deal(queue Deck) { A = QUEUEinit(); B = QUEUEinit(); while (!QUEUEisempty(Deck)) { QUEUEput(A, QUEUEget(Deck)); QUEUEput(B, QUEUEget(Deck)); Use first class queue ADT. Why queue?! Always draw cards from top, return captured cards to bottom. peace.c void play(queue A, Queue B) { Card Acard, Bcard; Queue T = QUEUEinit(); while (!QUEUEisempty(A) &&!QUEUEisempty(B)) { Acard = QUEUEget(A); Bcard = QUEUEget(B); QUEUEput(T, Acard); QUEUEput(T, Bcard); if (rank(acard) > rank(bcard)) while (!QUEUEisempty(T)) QUEUEput(A, QUEUEget(T)); else while (!QUEUEempty(T)) QUEUEput(B, QUEUEget(T)); 35 36 War Using Queue ADT Summary Use first class queue ADT. Why queue?! Always draw cards from top, return captured cards to bottom. Advantages:! Simplifies code.! Avoids details of linked lists. Disadvantage:! Adds detail of interface. How to build a "large" program? Use top-down design. Break into small, manageable pieces. Makes code: easier to understand easier to debug easier to change later on Debug each piece as you write it. Good algorithmic design starts with judicious choice of data structures. How to work with linked lists? Draw pictures to read and write pointer code. 37 38