GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 14-Mar-2006, 09:18
Lan Lan is offline
New Member
 
Join Date: Mar 2006
Location: In front of the Monitor
Posts: 20
Lan is on a distinguished road

Suggestions for my Code for Hangman /* Ansi C-based */


It is a single player hangman that uses text files to read phrases that will be used for the game and can /* store top 5 players in a text file */ and uses functions and a library for other utilities.

This is the main.c
CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "util.h"

#define MAX 80

typedef struct {
        char name[30];
        int score;
        } players;

char Phrase[MAX], temp1[MAX], storage[26];
int choice, chance1, tries1, diff;
players player;

void printSpace();   /* Tools that the program needs. */
int getCharacter();
int checkCharacter(char guessedChar, int noOftries);   

int menu();          /* These are the main functions of the game */
int diffSelect();
int playGame();
int mainGame();

int main()
{   
   printf("\n\n");
   printf("   |***********************| \n");
   printf("   \\* Welcome to Hangman  */\n");
   printf("   /*           by Lan    *\\ \n");
   printf("   |***********************| \n");
   printf("\n\n");
   menu();
}

int menu()
{
   int x; tries1 = 0, choice = 0;
    
      printf("\nPlayer Mode\n");
      printf("  [1].Play\n  [2].High Scores\n  [3].Im Tired\n\n");
      printf("Select you choice: ");
      scanf("%d", &choice); 
		
      if(choice==1)
	diffSelect();
      else if(choice==2)
             { displayHigh(); menu(); }
      else
	return 1;
}

int diffSelect()
{  
   char dummy[50];
   
   putchar('\n');
   printf("You chose to play.\n");
   printf("\nSelect difficulty\n  1(Hard) - 9(Easy) : ");
   scanf("%d", &diff); chance1 = diff+5;
   printf("Player name: ");
   scanf("%s", player.name);
   
   randPhrase(Phrase);
   playGame();
}
       
/* int randPhrase()
{   
   putchar('\n');
   printf("Choosing Random Phrase...");
   strcpy(Phrase, "Hello");
   printf("Done.\n\n");
   playGame();
} */

int playGame()
{
   int x, y;
   for(x = 0; x < strlen(Phrase); x++)
   {
      temp1[x] = '_';
      Phrase[x] = toupper(Phrase[x]);
   }
      temp1[strlen(Phrase)] = '\0';  
      
      
   y = mainGame();
   
      if(y)
      {
         printSpace();
         printf("You win %s , you got %s in %d tries.\n", player.name, Phrase, tries1);
         player.score = (100-(10-chance1)*10)+10;
         printf("Your score is %d points\n\n", player.score);
         menu();
      }
               
      else
      {
         printSpace();
         printf("You Lose %s, no points for this game.\n", player.name);
         printf("The correct phrase is \"%s\"\n\n", Phrase);
         menu();
      }
}

int mainGame()
{
   int x, y = 0, cond1; char guess;
   

      while(chance1>=1)
         {
            if(!strcmp(temp1, Phrase)) break;
            y = 0;
            printf("\nHint: %s\n", temp1);
            printf("Guess a letter: ");
            guess = getCharacter(); guess = toupper(guess); tries1++;
            
			for(x = 0; x < strlen(Phrase); x++)
			{
				if(!checkCharacter(guess, tries1))
				   { printf("Error. Already Guessed.\n"); y--; break; }
				else if(guess==Phrase[x])
				   { temp1[x] = guess; y++; continue; }
			}
					 
            if(y>0) praise();
            else if(y==0)
            {
               insult(); chance1--;
               printf("You got %d chance/s left.\n\n\n", chance1);
            }	 
         }
          
      if(!strcmp(temp1, Phrase)) return 1;
      else return 0;
}

void printSpace()
{ printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); }

int  getCharacter()
{
    int ch;       
    do             
    {
       ch = getchar();        
    } while((ch <= 0x20)||(ch >= 0x7F)/* check above SPACE, below the last ASCII char */ );                    
    return ch;
}

int checkCharacter(char guessedChar, int noOftries)
{
    int x;
    
    for( x = 0;  x < strlen(storage); x++)
       if(guessedChar == storage[x]) return 1;
       else
       {
          storage[noOftries-1] = guessedChar; return 0;
       }
}
/* Im having problems implementing checkCharacter, what it exactly does is that it puts the scanned char at a string and makes it an error-checker if the guess is already guessed xD */

