Vydělávej až 160.000 Kč měsíčně! Akreditované rekvalifikační kurzy s garancí práce od 0 Kč. Více informací.
Hledáme nové posily do ITnetwork týmu. Podívej se na volné pozice a přidej se do nejagilnější firmy na trhu - Více informací.

Hangman

Hangman

cpp

/**********
 * main.c *
 **********/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "hangman.h"

int main(void)
{
    char secret[30];
    char c = 'a';

    // initialize random
    srand(time(NULL));
    while(c == 'a' || c == 'A') {
        hangman(secret);
        printf("\n\nPOKRACOVAT? A/N: ");
        scanf("%c", &c);
        system("cls");
    }
    printf("\n\nKONIEC HRY!!!\n\n");
    system("pause");
    return 0;
}

/*************
 * hangman.c *
 *************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <string.h> // knižnica pre prácu s reťazcami
#include <ctype.h> // knižnica na pretypovanie veľkým písmen na malé
#include "hangman.h"

int getWord(char secret[]){
    // check if file exists first and is readable
    FILE *fp = fopen(WORDLIST_FILENAME, "rb");
    if( fp == NULL ){
        fprintf(stderr, "No such file or directory: %s\n", WORDLIST_FILENAME);
        return 1;
    }

    // get the filesize first
    struct stat st;
    stat(WORDLIST_FILENAME, &st);
    long int size = st.st_size;

    // initialize random
    //srand(time(NULL));

    do{
        // generate random number between 0 and filesize
        long int random = (rand() % size) + 1;
        // seek to the random position of file
        fseek(fp, random, SEEK_SET);
        // get next word in row ;)
        int result = fscanf(fp, "%*s %s", secret);
        if( result != EOF )
            break;
    } while(1);

    fclose(fp);

    return 0;
}

int isWordGuessed(char secret[], char lettersGuessed[])
{
    int i;
    char *najdi; // pomocný retazec

    najdi = (char *) malloc(15); // dynamické alokovanie pamäti pre pomocný reťazec
    /* cyklus prechádza reťazec "tajne" po pismenach,
       ak sa reťazci "zadane" znak nenachadza, funkcia vráti 0,
       ak sa nachádza, vráti 1
    */
    for (i = 0; i < strlen(secret); i++){
        najdi = strchr(lettersGuessed, secret[i]);
        while (najdi == NULL) {
            return 0;
        }
    }
    return 1;
}

void getGuessedWord(char secret[], char lettersGuessed[], char guessedWord[])
{
    int i, j = 0;
    char *najdi;

    najdi = (char *) malloc(15);
    /*
       cyklus prechádza reťazec "tajne" po pismenach,
       ak sa reťazci "zadane" znak nenachadza, zapíše do reťazca "vypis" znak '_',
       ak sa nachádza, zapíše daný znak
    */
    for (i = 1; i < (strlen(secret) * 2); i++) {
        if (i % 2 != 0) {
            najdi = strchr(lettersGuessed, secret[j++]);
            guessedWord[i - 1] = najdi != NULL ? *najdi : '_';
        }
        else
            guessedWord[i - 1] = ' ';
    }
    guessedWord[i] = '\0'; // ukončenie reťazca
    printf("%s", guessedWord); // vypíše reťazec "vypis" aj s medzerami
}

void getAvailableLetters(char lettersGuessed[], char availableLetters[])
{
    int i, j = 0;
    char *najdi, abcd[] = "abcdefghijklmnopqrstuvwxyz";

    najdi = (char *) malloc(15);
    /*
       cyklus prechádza reťazec "abcd" po znakoch,
       ak sa znak v raťazci "zadane" nenachádza, cyklus sa vráti na začiatok,
       ak sa nachádza, zapíše sa do reťazca "abeceda"
    */
    for (i = 0; i < strlen(abcd); i++){
        najdi = strchr(lettersGuessed, abcd[i]);
        if (najdi != NULL)
            continue;
        else {
            availableLetters[j++] = abcd[i];
        }
    }
    availableLetters[j] = '\0';
    printf("%s", availableLetters); // vypíše reťazec "abeceda"
}

