No GUI Delphi applications

Guess A Number

Let’s create a simple console game. The computer will randomly pick an integer number from 0 to 50. Your task is to guess the number. Each time you pick a number a program will tell that your number is larger or smaller than the one you are looking for. When, finally, you find what the number was it’ll tell you how many times it took you to find it.

I’ll give you the code, but first let’s see what are two most seen commands in a console application:
Write and Read RTL procedures are typically used for writing and reading from a file. There are two standard text-file variables, Input and Output. In a Console application, Delphi automatically associates the Input and Output files with the application’s console window. The standard file variable Input is a read-only file associated with the operating system’s standard input (typically the keyboard). The standard file variable Output is a write-only file associated with the operating system’s standard output (typically the display).
Thus, Writeln is used to display a message; ReadLn is normally used to read in variables. In the code below, you will notice it ends with a ReadLn. Readln without any parameters simply waits for the [Enter] key to be pressed. One of the peculiarities of a console application is that when it has stopped running, the console window is automatically closed. The ReadLn statement is necessary so that the user can see any text produced by Writeln statements before it disappears off the screen when the program finishes.

Here goes the code. I hope you understand it.

program GuessANumber;

 rn, un, cnt: Integer;
 guess: Boolean;

  rn := Trunc(Random(50) + 1);
  Write('Computer has picked an integer number,');
  Write('from 1 to 50, guess the number!');
  WriteLn('Your guess is: ');
  cnt := 1;  un := 0;
  Guess := False;
  while Guess = False do begin
   if un > rn then
     Write('Wrong, gimme a smaller number: ')
   else if un < rn then
     Write('Wrong, gimme a larger number: ')
   else //un=rn
       Write('Correct! It took you ' +
             IntToStr(cnt) +
             ' times to guess!')
   cnt := cnt + 1;
  end; //while
  ReadLn; //don't close the window, wait for [Enter]

Simply run the project and play....

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: