Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Hangman Strings and Characters

Posted on 2003-10-30
6
1,000 Views
Last Modified: 2008-02-01
I was wondering if you could help me, i am new to Delphi 7 as i have just started using it for college assignments and i am trying to create a hangman game in a Console Program, i was wondering if the User inputs a word which is to be guessed and then someone else enters a character and if that character is in the word a message appears saying well done or sorry. i would really appreciate it if you could help me.

Thankyou very much.
0
Comment
Question by:inanetreasure
6 Comments
 
LVL 8

Accepted Solution

by:
shamstar earned 44 total points
ID: 9653782

Heres something to get you started:

To write things out to the user via the console you use:
   Writeln('the message goes here');

To read in input from the user use:
   Readln(variable);

Hopefully you can easily use the Writeln (stands for write line) function.
To use the Readln function, you need to give it a variable for it to store the users input. This variable can
either be a string or a char type.  When you want the user to provide you with a word, then use a string type.
When you want another user to take a guess at a letter, use a char type.

The final thing to do would be to check to see if the guessed character was in the word the first user chose.
To do this you can use something like:

   var
   GuessedChar : Char;
   TheWord : String;


   if GussedChar in ['h', 'e', 'l', 'l', 'o'] then
      begin
      // add your correct guess code in here
      end
   else
      begin
      // add your wrong guess code in here
      end;

If you notice above, we are checking to see if the guessed character is in a set of other specific characters.  For things to work correctly you will need the character from the chosen word in that set.  Your best bet to do that is by accessing every character in a loop that runs for the number of characters in the word.  This loop will access the characters using an array notation such as TheWord[1] to give you the first character from TheWord.  To find the length of the word, use the Length funtion.
You may want to consider looking up the lenght function and sets in the delphi help.


0
 
LVL 2

Assisted Solution

by:Moroni24
Moroni24 earned 42 total points
ID: 9654355
This a small addition to shamstar's fine comments

Rather than hardcoding the value in i.e. ['h','e','l','','o']
try using POS. POS will search a string for the instance of a substring... which is exactly what you are doing



var
   GuessedChar : Char;
   TheWord : String;

if pos(GuessedChar,TheWord) > 0 then
  begin
    // add your correct guess code in here
  end
else
  begin
    // add your wrong guess code in here
  end
0
 
LVL 5

Assisted Solution

by:DeerBear
DeerBear earned 42 total points
ID: 9660166
Hi,

As usual, it all depends on the kind of compleity you want to give to
your application.

Personall, my hangman version would probably make
entire sentences being guessed and I would use a string list.

For Delphi 5 down, here is a cool string list extension:

Type

   TStringListEnh = class( TStringList )
   private
      FDelimitChar : Char;
      FDelimitedText : String;
       
      procedure SetDelimitChar( const Value : Char );
      procedure SetDelimitedText( const Value : String );
   protected
      procedure DoDelimitText;
   public
       constructor Create;// uh, I don't have Delphi in front of me,
                                  // thus I don't remember if the constructor's
                                  //virtual here.
   published
       property DelimitChar : Char read FDelimitChar write SetDelimitChar;
       property DelimitedText : String read FDelimitedText write SetDelimitedText;
   end;

constructor TStringListEnh.Create;
begin
  Inherited Create;
  FDelimitChar := #0;
  FDelimitedText := '';
end;

procedure TStringListEnh.SetDelimitChar( const Value : Char );
begin
   FDelimitChar := Value;
   if FDelimitedText <> '' then
   begin
     if FDelimitChar <> #0 then
       DoDelimitText;
   end;
end;

procedure TStringListEnh.SetDelimitedText( const Value : String );
begin
  FDelimitedText := Value;
  if FDelimitChar <> #0 then
  begin
    if FDelimitedText <> '' then
      DoDelimitText;
  end;
end;

procedure TStringListEnh.DoDelimitText;
var TempList : TStringList;
      CharPos : Integer;
begin
   TempList := TStringList.Create;
   if Pos( FDelimitChar,FDelimitedText ) > 0 then
   begin
     CharPos := Pos( FDelimitChar,FDelimitedText );
     while CharPos > 0 do
     begin
        TempList.Add( Copy( FDelimitedText,1,Pred( CharPos ) );
         Delete( FDelimitedText,1,CharPos );
         CharPos := Pos( FDelimitChar,FDelimitedText );
     end;
  end;
  if TempList.Count > 0 then
  begin
    Text := '';
    AddStrings( TempList );
  end;
  TempList.Free;
end;

This class is useful to split a string in several substrings and can
nicely extend the plain stringlist. Please note that from D6 up the
TStringList class already has the two properties listed here, so you
just have to use them.

To look for a match in the list, use the IndexOf method.

With this technique you can for example make a multiplayer
version of the hangman( use a StringList to hold the various
words for the players ) or to expand the hangman to use entire
sentences.

If you don't want to cope with this new class, you can use the
CommaText property already built in the TStringList class.

Read the help for more details on all the subjects.

HTH,

Andrew
0
 
LVL 27

Assisted Solution

by:kretzschmar
kretzschmar earned 42 total points
ID: 9679091
my very simple sample

program Hangman;

{$APPTYPE CONSOLE}

uses
  SysUtils;

const
  MaxMistakes = 10;

var
  MatchWord : String;
  ResultStr : String;
  Mistakes : Integer;
  GivenInput : String;
  finishApp : Boolean;
  c : integer;
  ch : Char;

Function Check(AMatchWord : String; var AResult : String; AChar : Char) : Boolean;
var i : integer;
begin
  result := False;
  if pos(UpperCase(AChar),UpperCase(AMatchWord)) > 0 then  //Caseinsentensive
  begin
    for i := 1 to length(AMatchWord) do
      if UpCase(AChar) = UpCase(AMatchWord[i]) then
        AResult[i] := AMatchWord[i];
    result := True;
  end;
end;

Procedure Display;
begin
  writeln;
  writeln(ResultStr+' Mistakes ',Mistakes:0);
  writeln;
end;


begin
  FinishApp := False;
  repeat
    writeln('Input SearchWord (the other should see away, use the word quit for quit):');
    readln(MatchWord);
    if UpperCase(MatchWord) <> 'QUIT' then
    begin
      //some Inits;
      Mistakes := 0;
      ResultStr := '';
      GivenInput := '';
      for c := 1 to length(MatchWord) do
        ResultStr := ResultStr+ '_';
      Display;
      while (UpperCase(ResultStr) <> UpperCase(MatchWord)) and
            (Mistakes <= MaxMistakes) do
      begin
        Write('Give me a Char: ');
        readln(ch);
        if pos(ch,GivenInput) = 0 then
        begin
          GivenInput := GivenInput + ch;
          if not(check(MatchWord,ResultStr,ch)) then
          begin
            writeln('sorry');
            inc(Mistakes);
          end
          else
            writeln('yep, go on');
          Display;
        end
        else
          writeln('This Char you typed already');
      end;
      if Mistakes > MaxMistakes then
        writeln('You don''t got it. The word was:'+Matchword)
      else
        writeln('Congratulation, you got it ;-)')
    end
    else
      FinishApp := true;
  until FinishApp;
end.

meikl ;-)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Delphi application Soap connection 5 120
Base1 Encode/Decode 3 81
Multi-layered image in FireMonkey 9 48
DBCtrlGrid, Delphi, Scroll 7 26
Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
In my programming career I have only very rarely run into situations where operator overloading would be of any use in my work.  Normally those situations involved math with either overly large numbers (hundreds of thousands of digits or accuracy re…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question