~ Introduction to Programming: Pascal ~

Session 13 - Sample Exam and more on Procedures

<<  Back to Contents Page 

Unit 14 – The Exam; Command Summary

 During the course of this session, we will be looking at the assignment set over Christmas, which is repeated below for your convenience. We will look at how it was approached, and also some watch-points when doing the exam. 

Christmas Assignment

9531 – INTRODUCTORY COMPUTER PROGRAMMING – STRUCTURED ASSIGNMENT

Assignment Details

Topic:                          Games and Quizzes

Title of this Assignment:                      Higher or Lower game

Introduction

The purpose of this assignment is to write a program to generate a number from 1 to 10, then prompt the user to guess whether the next generated number will be higher or lower, keeping a score which is increased by 1 for a correct guess. A high score is kept with a name.

Assignment Specification

Write a program, which generates a random number between 1 and 10, and prompts the user to press H for higher or L for lower or X for Exit.

If the next number generated by the computer is as the user guessed, then increase a score variable by one. If the guess is wrong, end the game.

Maintain a high score variable (initially set to 0) which, if the score after the game is higher than the current high-score value, is set to the new value, displaying a congratulatory message to the user on the screen, and prompting for the user’s name.

Thereafter, at the end of each game, a message is displayed stating what the score for the last game was, what the high score is, and what the name of the high-score holder is.

At this point, ask the user if he or she wishes to play again. If Y is pressed, go back to the beginning, resetting the score, but maintaining the high score and high score holder name variables. If N is pressed, show a goodbye message, ask the user to press a key, wait until a key is pressed, and then exit the program

Procedure

a)       Describe briefly in writing for a possible user

i)                     The purpose of your program

ii)                   The limitations of your program

b)       Construct (on paper) a screen layout indicating what will appear on the screen – prompts, input, output with annotations, any other messages.

c)       Describe (on paper) the main stages of the program - by means of a flowchart or an alternative technique.

d)       Produce a listing of the program.  This should have adequate comment lines and should demonstrate to the examiner that the program solves the problem set.

e)       Include in the program statements to display adequate instruction to the user of the program – e.g. prompts for data entry and appropriate error messages for invalid input.

f)         Key in and run the program, producing and using simple test data if necessary. Check that the program's output agrees with the expected results and correct any errors.

g)       Use appropriate language facilities.

 

Working through the exam question

1.      Read through the introduction to get an overall idea of what is required.

2.      Read through the Assignment specification to get an idea of how the program should operate, and what it should include.

3.      Read through the Procedure, and get an idea in your mind about what is required of you, and how each section relates to the Specification.

4.      Read through the Specification again. This time, as you go, separate out the following information:-

a.      A brief description of the program's function, as seen from the user's perspective

b.      What will be displayed on the screen

c.      What information needs to be taken from the user (this will need to be stored in variables)

d.      What information is generated by the computer (either by working on other information given by the user, or generated without user input)

e.      List the main actions that need to be taken in the program as boxes joined together by a line. This forms the basis for your JSP diagram.

f.        Break down these actions into smaller actions using JSP techniques. Identify where the program goes back to an earlier stage – this will indicate a loop. There will be a condition that will indicate how to exit the loop (i.e. carry on and not go back to an earlier stage).

a) i) User's Description

When thinking about what the user needs to know, strip out any technical jargon and focus on the purpose of the program – e.g.

This program works rather like a number of popular TV quiz shows where you, the player, are given a number between 1 and 10 and must decide whether the next number given to you will be higher or lower. You are scored on the number of correct guesses, and your (or any other competing players') highest score is kept with your name, for you to beat next time!

b) Screen Display

Reading through the Assignment specification, we can give a sequence of events, and thus screen displays, that will occur in the program:-

1.      Random number will be displayed on the screen
First Number is 3

2.      Computer prompts whether user should go higher or lower:-
Press H for Higher, L for Lower or X to Exit

