A game of poker
Download the code of the game of poker in the So-o folder:
- So-o
- So-o.php
- OL.php
- Object.php
- ...
- poker
- poker.php
- Card.php
- Hand.php
- Deck.php
- ...
In the folder poker, run the program poker.php:
$ php -f poker.php
3h,4h,4s,Jd,6c -> ONEPAIR
Keep (1-5...)? 23
You have one pair. The program asks which cards you wish to keep. Enter 23 to keep the second and the third card and draw 3 new cards. The program displays the result of the second draw:
Js,4h,4s,Ks,4c -> THREEOFKIND
Play or (q)uit?
You have a three of a kind. Press Enter to play again:
3c,Ah,2s,7d,3d -> ONEPAIR
Keep (1-5...)? 15
3c,5h,3s,5d,3d -> FULLHOUSE
Play or (q)uit? q
Enter q to quit the program.
CODE
- set_include_path(dirname(getcwd()) . PATH_SEPARATOR . getcwd());
Sets the PHP configuration parameter include_path
to the current directory and the directory containing the So-o code.
- require_once 'So-o.php';
- require_once 'Deck.php';
Loads So-o and the Deck class.
- $deck=sendmsg($Deck, 'new', true);
- sendmsg($deck, 'shuffle');
Creates a deck of cards which is automatically shuffled when all the cards have been drawn. Shuffles the deck.
- $stdin = fopen('php://stdin', 'r');
Opens the keyboard to interact with the user.
- do {
Plays one turn indefinitely until the user exits the game.
- }
- while (true);
- fclose($stdin);
Closes the keyboard before quitting the program.
- $hand=sendmsg($deck, 'hand');
- sendmsg($hand, 'print', true);
Draws a hand of five cards and displays it.
- echo 'Keep (1-5...)? ';
- $line = fgets($stdin);
- if ($line === false) {
- break;
- }
- trim($line);
Asks the user which cards are to be kept. Reads the answer from the keyboard. Quits if the input is closed.
- $keep=array_fill(1, 5, false);
- preg_match_all('/\d/', $line, $r);
- foreach ($r[0] as $n) {
- if ($n >=1 and $n <= 5) {
- $keep[$n]=true;
- }
- }
Fills the array of five booleans $keep
, one for each card, with false
then with true
for each card which must be kept.
- for ($i=1; $i <= 5; $i++) {
- if (!$keep[$i]) {
- sendmsg($hand, 'setCard', $i, sendmsg($deck, 'deal'));
- }
- }
- sendmsg($hand, 'print', true);
Redraws a card for each card which isn't kept. Displays the hand.
- echo 'Play or (q)uit? ';
- $line = fgets($stdin);
- if ($line === false) {
- break;
- }
- trim($line);
- if ($line[0] == 'q' or $line[0] == 'Q') {
- break;
- }
Asks the user if she wants to play again or quit the game. Quits the game if the awswer starts with q or Q or if the input is closed.
Comments