Система показателей Палач. C ++

0

Прямо сейчас я пытаюсь заставить свою оценочную карту работать на палача. Это игра, в которую я могу играть столько раз, сколько хочу, и хочу, чтобы она показывала мой самый низкий результат, когда я нажимаю 2 в меню игры. По какой-то причине моя логика не работает. Может ли кто-нибудь помочь? Я приложил к нему 3 раздела кода, необходимые для этого.

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <fstream>

using namespace std;

int maxAttempts = 10; //max attempts possible
void poorStiff(int);
int wordFill(char, string, string&);


int main()
{


    int intro;
    int bodyPart = 0;
    ifstream wordIn; //file stream read in
    wordIn.open("WordList.txt"); //list of words used in this game
    //if (!wordIn.good()) { std::cerr << "open failed.\n"; exit(1); }
    char letter; //letter guessed
    int numWrongGuesses = 0; //counts the number of wrong guesses
    string theWord;
    string words[13];
    int play = 0;
    bool run = true;
    int makeYourSelection = 0;
    int bestScore = 11;

    while (run == true)
    {
        int attemptsGame = 0;
        // put a game menu to loop that asks if you want to keep playing or exit and go to scorecard
        cout << "            WELCOME TO THE GAME OF HANGMAN\n\n\n\n";
        cout << "    Press 1 to play the game, press 2 to exit to the scorecard \n\n";
        cout << "   You have 10 attempts to guess the words before you get hung \n\n";
        cin >> play;


        while (play == 1)//loops while user has entered 1, 0 exits the game
        {
            for (int i = 0; i < 13; i++) //labeled 13 and not words because 13 is a constant
            {
                wordIn >> words[i];//replaces the file words and puts them in an array and counts them out of the file
                cout << words[i] << endl;
            }
            srand(time(NULL));//to get a random word
            int n = rand() % 12;
            theWord = words[n]; //pulls word from file
            wordIn.close();

            string mystery(theWord.length(), '*'); //replaces word letters with asterisks



            while (numWrongGuesses < maxAttempts) // while the amount of guesses is less than the max wrong guesses
            {
                cout << mystery << endl << endl;
                cout << "You now have the length of the word represented by the *'s. \n\n";
                cout << "Guess a letter \n\n";
                cin >> letter;


                if (wordFill(letter, theWord, mystery) == 0) //fuction call
                {
                    bodyPart++;
                    poorStiff(bodyPart);
                    cout << "You have entered a letter that isn't in the word, guess again. \n\n";
                    numWrongGuesses++;
                    attemptsGame++;
                }
                else
                {
                    for (int i = 0; i < mystery.length(); i++)
                    {
                        if (theWord[i] == letter)
                        {
                            mystery[i] = letter;
                        }
                    }
                    cout << "You have found one of the letters. Congratulations! \n\n";
                    cout << "You have: " << maxAttempts - numWrongGuesses;
                    cout << " guesses left \n\n" << endl;
                }

                if (theWord == mystery) // the word is the same as mystery
                {
                    cout << theWord << endl;
                    cout << "\n\n Awesome, you guessed it. \n\n";
                    break;
                    if (attemptsGame < bestScore)
                    {
                        bestScore = attemptsGame;

                    }
                }
            }
            if (numWrongGuesses == maxAttempts) //when you run out of guesses
            {
                cout << "Too bad, you ran out of guesses and have been hung at the gallows. \n\n";
                cout << "The word you were trying to guess was " << theWord << endl;
                poorStiff(bodyPart);
            }
            cin.ignore();
            cin.get();

            break;
        }
            while (play == 2)
            {
                cout << "Best Scores: \n\n";
                cout << bestScore << endl;
                system("pause");
                return 0;
                break;
            }
        }
        system("pause");
        return 0;
    }


    int wordFill(char guess, string theWordSecret, string&guessWord) //function for determing if you guess a letter contained
    {
        int i;
        int hits = 0; //letter hits within the word
        int many = theWordSecret.length();

        for (i = 0; i < many; i++)
        {
            if (guess == guessWord[i])
                return 0;
            if (guess == theWordSecret[i])
            {
                guessWord[i] == guess;
                hits++;
            }
        }
        return hits;
    }

    void poorStiff(int bodyPart)
    {

        if (bodyPart == 1)
        {
            cout << "_______" << endl;
            cout << "|      }" << endl;
            cout << "|      O" << endl;
            cout << "|" << endl;
            cout << "|" << endl;
            cout << "|" << endl;
            cout << "|" << endl;
            cout << "_______________" << endl;

        }
        else if (bodyPart == 2)
        {
            cout << "_______" << endl;
            cout << "|      }" << endl;
            cout << "|      O" << endl;
            cout << "|      |" << endl;
            cout << "|" << endl;
            cout << "|" << endl;
            cout << "|" << endl;
            cout << "_______________" << endl;

        }
        else if (bodyPart == 3)
        {
            cout << "_______" << endl;
            cout << "|      }" << endl;
            cout << "|      O" << endl;
            cout << "|     /|" << endl;
            cout << "|" << endl;
            cout << "|" << endl;
            cout << "|" << endl;
            cout << "_______________" << endl;

        }
        else if (bodyPart == 4)
        {
            cout << "_______" << endl;
            cout << "|      }" << endl;
            cout << "|      O" << endl;
            cout << "|     /|" << endl;
            cout << "|    / " << endl;
            cout << "|" << endl;
            cout << "|" << endl;
            cout << "_______________" << endl;

        }
        else if (bodyPart == 5)
        {
            cout << "_______" << endl;
            cout << "|      }" << endl;
            cout << "|      O" << endl;
            cout << "|     /|" << endl;
            cout << "|    / |" << endl;
            cout << "|" << endl;
            cout << "|" << endl;
            cout << "_______________" << endl;

        }
        else if (bodyPart == 6)
        {
            cout << "_______" << endl;
            cout << "|      }" << endl;
            cout << "|      O" << endl;
            cout << "|     /|\." << endl;
            cout << "|    / | \." << endl;
            cout << "|" << endl;
            cout << "|" << endl;
            cout << "_______________" << endl;

        }
        else if (bodyPart == 7)
        {
            cout << "_______" << endl;
            cout << "|      }" << endl;
            cout << "|      O" << endl;
            cout << "|     /|\." << endl;
            cout << "|    / | \." << endl;
            cout << "|     /" << endl;
            cout << "|" << endl;
            cout << "_______________" << endl;

        }
        else if (bodyPart == 8)
        {
            cout << "_______" << endl;
            cout << "|      }" << endl;
            cout << "|      O" << endl;
            cout << "|     /|\." << endl;
            cout << "|    / | \." << endl;
            cout << "|     / \." << endl;
            cout << "|" << endl;
            cout << "_______________" << endl;

        }
        else if (bodyPart == 9){
            cout << "_______" << endl;
            cout << "|      }" << endl;
            cout << "|      O" << endl;
            cout << "|     /|\." << endl;
            cout << "|    / | \." << endl;
            cout << "|     / \." << endl;
            cout << "|    / " << endl;
            cout << "_______________" << endl;

        }
        else if (bodyPart == 10)
        {
            cout << "_______" << endl;
            cout << "|      }" << endl;
            cout << "|      O" << endl;
            cout << "|     /|\." << endl;
            cout << "|    / | \." << endl;
            cout << "|     / \." << endl;
            cout << "|    /   \." << endl;
            cout << "_______________" << endl;
        }
    }
  • 0
    Трех разделов кода недостаточно, чтобы определить, почему ваша программа не работает. Вы должны опубликовать все это, желательно сократить до минимума, чтобы оно скомпилировалось и работало.
  • 0
    Не уверен, сколько еще вы хотите, но это весь код, если это поможет.
