Programs to Complete: Cards

Program Cards, as it stands, alternately selects a playing card for the user and the computer and compares their values. You could develop the program in several ways:

  • Keep a tally of the number of wins, losses and draws.
  • Turn it into a game of snap by allowing the user a fixed response time (using the time function) in order to 'beat the computer'.
  • Allow the computer to pick a hand of, say, 5 cards for itself and for the user. It could then examine each hand for runs, flushes, n of a kind etc.
  • Pick four hands of thirteen cards and sort them by suit and value.
program Cards;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  CardUsed : array [1..52] of Boolean;
  Round, MaxRounds, PlayerValue, ComputerValue : integer;
  PlayerCard, ComputerCard : string;

procedure Draw(var Card : string; var Value : integer);
var
  Rank, Suit : string;
  CardNumber : integer;
begin
  //Select unused card
  repeat
    CardNumber := random(52) + 1;
  until CardUsed[Cardnumber] = False;
  CardUsed[Cardnumber] := True;
  //Allocate the suit using its character
  case CardNumber of
    1..13  : Suit := CHR(3);
    14..26 : Suit := CHR(4);
    27..39 : Suit := CHR(5);
    40..52 : Suit := CHR(6);
  end;
  //Allocate the card type (Rank) and value
  CardNumber := CardNumber mod 13;
  case CardNumber of
    0 :       begin
                Rank := 'K';
                Value := 13;
              end;
    1 :       begin
                Rank := 'A';
                Value := 14;
              end;
    2 .. 10 : begin
               Rank := inttostr(CardNumber);
               Value := CardNumber;
              end;
    11 :      begin
                Rank := 'J';
                Value := 11;
              end;
    12 :      begin
                Rank := 'Q';
                Value := 12;
              end;
  end;
  Card := Rank + Suit;
end;

procedure Deal;
begin
  draw(PlayerCard, PlayerValue);
  writeln('This is your card: ', PlayerCard);
  writeln;
  sleep(1000);
  draw(ComputerCard, ComputerValue);
  writeln('This is the computer''s card: ', ComputerCard);
  sleep(1000);
  writeln;
  if PlayerValue > ComputerValue then
    writeln('***Well done, you won!***')
  else
    if ComputerValue > PlayerValue then
       writeln('***Unlucky, you lost!***')
    else writeln('***Even Stevens, you drew!***');
  sleep(1000);
end;

begin
  randomize;
  Round :=0;
  writeln('*****Welcome to the High Card Game!*****');
  writeln;
  write('Enter the number of times you wish to play: ');
  readln(MaxRounds);
  writeln;
  repeat
    Round := Round + 1;
    writeln('<<Round ', Round,'>>');
    writeln('Press ENTER to draw a card!');
    readln;
    Deal;
    writeln;
  until Round = MaxRounds;
  readln;
end.

Programming - a skill for life!

Unfinished programs for you to complete