This is the util.h
CPP / C++ / C Code:
extern void randPhrase();
extern void praise();
extern void insult();
extern void displayHigh();

void randPhrase(char *array)
{
	int x=0;
	char *temp = { "Hello" }; 
 
	for(x=0; x<strlen(temp); x++)
	{
		array[x] = temp[x];
	}

	array[x] = '\0';
}

void praise()
{
char praise[5][20] = { "Good Job.", "Great!", "Amazing!", "Keep it up!", "Go go go!" };

   srand( time() );                           
   printf("%s.\n", praise[(rand()%10%5)+1]);
}

void insult()
{
char praise[5][30] = { "Think Again.", "Bah Humbug!", "You're a Big Joke", "Go Home.", "Press Ctrl+C." };

   srand( time() );                           
   printf("%s.\n", praise[(rand()%10%5)+1]);
}

void displayHigh()
{
   printf("Hello World.\n");
}

Please appologize if there are several mistakes in my program. It is currently under development. But that is the main program. My main objectives are to:

1. Have random praise or insult. /* Implemented */
2. Case insensitive character checking. /* Implemented */
3. Save the top 5 players in a seperate file. /* Under Debug */
4. Encrypton/ Decryption Scheme. /* Alpha Stage */
5. Use comments so the phrase will not be repeated. /* Not yet done. */
6. Use srand() to change the sequence of rand(). /* Implemented */

Suggestions, comments, additional codes, improvements is very much needed. Please bear with the code. I haven't got the time to document it.

Thanks.
/* Note: For students whose from UPLB, please no plagiarizing, and if you want to use some of my algo, please cite my complete name in your documentation. */
  #2  
Old 15-Mar-2006, 07:25
davis
 
Posts: n/a

Re: Suggestions for my Code for Hangman /* Ansi C-based */


All I did was make it so that your code would compile cleanly without errors. There are still numerous warnings. Here is the code:

util.h
CPP / C++ / C Code:
#ifndef UTIL_H
#define UTIL_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>

extern void randPhrase();
extern void praise();
extern void insult();
extern void displayHigh();

void randPhrase(char *array)
{
    int x=0;
    char *temp = { "Hello"}; 

    for( x=0; x<strlen(temp); x++ )
    {
        array[x] = temp[x];
    }

    array[x] = '\0';
}

void praise()
{
    char praise[5][20] = { "Good Job.", "Great!", "Amazing!", "Keep it up!", "Go go go!"};

    srand( time( 0 ) );                           
    printf("%s.\n", praise[(rand()%10%5)+1]);
}

void insult()
{
    char praise[5][30] = { "Think Again.", "Bah Humbug!", "You're a Big Joke", "Go Home.", "Press Ctrl+C."};

    srand( time( 0 ) );                           
    printf("%s.\n", praise[(rand()%10%5)+1]);
}

void displayHigh()
{
    printf("Hello World.\n");
}

#endif /* UTIL_H */

...and your "main" file, that I called hangman.c:

CPP / C++ / C Code:
#include "util.h"

#define MAX 80

typedef struct
{
    char name[30];
    int score;
} players;

char Phrase[MAX], temp1[MAX], storage[26];
int choice, chance1, tries1, diff;
players player;

void printSpace();   /* Tools that the program needs. */
int getCharacter();
int checkCharacter(char guessedChar, int noOftries);   

int menu();          /* These are the main functions of the game */
int diffSelect();
int playGame();
int mainGame();

int main()
{
    printf("\n\n");
    printf("   |***********************| \n");
    printf("   \\* Welcome to Hangman  */\n");
    printf("   /*           by Lan    *\\ \n");
    printf("   |***********************| \n");
    printf("\n\n");
    menu();
}

int menu()
{
    int x; tries1 = 0, choice = 0;

    printf("\nPlayer Mode\n");
    printf("  [1].Play\n  [2].High Scores\n  [3].Im Tired\n\n");
    printf("Select you choice: ");
    scanf("%d", &choice); 

    if( choice==1 )
        diffSelect();
    else if( choice==2 )
    {
        displayHigh(); menu();
    }
    else
        return 1;
}

int diffSelect()
{
    char dummy[50];

    putchar('\n');
    printf("You chose to play.\n");
    printf("\nSelect difficulty\n  1(Hard) - 9(Easy) : ");
    scanf("%d", &diff); chance1 = diff+5;
    printf("Player name: ");
    scanf("%s", player.name);

    randPhrase(Phrase);
    playGame();
}