Показать ещё 1 комментарий
Теги:
visual-studio-2013

2 ответа

1
Лучший ответ

Вы пытались отладить? Если вы пройдете через свой код, вы сразу же найдете проблему, которая находится здесь:

            if (theWord == mystery) // the word is the same as mystery
            {
                cout << theWord << endl;
                cout << "\n\n Awesome, you guessed it. \n\n";
                break;    // problem here
                if (attemptsGame < bestScore)
                {
                    bestScore = attemptsGame;

                }
                // break should be here
            }

Вы выходите из своего цикла перед вашей логикой проверки. Поэтому переместите оператор break после проверки, потому что этот код никогда не будет выполнен.

  • 0
    +1 за разрыв, который я не нашел на первый взгляд (я нашел его сейчас, изучая код, но вы уже нашли его).
  • 0
    Да, это исправило это. Очень признателен.
Показать ещё 1 комментарий
1

Для начала включите свои предупреждения о компиляторе, вы получите много от быстрого просмотра вашего кода.

Изменить это

guessWord[i] == guess;

к этому

guessWord[i] = guess;


С этой точки зрения

if (wordFill(letter, theWord, mystery) == 0) //fuction call
{    
  ...
  cout << "You have entered a letter that isn't in the word, guess again. \n\n";
}
else
{
    ...

    if (theWord == mystery) // the word is the same as mystery
    {
       cout << theWord << endl;
       cout << "\n\n Awesome, you guessed it. \n\n";
       break;
       ...
    }
 }

Здесь, когда вы входите в первое, если, тогда вы введете второй, если тоже, что не имеет смысла. Это происходит потому, что theWord и mystery - это пустые строки!

Также обратите внимание, что разрыв должен быть после этой части кода:

if (attemptsGame < bestScore)
{
   bestScore = attemptsGame;    
}

потому что как бы то ни было, эта часть кода никогда не будет выполнена.


Я предлагаю принять этот ответ (не относящийся к вашей логической ошибке)

Система ( "пауза"); - Почему это неправильно?

  • 1
    +1. Есть еще несколько областей, которые будут выдавать предупреждения компилятора, включая проблемную область в коде OP.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню