Let's Play Hangman Challenge

This is the place for ALL of the user submitted challenges. If you create a little challenge/mission/riddle/whatever, post it here.
Forum rules
Do not post missions that you did NOT create without proper citing.

Re: Let's Play Hangman Challenge

Post by -Ninjex- on Sat Sep 21, 2013 3:20 am
([msg=77446]see Re: Let's Play Hangman Challenge[/msg])

@cent +205

I Like the use of D lang, I might get into it soon :D
It's great that you commented up the code, that's what I like to see is nice organized and well documented code. For that you get an additional +30 points
image
For those that know
K: 0x2CD8D4F9
User avatar
-Ninjex-
Moderator
Moderator
 
Posts: 1691
Joined: Sun Sep 02, 2012 8:02 pm
Blog: View Blog (0)


Re: Let's Play Hangman Challenge

Post by Ayr3s on Sun Jul 12, 2015 1:06 am
([msg=88966]see Re: Let's Play Hangman Challenge[/msg])

Done in Python 2

Code: Select all
#!/usr/bin/python2

import sys
import string
import random

def print_hangman(guesses_left):
    hangman_line1="   "
    hangman_line2="   "
    hangman_line3="   "
    hangman_line4="   "
    game_over=""
    if guesses_left <= 5:
        hangman_line1="(_)"
    if guesses_left <= 4:
        hangman_line2=" | "
        hangman_line3=" | "
    if guesses_left <= 3:
        hangman_line2=" |/"
    if guesses_left <= 2:
        hangman_line2="\\|/"
    if guesses_left <= 1:
        hangman_line4="  \\"
    if guesses_left == 0:   
        hangman_line4="/ \\"
        game_over="   GAME OVER!"
   
    print("----------------------")
    print("Guesses Left: %d" % guesses_left)
    print("%s" % game_over)
    print("   _________   ")
    print("   |/      |   ")
    print("   |      %s " % hangman_line1)
    print("   |      %s " % hangman_line2)
    print("   |      %s " % hangman_line3)
    print("   |      %s " % hangman_line4)
    print("   |           ")
    print("___|___        \n")

def choose_word(wordlist):
    try:
        f = open(wordlist)
    except:
        print("Cannot open wordlist!")
        sys.exit(0)
       
    words = f.readlines()
    f.close()
    selected_word = words[random.randint(0, len(words)-1)].strip()
    del words
    return selected_word

def generate_template(word):
    template = []
    for char in word:
        template.append("_")
    return template
   
def try_guess(letter):
    global guess_word
    global guesses_left
    global user_guesses
   
    if letter not in guess_word:
        if letter in user_guesses:
           print("\nYou already tried that!")
        else:
            guesses_left += -1
            user_guesses.append(letter)
    else:
        update_template(letter)
           
def update_template(letter):
    global template
    global guess_word
   
    for i in range(len(guess_word)):
        if letter == guess_word[i]:
            template[i] = letter
   

### Entry point ###

if len(sys.argv) != 2:
    print("Pass a wordlist as the only argument, please.")
    sys.exit(0)

guess_word = choose_word(sys.argv[1])
template = generate_template(guess_word)
user_guesses = []

guesses_left = 6
print_hangman(guesses_left)
print("%s\n" % " ".join(template))
# Main Loop
while guesses_left != 0:
    if "".join(template) == guess_word:
        print("You won!")
        break
    print("[qq] to quit")
    user_input = raw_input("Your guess: ").lower()
   
    if user_input == "qq":
        print("Goodbye")
        break
   
    try_guess(user_input)
    print_hangman(guesses_left)
    print("%s\n" % " ".join(template))
    print("You already tried: %s" % ",".join(user_guesses))

print("The word was: %s" % guess_word)
User avatar
Ayr3s
New User
New User
 
Posts: 29
Joined: Mon Feb 02, 2015 2:34 pm
Blog: View Blog (0)


Re: Let's Play Hangman Challenge

Post by -Ninjex- on Mon Jul 13, 2015 10:27 am
([msg=88996]see Re: Let's Play Hangman Challenge[/msg])

Ayr3s wrote:Done in Python 2


Great work :D
I need to fix up some server stuff and get things hosted correctly again and distribute points accordingly.
image
For those that know
K: 0x2CD8D4F9
User avatar
-Ninjex-
Moderator
Moderator
 
Posts: 1691
Joined: Sun Sep 02, 2012 8:02 pm
Blog: View Blog (0)


Re: Let's Play Hangman Challenge

Post by boriz666 on Thu Jul 16, 2015 10:34 am
([msg=89021]see Re: Let's Play Hangman Challenge[/msg])

Done in C++,
haven't seperated it into header and source, cause i wanted it all in one file (easier for the user to dl),
normally it would be seperated into class source, class header and main program file with includes.

The Hangman class also include a debug mode ( game.setDebugStatus(1); )
so the user of the class can see debug information at the moment its the current word displayed
in the start.

Code: Select all

// g++ -std=c++0x -o hangman hangman.cpp

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iterator>
#include <algorithm>

using namespace std;

void remove_carriage_return(std::string& line);

// Hangman class
// Synopsis:
//   
//   Hangman game = Hangman(wordList);
//   game.setDebugStatus(1);
//   game.start();
//
//
//
class Hangman {

  public:
   Hangman(vector<string> wordList):wordList(wordList)
    {      
     debug=0;
    }

       vector<string> getWordList() const {
     return wordList;
   }

   int getDebugStatus() const {
          return debug;
   }

   // Debug status shows the current word, that we are trying to guess   
   void setDebugStatus(int d) {
     if (d == 1) {debug = 1;}
     else {debug = 0;}
   
   }

   //
        // public member function that initialize the game anew,
        // sets the current word we need to guess (random function could be improved)
   // clears the wordGuess progression vector to contain "_"'s eg. clearing the gameboard
   // draws the gamefield and enters the gameloop
   void start() {

            srand (time(0));
            int index = rand() % wordList.size();
       currentWord = wordList[index];
            currentWordSize = currentWord.size();
            nrOfGuessesAllowed=6;

       wrongGuesses = 0;
       gameSolved = 0;

            wordGuess.clear();
       wordGuess.resize(currentWordSize);

       char * cstr = new char [currentWord.length()+1];
      
       for (int i = 0; i < currentWordSize; i++) {
        wordGuess[i] = string("_");
       }

       drawGameField();      
       gameLoop();
   }


  private:
   vector<string> wordList;
        vector<string> wordGuess;
   int nrOfGuessesAllowed;
        int wrongGuesses;
        string currentWord;
        int currentWordSize;
        int gameSolved;
   int debug;


   // simple function to "clear" the screen, a better aproach could be
        // to use the ncurses library to draw the screen, but this is a bit overkill.
        void ClearScreen()
        {
     cout << string( 100, '\n' );
        }


   // member function to draw the hangman,
        // each stage has its own unique ascii drawing, so you have the
        // option to change this to your liking.
        // This function rely on the wrongGuesses variable in order to
        // to draw the hangman.

   void DrawHangman() {

          vector<string> hangmanSprites;

     hangmanSprites.push_back(
           string("                    \n") +
       "      _________     \n" +
       "      |/      |     \n" +
       "      |             \n" +
       "      |             \n" +
       "      |             \n" +
       "      |             \n" +
       "      |             \n" +
       "   ___|___          \n" +
       "                    \n");

     hangmanSprites.push_back(
           string("                    \n") +
       "      _________     \n" +
       "      |/      |     \n" +
       "      |      (_)    \n" +
       "      |             \n" +
       "      |             \n" +
       "      |             \n" +
       "      |             \n" +
       "   ___|___          \n" +
       "                    \n");

     hangmanSprites.push_back(
           string("                    \n") +
       "      _________     \n" +
       "      |/      |     \n" +
       "      |      (_)    \n" +
       "      |       |     \n" +
       "      |       |     \n" +
       "      |             \n" +
       "      |             \n" +
       "   ___|___          \n" +
       "                    \n");

     hangmanSprites.push_back(
           string("                    \n") +
       "      _________     \n" +
       "      |/      |     \n" +
       "      |      (_)    \n" +
       "      |      \\|    \n" +
       "      |       |     \n" +
       "      |             \n" +
       "      |             \n" +
       "   ___|___          \n" +
       "                    \n");

     hangmanSprites.push_back(
           string("                    \n") +
       "      _________     \n" +
       "      |/      |     \n" +
       "      |      (_)    \n" +
       "      |      \\|/   \n" +
       "      |       |     \n" +
       "      |             \n" +
       "      |             \n" +
       "   ___|___          \n" +
       "                    \n");

     hangmanSprites.push_back(
           string("                    \n") +
       "      _________     \n" +
       "      |/      |     \n" +
       "      |      (_)    \n" +
       "      |      \\|/   \n" +
       "      |       |     \n" +
       "      |      /      \n" +
       "      |             \n" +
       "   ___|___          \n" +
       "                    \n");


     hangmanSprites.push_back(
           string("                    \n") +
       "      _________     \n" +
       "      |/      |     \n" +
       "      |      (_)    \n" +
       "      |      \\|/   \n" +
       "      |       |     \n" +
       "      |      / \\      \n" +
       "      |             \n" +
       "   ___|___          \n" +
       "                    \n");

       cout << hangmanSprites[wrongGuesses];

   }


   // Member function to draw how many guesses the user have left.
   // Again uses internal member variables to determine this.
   void DrawGuessesLeft() {
     cout << "Guesses Left: " << (nrOfGuessesAllowed-wrongGuesses) << endl;
   }


   // Member function to draw the progression of the current word
        // the user is trying to guess.
        // progression is stored in a vector with each element containing either "_"
        // or the corresponding correct letter.
   void DrawCurrentWordProgress() {
          cout << "Current Word " << endl;
          for (int i=0; i < wordGuess.size(); i++) {
            cout << wordGuess[i] << " ";
          }
          cout << endl;
   }


   // Member function tasked with drawing the current gamefield,
   // based on the internal gamestate.
        void drawGameField() {
           ClearScreen();
      if (debug)  cout << "(" << currentWord << ")" << endl;
      DrawGuessesLeft();
      DrawHangman();
           DrawCurrentWordProgress();
   }

   // Input to the game and update the gamestate as a response to this.
        // It was decided not to give an error if the user enter an already used letter.
        // instead the game just re-update the progression vector.
   void gameMove() {
            string guess;
            cout << "Please enter a letter ";
            getline(cin,guess);

       if ( guess.length() == 1) {

         const char* cWd = currentWord.c_str();
         const char* gs  = guess.c_str();

         int correctGuess = 0;

              for (int i = 0; i < currentWordSize; i++) {
               if ( cWd[i] == gs[0] ) {
                 wordGuess[i] = guess;
            correctGuess = 1;
               }
              }

         if (! correctGuess) { wrongGuesses++;}

         updateGameState();
         if ( gameSolved ) {
      cout << endl;
                cout << "CONGRATS, YOU AVOIDED HANGING!!! " << endl;
      cout << "You you guessed wrong " << wrongGuesses << " times" << endl;
         }
       }
   }

   // function to check if the game is solved or not based on the
        // internal state of the game object.
        // gameSolved will be updated accordingly
   void updateGameState() {
         const char* cWd = currentWord.c_str();
         int solved = 1;

         for (int i = 0; i < currentWordSize; i++) {
        const char* wg  = wordGuess[i].c_str();
           if ( wg[0] == '_' ) {
             solved = 0;
           }
         }
         gameSolved=solved;
   }


   //
        // Main game loop, runs as long as the game isn't solved or
        // the nuber of turns has been exceeded.
        //
   void gameLoop() {
     while (wrongGuesses <= nrOfGuessesAllowed && gameSolved==0) {
            drawGameField();
       gameMove();      
     }

          if ( gameSolved == 0) {
       cout << "YOU ARE HANGING IN THE GALLOWS! " << endl;
       cout << "Practice more or you will burn in hell!!" << endl;
       cout << "The correct word was: " << currentWord << endl;
     }

   }

};




int main(int argc, char** argv) {


   // trivial commandline argument checking
   if ( argc != 2) {
     cout << "Please enter a wordlist file as the first argument!\n\n";
     return 1;
   }

   string wordFilename = string(argv[1]);
   ifstream wordFile(wordFilename);

   if (!wordFile) {
     cout << "Input file " << wordFilename << " doesn't exist!!\n\n";
     return 1;
   }


   // initialize the wordList vector so each element contains a word from
   // the input file.

   vector<string> wordList;
   string line;

   while (getline(wordFile, line)) {
     remove_carriage_return(line);
     wordList.push_back(line);
   }

   // initialize the game using the wordList vector we prepared above
   // as the list of words to use in the game.
   Hangman game = Hangman(wordList);
   game.setDebugStatus(0);

   // start the hangman game
   game.start();

}

void remove_carriage_return(std::string& line)
{
    if (*line.rbegin() == '\r')
    {
        line.erase(line.length() - 1);
    }
}

boriz666
Experienced User
Experienced User
 
Posts: 99
Joined: Tue Mar 24, 2015 11:53 am
Blog: View Blog (0)


Previous

Return to User Submitted

Who is online

Users browsing this forum: No registered users and 0 guests