3.      If the user chooses H then the following would be displayed:-
You chose Higher than a 3

4.      If the user chooses L then the following would be displayed:-
You chose Lower than a 3

5.      If the user chooses X then go to step 10

6.      In order to determine whether the next number is higher or lower, the next number will need to be generated.
Next Number is 5

7.      If the user was correct (i.e. next number generated is higher or lower), then the following message could be displayed:-
You guessed correctly.

8.      If the user chose incorrectly then show the following message, and go to step 10 :-
You were wrong! Sorry!

9.      The program would loop back to step 2.

10. The score is displayed on the screen at the end of the game:-
Game Over – Your score was 3.

11. If a new high score was achieved, the following message would be displayed:-
A New High Score was achieved. It was 2, but you scored 3. Well done!
Enter your name: SIMON

12. The user would enter their name.

13. Whether or not the high score was achieved, the following would be displayed:-
High score is 3, and is held by SIMON.
Would you like another game (Y for Yes, or N for No)?

14. If user presses Y for Yes, screen is cleared, and go back to step 1.

15. If user presses N then the following message is displayed:-
Goodbye. Thank you for playing this game.

By breaking this down, we start getting an idea of what needs to be stored, where the loops are, and how the program will be structured.

Data Storage

If we read through the previous section, we can see that the following information needs to be stored and used for the program to work correctly. Note that this is not something in the procedure, but you need to think about this before writing your program :-

§         Generated Number – e.g. call CurrentNumber. This is a number between 1 and 10 and can be a whole number, thus it can be stored in an Integer.

§         Next Number – e.g. call NextNumber. This is the number between 1 and 10 and can also be an integer. It is used to compare with the previous number (CurrentNumber) to see whether or not the user chose correctly Higher or Lower. Note that the CurrentNumber now becomes the NextNumber.

§         Keyboard response – i.e. when choosing Higher or Lower or Exit (H/L/X) and when choosing Yes or No to go again (Y/N). These are single-character responses (i.e. press a key on the keyboard), so it can be stored in a Char variable. Call this ch

§         The score needs to be maintained during the length of the game – as a score of 1 is given for each correct guess, this can be stored in an Integer variable. Call this Score

§         The high score needs to be maintained throughout the life of the program – as it is a copy of the best score, this can be stored in an Integer variable too. Call this HighScore

§         The name of the high scorer also needs to be stored. It would make sense to store this as a String. Let's call this HighScorerName

a) ii) Assumptions / Restrictions

From this, we can see that we are making a number of assumptions that restrict the functionality of the program – e.g.

§         The high score is lost at the end of the program – it is not stored it in a file or similar permanent storage.

§         If the current number generated is the same as the prior number generated (e.g. the computer selects a 5 and then another 5), this will not be higher or lower. It is assumed that this is treated as the user making an incorrect choice. An alternative may have been to keep selecting a random number between 1 and 10 in a loop until the number selected is not the same as the previous number selected.

§         As the high score is reset each time, the high scorer name and number will be set to an arbitrary value at the beginning of the program – e.g. No High Scorer for the name and 0 for the score.

§         The compute can only generate a number between 1 and 10. To increase levels of difficulty, it could have been that the program started from 1 to (say) 20, and decreased this range by 1 each time to decrease the likeliness that the user will give a correct answer. This would introduce an increasing challenge as the game progresses. Perhaps in a future version?

d) Stages of program

A JSP diagram can be built – the specification and the display output are good places to start. In honesty, you will probably need to do some jotting on a notepad, and work through possibly more than one piece of paper until you come up with a good structure. You should then copy this to be your final diagram to be submitted. Think in terms of where your loops are – these will typically have child boxes that describe what goes on within the loop. Be careful of loops within loops – e.g. the game is one loop, but there is another loop which allows the player to go back and play another game (and thus the score gets reset), maintaining the high score / scorer name. 

 

 

   

 

 

 

 

 

 

 The whole section is new random no < old could be vastly simplified if you do not wish to go into every part of the logic involved – e.g.

 

 

 

 

 

 

