Starting today, I will be remaking hangman and positing the pieces of my code as it grows. I have been working on it and I just want to see that I can do it. Any feedback on the code that I post is appreciated. So, without further ado, here is the code as it stands so far:
// Hangman
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <string>
usingnamespace std;
int main(){
ifstream infile;
int x;
string words[100]; // DON'T REALLY WANT MORE THAN 100 WORDS ANYWAY.
char player_choice;
// READ THE NUMBER OF WORDS AND THE ACTUAL WORDS IN FROM THE FILE.
infile.open("hangman_input.txt");
while(infile){
infile >> x;
for(int i = 0; i < x; i++){
infile >> words[i];
}
}
cout << "Welcome to Hangman!" << endl;
bool play = true;
while(play == true){
int misses = 0;
int state = 0;
// PICK A WORD FROM OUR LIST
long seed = time(NULL);
srand(seed);
int index = rand() % x;
string puzzle = words[index];
// MAKE AN ARRAY OF DASHES FOR THE WORD
char word_copy[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++){
word_copy[i] = '-';
}
bool computer_ready = true;
bool player_win = false;
cout << "Here is your word: " << endl << endl;
for (int i = 0; i < puzzle.length(); i++){
cout << word_copy[i];
}
while(computer_ready = true){
cout << "\n\nGuess a letter: ";
cin >> player_choice;
// EVALUTATE WHETHER OR NOT THE PLAYER WAS CORRECT AND REFLECT IT TO THE SCREEN
for(int i = 0; i < puzzle.length(); i++){
if (player_choice == puzzle[i]){
word_copy[i] = player_choice;
}
if (player_choice != puzzle[i]){
misses += 1;
state += 1;
}
}
if (player_win == true){
cout << "You win!" << endl;
play = false;
computer_ready = false;
}
if (player_win == false){
for(int i = 0; i < puzzle.length(); i++){
cout << word_copy[i];
}
}
}
}
return 0;
}
I have made an input file named "hangman_input.txt" with an integer as the first line representing the number of words in the file and the list of words that follows that.
Thanks for that line 51 thing! I didn't even notice that I did that. When the player finishes the game, they will be asked to play again and I want it to pick another word from my list. That's why I have srand where it is. Otherwise, it would just pick the same word over and over, right?