void hangman(char secret[])
{
    int i = 0, j, k = 0, pokracuj = 1, pokusy = 8;
    char c, tajne[15], abeceda[30], zadane[50] = "", vypis[30] = "", t_a_j_n_e[30] = "";

    getWord(tajne); // vygeneruje zo súboru words.txt náhodný rťazec "tajne"
    /*
       cyklus prejde reťazec "tajne" po písmenách a zmení ich na malé
    */
    for (j = 0; j < strlen(tajne); j++)
        tajne[j] = tolower(tajne[j]);
    /*
       cyklus vytvorí reťazec s medzerami "t_a_j_n_e"
    */
    for (j = 1; j < strlen(tajne) * 2; j++)
        t_a_j_n_e[j - 1] = j % 2 == 0 ? ' ' : tajne[k++];
    t_a_j_n_e[j] = '\0';
    printf("Welcome to the game, Hangman!\n");
    printf("I am thinking of a word that is %d letters long.", strlen(tajne));
    CIARA;
    /*
       cyklus beží, kým je v premennej "pokracuj" hodnota 1
    */
    while (pokracuj) {
        printf("\nYou have %d guesses left.\nAvailable letters: ", pokusy);
        getAvailableLetters(zadane, abeceda);
        printf("\nPlease guess a letter: ");
        scanf("%c", &c);
        while (getchar() != '\n') // zbavenie sa znaku <Enter>
            ;                     // botkočiarka patri k tomu
        c = tolower(c); // zmena velkého pismena na malé
        /*
           ak sa v "abeceda" zadaný znak nenachádza, už bol predtým použitý
        */
        if (!strchr(abeceda, c)) {
            printf("\nOops! You've already guessed that letter: ");
            getGuessedWord(tajne, zadane, vypis); // výpis
            CIARA;
            continue;
        }
        zadane[i++] = c; // zapísanie znaku do reťazca "zadane"
        /*
           ak sa znak nachádza v reťazci "tajne":
        */
        if (strchr(tajne, c)) {
            printf("\nGoog quess: ");
            getGuessedWord(tajne, zadane, vypis); // výpis
            /*
               vtedy ak sa uhádlo celé slovo
            */
            if (strcmp(t_a_j_n_e, vypis) == 0) {
                CIARA;
                printf("\nCongratulations, you won!\n"); // výhra
                break; // koniec programu
            }
        }
        /*
           ak sa znak v reťazci "tajne" nenachádza:
        */
        else {
            printf("\nOops! That letter is not in my word: ");
            getGuessedWord(tajne, zadane, vypis); // výpis
            pokusy--; // počet pokusov sa zbníži o 1
            /*
               vtedy ak počet pokusov rovná sa 0
            */
            if (pokusy == 0) {
                CIARA;
                printf("\nSorry, you ran out of guesses. The word \"%s\" was undeserved.\n", tajne);
                break; // koniec programu
            }
        }
        CIARA;
    }
}


/*************
 * hangman.h *
 *************/

#define WORDLIST_FILENAME "words.txt"
#define CIARA printf("\n\n-----------------------------------------------\n");

/**
 * Function detects, whether player guessed the secret word
 * Based on the letters player used for guessing, this function detects,
 * if it is possible to construct (and guess) the secret word from this set.
 * If it is possible, function returns 1. If not, returns 0.
 * @param secret the secret word lowercase
 * @param lettersGuessed the lowercase letters player already used in his guessing
 * @return 1, if word is guess; 0 otherwise.
 */
int isWordGuessed(char secret[], char lettersGuessed[]);

/**
 * Function returns string representing the guessed word
 * This string contains visible letters, which were guessed successfuly
 * by player at their correct positions. If there are still some hidden
 * letters, the character '_' will be used for their representation.
 * @param secret the secret word lowercase
 * @param lettersGuessed the lowercase letters player already used in his guessing
 * @param guessedWord the constructed string as result of this function (output parameter)
 */
void getGuessedWord(char secret[], char lettersGuessed[], char guessedWord[]);

/**
 * Returns all letters, which were not used for guessing
 * Function returns set of lowercase letters sorted in alphabetical order. This
 * set will contain all letters from the alphabet, but it ommits those, which
 * were already guessed.
 * @param lettersGuessed the lowercase letters player already used in his guessing
 * @param availableLetters set of lowercase not yet used letters
 */
void getAvailableLetters(char lettersGuessed[], char availableLetters[]);

/**
 * Starts interactive hangman game
 *
 * @param secret the secret word lowercase
 */
void hangman(char secret[]);

/**
 * Returns the random word
 * Function opens the file with all the words and reads randomly one of them
 * into the buffer pointed by secret. Word consists of lowercase letters.
 * If there is some error with reading the file, 1 is returned.
 * Otherwise (everything is ok), 0 is returned.
 * @param secret buffer, where random word will be read
 * @return status code
 */
int getWord(char secret[]);

Neformátovaný

Přidáno: 28.4.2014
Expirace: Neuvedeno

Aktivity