e) Create program – generate listing

From this structure (starting from the top) it is possible to devise your program. Here are two versions – one that doesn't use procedures, and one that does (following the structure). You will receive more marks for using procedures where appropriate, but if you do not yet feel confident to do so, you may wish to follow the version without.

 No procedures version

program HigherLower;

{ Game to choose a higher or lower value.
  Written by Simon Huggins, 8th January 2002 }

{ Included libraries }
uses Crt;

{ Global Variable Declarations }
var CurrentNumber,NextNumber:integer;
    Score,HighScore:integer;
    HighScorerName:String;
    ch:Char;

begin {Program}

  { Set up high score / name }
  HighScore := 0;
  HighScorerName := 'No High Scorer';

  { New Game Loop }
  repeat

    { Reset score to zero for new game }
    Score := 0;

    { Generate first random number between 1 and 10}
    Randomize;
    CurrentNumber := Random(10) + 1;

    { Display heading and first random number }
    ClrScr;
    WriteLn('Higher or Lower Game');
    WriteLn('--------------------');
    WriteLn;
    WriteLn('First Number is ',CurrentNumber);

    { Main Loop - exits if user chooses X or incorrect guess given }
    repeat
      WriteLn;

      { Prompt user for H for Higher, L for Lower or X to finish game }
      repeat
        Write('Press H for Higher, L for Lower or X to Exit: ');
        ch:=UpCase(ReadKey);
        WriteLn(ch);
      until (ch='H') or (ch='L') or (ch='X');

      { Carry on with game loop only if X was not chosen }
      if (ch<>'X') then
      begin

        { Display user's choice }
        Write('You chose ');
        if (ch='H') then Write('Higher') else Write('Lower');
        Write(' than a ',CurrentNumber); WriteLn;

        { Generate and display the next random number }
        NextNumber := Random(10)+1;
        WriteLn('Next Number is ',NextNumber); WriteLn;

        { Check whether guess was correct }
        if ((ch='H') and (NextNumber > CurrentNumber)) or
           ((ch='L') and (NextNumber < CurrentNumber)) then
        begin
          { Correct, so increase score and display message.
            Also store the new number as the current number. }
          Score := Score + 1;
          CurrentNumber := NextNumber;
          WriteLn('You guessed correctly.')
        end
        else
        begin
          { Otherwise incorrect, so exit loop by pretending
            X was pressed }
          ch := 'X';
          WriteLn('You were wrong! Sorry!');
        end;

      end;

    until (ch='X'); { X was chosen or incorrect answer given }

    { Display game over message }
    WriteLn('Game Over - Your score was ',Score);
    WriteLn;

    { Check for new high score }
    if(Score > HighScore) then
    begin
      { Show old/new high score, and get high scorers name }
      WriteLn('A new High Score was achieved.');
      WriteLn('It was ',HighScore,' but you scored ',Score,'. Well Done!');
      Write('Enter your name: ');
      ReadLn(HighScorerName); WriteLn;
      HighScore := Score;
    end;

    { Display high scorer details }
    WriteLn('High score is ',HighScore,
            ', and is held by ',HighScorerName,'.'); WriteLn;

    { Ask user if wants another game - must press Y or N }
    repeat
      Write('Would you like another game (Y for Yes, or N for No)? ');
      ch:=UpCase(ReadKey);
      WriteLn(ch);
    until (ch='Y') or (ch='N');

  until ch = 'N';

  { Finish Message }
  WriteLn; WriteLn('Goodbye. Thank you for playing this game.');
  WriteLn('Press a key to finish.');
  readKey;

end.

Note the use of indentation – every time either a loop or other block of code is started, the following instructions are indented two spaces (some people use three or four spaces). When the block or loop ends, the indent is made two spaces less.

Note also the use of comments (start with a { and end with a }) to show what each part of the program does. This makes it easy to relate to the JSP diagram, and also makes it easy to follow what the program is doing and why it is doing it.

You will be marked on style and clarity of your program, so it is worth practicing this.

 Procedures version

 Below is the procedures version. Note how closely it matches the breakdown of the JSP diagram. The use of procedures allows us to do this.

program HigherLower;

{ Game to choose a higher or lower value.
  Written by Simon Huggins, 8th January 2002 }

{ Included libraries }
uses Crt;

{ Global Variable Declarations }
var HighScore:integer;
    HighScorerName:String;

  procedure SetUpHighScore;
  begin
    { Set up high score / name }
    HighScore := 0;
    HighScorerName := 'No High Scorer';
  end;

  { New Game Loop }
  function NewGame : char;

    { Variables available only in NewGame function }
    var ch:Char;
        Score : integer;
        CurrentNumber,NextNumber:integer;

    { Display title for beginning of game }
    procedure DisplayTitle;
    begin
      ClrScr;
      WriteLn('Higher or Lower Game');
      WriteLn('--------------------');
      WriteLn;
    end;

    { Generate random number between 1 and 10}
    procedure RandomNumber(msg:String);
    begin
      CurrentNumber := Random(10) + 1;
      WriteLn(msg,' ',CurrentNumber);
    end;

    { Main Loop - exits if user chooses X or incorrect guess given }
    function MainLoop:Char;

      { Prompt user for H for Higher, L for Lower or X to finish game }
      procedure GetUserChoice;
      begin
        repeat
          Write('Press H for Higher, L for Lower or X to Exit: ');
          ch:=UpCase(ReadKey);
          WriteLn(ch);
        until (ch='H') or (ch='L') or (ch='X');
        end;

      { Display user's choice }
      procedure DisplayUserChoice;
      begin
        Write('You chose ');
        if (ch='H') then Write('Higher') else Write('Lower');
        Write(' than a ',CurrentNumber); WriteLn;
      end;

      { Correct, so increase score and display message.
        Also store the new number as the current number. }
      procedure CorrectChoice;
      begin
        Score := Score + 1;
        CurrentNumber := NextNumber;
        WriteLn('You guessed correctly.')
      end;

      { Otherwise incorrect, so exit loop by pretending
        X was pressed }
      procedure IncorrectChoice;
      begin
        ch := 'X';
        WriteLn('You were wrong! Sorry!');
      end;

    begin
      WriteLn;
      GetUserChoice;
 
      { Carry on with game loop only if X was not chosen }
      if (ch<>'X') then
      begin
        DisplayUserChoice;

        { Generate and display the next random number }
        RandomNumber('Next Number is'); WriteLn;

        { Check whether guess was correct }
        if ((ch='H') and (NextNumber > CurrentNumber)) or
           ((ch='L') and (NextNumber < CurrentNumber)) then
          CorrectChoice
        else
          IncorrectChoice;

      end;
      MainLoop:=ch;
    end;

    { Display game over message }
    procedure GameOverMessage;
    begin
      WriteLn('Game Over - Your score was ',Score);
      WriteLn;
    end;

    { Check for new high score }
    procedure NewHighScoreCheck;
    begin
      if(Score > HighScore) then
      begin
        { Show old/new high score, and get high scorers name }
        WriteLn('A new High Score was achieved.');
        WriteLn('It was ',HighScore,' but you scored ',Score,'. Well Done!');
        Write('Enter your name: ');
        ReadLn(HighScorerName); WriteLn;
        HighScore := Score;
      end;
    end;

    { Display high scorer details }
    procedure DisplayHighScorer;
    begin
      WriteLn('High score is ',HighScore,
              ', and is held by ',HighScorerName,'.'); WriteLn;
    end;

    { Ask user if wants another game - must press Y or N }
    function AnotherGameCheck:Char;
    begin
      repeat
        Write('Would you like another game (Y for Yes, or N for No)? ');
        ch:=UpCase(ReadKey);
        WriteLn(ch);
      until (ch='Y') or (ch='N');
      AnotherGameCheck:=ch;
    end;

  begin
    { Reset score to zero for new game and randomize numbers generated }
    Score := 0;
    Randomize;

    DisplayTitle;
    RandomNumber('First number is');
    repeat until (MainLoop='X'); { X was chosen or incorrect answer given }
    GameOverMessage;
    NewHighScoreCheck;
    DisplayHighScorer;
    NewGame:=AnotherGameCheck;
  end;

  { Finish Message }
  procedure FinishMessage;
  begin
    WriteLn; WriteLn('Goodbye. Thank you for playing this game.');
    WriteLn('Press a key to finish.');
    readKey;
  end;

begin {Program}

  SetUpHighScore;

  repeat until NewGame='N';

  FinishMessage;

end.

If you look at individual blocks, you can see that they show the bare bones of what needs to be done – e.g. the main program consists of running three instructions – SetUpHighScore for initialisation, and NewGame is looped until the 'N' is returned (i.e. that key was pressed). Finally, a FinishMessage is displayed.

 If you want to know more about NewGame to see how a game is made, then you would look in the NewGame procedure, which itself contains further procedures to describe how the NewGame works. NewGame sets the score to zero, randomises, displays the title, Gets the first random number, Do the main loop until the user quits with 'X' (or a wrong number is chosen), Display a game over message, Check for a new high score, display the high score, and then check with the user if a new game is required – this is returned from NewGame.

 f) Test Results

A test plan will give some indication can be formulated from the inputs and outputs of the program:-

Function

Expected Results

Actual Results

Does title display OK?

Higher or Lower Game

--------------------

Higher or Lower Game

--------------------

First and Next numbers distinguished?

First time: First number is…
Second time: Next number is…

First number is 8
Next number is 4
Next number is 1

Check randomness

Different results each time

First number 3

Next number 10

Next number 6

Next number 6

Check range of values

1 and 10 should be displayed at some point

Nums: 3,10,6,6
5,3,5,5
2,3,1

User: Lower,

Computer: Lower

You guessed correctly

First num: 8
You chose lower
Next number is 4
You guessed correctly

User: Lower

Computer: Same

You were wrong! Sorry!

Next number is 6
You chose lower…
Next number is 6
You were wrong! Sorry!

User: Lower
Computer: Higher

You were wrong! Sorry!

Next number is 4
You chose lower…
Next number is 7
You were wrong! Sorry!

User: Higher,

Computer: Higher

You guessed correctly

First num: 3
You chose higher
Next number is 6
You guessed correctly

User: Higher

Computer: Same

You were wrong! Sorry!

Next number is 3
You chose higher…
Next number is 3
You were wrong! Sorry!

User: Higher
Computer: Lower

You were wrong! Sorry!

Next number is 5
You chose higher…
Next number is 2
You were wrong! Sorry!

What if don't get any right?

High score is 0, and held by No High Scorer

First number is 6
You chose lower
Next number is 8
Wrong! Sorry!
Game over – score 0
High score 0, held by No High Scorer

When choosing Higher/Lower/Exit, what happens if press X

Game over – score 0

Game over – score 0

When choosing Higher/Lower/Exit, what happens if press non-H/L/X

Repeat of message

F: Message repeats
0: Message repeats
=: Message repeats

H: You chose higher…

Etc. etc. etc…

 Refresher Exercises

 Here's a number of exercises which will take you through the basics of what you have learned so far…

 Here's a table of the most commonly used keywords we have used so far:-

Keyword

Description

Example

ClrScr;

Clear the screen

ClrScr;

WriteLn('New Clear Screen…');

WriteLn;

Write a blank line

WriteLn('First section); WriteLn;

WriteLn('Second section.');

WriteLn(string);

Write a string value to the screen and move to next line down.

str:='Simon';

WriteLn('My name is',str);