/* int randPhrase()
{   
   putchar('\n');
   printf("Choosing Random Phrase...");
   strcpy(Phrase, "Hello");
   printf("Done.\n\n");
   playGame();
} */

int playGame()
{
    int x, y;
    for( x = 0; x < strlen(Phrase); x++ )
    {
        temp1[x] = '_';
        Phrase[x] = toupper(Phrase[x]);
    }
    temp1[strlen(Phrase)] = '\0';  


    y = mainGame();

    if( y )
    {
        printSpace();
        printf("You win %s , you got %s in %d tries.\n", player.name, Phrase, tries1);
        player.score = (100-(10-chance1)*10)+10;
        printf("Your score is %d points\n\n", player.score);
        menu();
    }

    else
    {
        printSpace();
        printf("You Lose %s, no points for this game.\n", player.name);
        printf("The correct phrase is \"%s\"\n\n", Phrase);
        menu();
    }
}

int mainGame()
{
    int x, y = 0, cond1; char guess;


    while( chance1>=1 )
    {
        if( !strcmp(temp1, Phrase) ) break;
        y = 0;
        printf("\nHint: %s\n", temp1);
        printf("Guess a letter: ");
        guess = getCharacter(); guess = toupper(guess); tries1++;

        for( x = 0; x < strlen(Phrase); x++ )
        {
            if( !checkCharacter(guess, tries1) )
            {
                printf("Error. Already Guessed.\n"); y--; break;
            }
            else if( guess==Phrase[x] )
            {
                temp1[x] = guess; y++; continue;
            }
        }

        if( y>0 ) praise();
        else if( y==0 )
        {
            insult(); chance1--;
            printf("You got %d chance/s left.\n\n\n", chance1);
        }
    }

    if( !strcmp(temp1, Phrase) ) return 1;
    else return 0;
}

void printSpace()
{
    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}

int  getCharacter()
{
    int ch;       
    do             
    {
        ch = getchar();        
    } while( (ch <= 0x20)||(ch >= 0x7F)/* check above SPACE, below the last ASCII char */ );                    
    return ch;
}

int checkCharacter(char guessedChar, int noOftries)
{
    int x;

    for( x = 0;  x < strlen(storage); x++ )
        if( guessedChar == storage[x] ) return 1;
        else
        {
            storage[noOftries-1] = guessedChar; return 0;
        }
}
/* Im having problems implementing checkCharacter, what it exactly does is that it puts the scanned char at a string and makes it an error-checker if the guess is already guessed xD */


...and the compiler warnings:

Code:
gcc -c -ansi -g -Wall -pedantic -o "Debug/hangman.o" "hangman.c" hangman.c: In function `main': hangman.c:33: warning: control reaches end of non-void function hangman.c: In function `menu': hangman.c:37: warning: unused variable `x' hangman.c:52: warning: control reaches end of non-void function hangman.c: In function `diffSelect': hangman.c:56: warning: unused variable `dummy' hangman.c:67: warning: control reaches end of non-void function hangman.c: In function `playGame': hangman.c:107: warning: control reaches end of non-void function hangman.c: In function `mainGame': hangman.c:111: warning: unused variable `cond1' hangman.c: In function `checkCharacter': hangman.c:171: warning: control reaches end of non-void function gcc -g -Wall -pedantic -o "Debug/hangman" Debug/hangman.o


You've got globals, multiple statements on single lines, multiple variables declared on single lines, no return values for functions declared to return a value, you use single-line and multi-line conditional braces, in some cases you jam your variables and operators together and in others you separate them with appropriate whitespace, you were missing headers and inclusion guards...give it a bit more work and clean it up and we'll take another look at it, okay?


:davis:
  #3  
Old 15-Mar-2006, 21:20
Lan Lan is offline
New Member
 
Join Date: Mar 2006
Location: In front of the Monitor
Posts: 20
Lan is on a distinguished road

Re: Suggestions for my Code for Hangman /* Ansi C-based */


Well, thanks man.. It helped me a lot. Sorry for the trash... I will clean it up ASAP.

Err.. I have managed to clean it up and im down with the problem of how to restate an argument like this?
CPP / C++ / C Code:
temp[x] = toupper( temp[x] )
As of now, my only warnings are two of that type. Ansi C forbids braced groups to be used in an expression?
  #4  
Old 16-Mar-2006, 09:01
Lan Lan is offline
New Member
 
Join Date: Mar 2006
Location: In front of the Monitor
Posts: 20
Lan is on a distinguished road

Re: Suggestions for my Code for Hangman /* Ansi C-based */


Ive now encountered my second problem in decypting a text file. I managed to encrypt it by changing each character to it hex equivalent and decrypting it is successful. The problem is it doesnt have any newlines. So the multi-lined source file becomes a single line source file!

Encryption.c
CPP / C++ / C Code:
#include <stdio.h>

int main()
{

  FILE 	*Ptr;

  char	 Line[80];
  int x, length;
  /* ...	Open a file for output. */

  Ptr = fopen("hello1.txt", "w");
  
  while( gets(Line) )		/* Get data from stdin */
  {
	length = strlen(Line);
	for( x = 0; x < length; x++ )
    fprintf(Ptr, "%02x ", Line[x]); 
    putc('\n', Ptr);
  }
    putc('\b', Ptr);
    
  fclose(Ptr);
  
  exit(1);
}

Decryption.c
CPP / C++ / C Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>

main()
{
   FILE *source, *dest, *temp;
   char data[80];
   int hex;
   
   if((source=fopen("hello1.txt", "r"))==NULL)
   {
      printf("Error opening source file\n");
      exit(1);
   }
      
   if((dest=fopen("hello.txt", "w"))==NULL)
   {
      printf("Unable to write/create destination file");
      exit(1);
   }
   
   fscanf(source, "%x", &hex);
   while(!feof(source))
   {
      fprintf(dest, "%c", hex); 
      fscanf(source, "%x", &hex);
   }

   fclose(source);
   fclose(dest);
}

So a file with:
// Hello
// world
is encypted as:
// 68 65 6c 6c 6f
// 77 6f 72 6c 64
and decrypted as:
// helloworld

I want an expected output of:
// hello
// world

Any one?
  #5  
Old 16-Mar-2006, 11:04
Lan Lan is offline
New Member
 
Join Date: Mar 2006
Location: In front of the Monitor
Posts: 20
Lan is on a distinguished road

Re: Suggestions for my Code for Hangman /* Ansi C-based */


After cont's debugging, problem solved. Thanks people.
  #6  
Old 19-Mar-2006, 00:25
Lan Lan is offline
New Member
 
Join Date: Mar 2006
Location: In front of the Monitor
Posts: 20
Lan is on a distinguished road

Re: Suggestions for my Code for Hangman /* Ansi C-based */


To prevent plagiarized codes, can the admin please erase my C codes? Because this hangman was assigned to be a project individually. Im afraid that someone can gain access to this codes with simple searches on google.

Ive done one and this thread showed on page 3. !
  #7  
Old 19-Mar-2006, 08:16
admin's Avatar
admin admin is offline
Administrator
 
Join Date: Sep 2002
Posts: 870
admin will become famous soon enough

Re: Suggestions for my Code for Hangman /* Ansi C-based */


Unfortunately, I cannot delete the code. I am not obliged to do so.

Quote:
Originally Posted by Lan
Im afraid that someone can gain access to this codes with simple searches on google.

This is why we exist... So (other) people can find things already being discussed and shared. We cannot control what people do with the information they find here.

This may be obvious but I'll state it again -- please refrain from posting or replying if you don't want certain information to be shared with others.

As far as I am concerned, you already did the responsible thing by suggesting / advising people what they can and cannot do with your code examples inside this thread.
__________________
Custom BB codes you can use here:
[HTML] | [C++] | [CSS] | [JAVA] | [PY] | [VB]
  #8  
Old 19-Mar-2006, 18:29
Lan Lan is offline
New Member
 
Join Date: Mar 2006
Location: In front of the Monitor
Posts: 20
Lan is on a distinguished road

Re: Suggestions for my Code for Hangman /* Ansi C-based */


I realized that after posting the last post. Oh well, what done is done. Its up to them now.

BTW, thanks.
__________________
[ http://www.komsay-elbi.tk/ ] [ http://www.abovetopsecret.com/ ]
 
 

Recent GIDBlogLast post for some time (ever?) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Code Contest Paramesh Miscellaneous Programming Forum 76 30-Jun-2006 12:18
User defined headers davis Miscellaneous Programming Forum 6 16-Feb-2006 18:40
Guidelines for posting requests for help - UPDATED! WaltP C++ Forum 0 21-Apr-2005 02:44
Problem with int mixed with char,... leitz C++ Forum 17 07-Dec-2004 20:56

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 02:40.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.