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 Assassian360 on Thu Aug 15, 2013 11:23 pm
([msg=76873]see Re: Let's Play Hangman Challenge[/msg])

Here's an updated version that should compile in g++.

I used http://www.compileonline.com/compile_cpp_online.php to test the g++ compiling.

Code: Select all
#include <iostream>
#include <string>
#include <time.h>
#include <vector>
#include <algorithm>
using namespace std;

bool showVisibleString(string selectedWord, vector<char> usedLetters);
void showUsedLetters(vector<char> usedLetters);
void showHangMan(int guesses);

int main(int argc, char* argv[]) {
    srand(time(NULL));
   int selectedWord = rand() % (argc - 1) + 1;
   string solutionWord = string(argv[selectedWord]);
   vector<char> usedLetters = vector<char>();
   int guesses = 6;
   char guessInput;

   while(true) {
      showUsedLetters(usedLetters);
      bool complete = showVisibleString(solutionWord, usedLetters);
      if(complete){
         cout << "You guessed the word " << solutionWord
            << " correctly! Well done!" << endl;
         break;
      } else if(!guesses) {
         cout << "Game over, the correct word was: "
            << solutionWord << endl;
         break;
      } else {
         cout << "Enter your guess: ";
         cin >> guessInput;
         if(find(usedLetters.begin(), usedLetters.end(),
                  guessInput) != usedLetters.end()) {
            cout << "You already guessed that!" << endl;
         } else {
            usedLetters.push_back(guessInput);
            if(find(solutionWord.begin(), solutionWord.end(), guessInput)
                     == solutionWord.end())
            {
               cout << "Guesses left: " << --guesses << endl;
               showHangMan(guesses);
            }
         }
      }
   }

   cin >> selectedWord;
   return 0;
}

bool showVisibleString(string selectedWord, vector<char> usedLetters) {
   bool complete = true;
   cout << "Word: ";
   for (int i = 0; i < selectedWord.size(); ++i) {
      if(find(usedLetters.begin(), usedLetters.end(), (char)(selectedWord[i]))
               != usedLetters.end()) {
         cout << selectedWord[i] << " ";
      } else {
         cout << "_ ";
         complete = false;
      }
   }
   cout << endl;
   return complete;
}

void showUsedLetters(vector<char> usedLetters) {
   cout << "Used Letters: ";
   if(usedLetters.size() == 0)
      cout << "You have not used any letters yet.";

   for (int i = 0; i < usedLetters.size(); ++i) {
      if(i != 0)
         cout << ", ";
      cout << usedLetters[i];
   }
   cout << endl;
}

void showHangMan(int guesses) {
   cout << "\t_________\n\t|/      |\n\t|      (_)";
   cout << "\n\t|      " << ((guesses<4)?"\\":" ");
   cout << ((guesses<5)?"|":" ") << ((guesses<3)?"/":" ");
   cout << "\n\t|       " << ((guesses<5)?"|":" ");
   cout << "\n\t|      " << ((guesses<2)?"/ ":" ");
   cout << ((guesses<1)? "\\":" ") << "\n\t|\n     ___|___\n";
}
Assassian360
Poster
Poster
 
Posts: 135
Joined: Sat Jun 26, 2010 1:37 am
Blog: View Blog (0)


Re: Let's Play Hangman Challenge

Post by caracarn001 on Fri Aug 16, 2013 1:57 am
([msg=76878]see Re: Let's Play Hangman Challenge[/msg])

currently the wordlist I use are all the arguments given in at the commandline (everything in args). Do you need the wordlist to be read from a file given in at cmd-line?
User avatar
caracarn001
New User
New User
 
Posts: 42
Joined: Thu Nov 04, 2010 5:23 am
Blog: View Blog (0)


Re: Let's Play Hangman Challenge

Post by pretentious on Fri Aug 16, 2013 7:29 am
([msg=76881]see Re: Let's Play Hangman Challenge[/msg])

caracarn001 wrote:currently the wordlist I use are all the arguments given in at the commandline (everything in args). Do you need the wordlist to be read from a file given in at cmd-line?

I'd say hard code it to begin with. It's easier in my opinion to debug and stuff. You can always change the expression from a string to arg once you know for sure
Goatboy wrote:Oh, that's simple. All you need to do is dedicate many years of your life to studying security.

IF you feel like exchanging ASCII arrays, let me know ;)
Can you say brainwashing It's a non stop disco
User avatar
pretentious
Addict
Addict
 
Posts: 1203
Joined: Wed Mar 03, 2010 12:48 am
Blog: View Blog (0)


Re: Let's Play Hangman Challenge

Post by -Ninjex- on Fri Aug 16, 2013 7:47 am
([msg=76883]see Re: Let's Play Hangman Challenge[/msg])

caracarn001 wrote:currently the wordlist I use are all the arguments given in at the commandline (everything in args). Do you need the wordlist to be read from a file given in at cmd-line?


Yes, when running the program from command line, you should specify a file, once that file is specified the program will grab a random word from within the file for the game.
For example say a file, wordlist contains 5 words: hey, hello, dude, say, maybe
at the command line: java hangman wordlist
then the program will select one of the above words from within the file wordlist
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 PinkFloyd22 on Mon Aug 19, 2013 9:36 am
([msg=76905]see Re: Let's Play Hangman Challenge[/msg])

Just to check when you mean the wordlist in command line.You mean when i start the hangman program from cmd I should use the wordlist as an arg so basically you can use different wordlists right?
This challenge seems like a lot of fun :D
^_^
User avatar
PinkFloyd22
Experienced User
Experienced User
 
Posts: 70
Joined: Sat Sep 26, 2009 4:35 am
Blog: View Blog (0)


Re: Let's Play Hangman Challenge

Post by -Ninjex- on Wed Aug 21, 2013 7:00 pm
([msg=76939]see Re: Let's Play Hangman Challenge[/msg])

PinkFloyd22 wrote:Just to check when you mean the wordlist in command line.You mean when i start the hangman program from cmd I should use the wordlist as an arg so basically you can use different wordlists right?
This challenge seems like a lot of fun :D


That is correct.
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 Amazingred on Fri Sep 20, 2013 7:05 pm
([msg=77438]see Re: Let's Play Hangman Challenge[/msg])

Python. How's this:

Code: Select all
import re, sys
from random import choice

def showmap(hangmanpic):
    """Will show the hangman pic after subtracting any
    characters holding the place of a future body part"""
    tempmap=''
    x=str(range(7))
    for i in hangmanpic:
        if i in x:
            tempmap+=' '
        else:
            tempmap+=i
    return tempmap

def addbodypart(remaining, hangmanmap):
    """takes the hangman map and substitutes in a body
    part when a wrong answer is chosen.  Returns the new
    hangmanmap"""
    bodyparts={'6':'(_)',
           '5':'|',
           '3':'\\\\',
           '2':'\\\\',
          '4':'/',
           '1':'/'
          }
    return re.sub(str(remaining), bodyparts[str(remaining)], hangmanmap)

def StartGame(hangmanmap, word):
    """Starts the game"""
    dashword, wrong=[], []
    remaining=6
    for i in word:
        dashword.append('_')
    while remaining>0:
        if '_' not in dashword:
            remaining=0
            continue
        for i in range(5):
            print ""
        print "Guesses Left = %d" %(remaining)
        print showmap(hangmanmap)
        print ""
        print "Used Letters: %s" %(', '.join(wrong))
        print "Word: %s"%(' '.join(dashword))
        guess=str(raw_input('Guess a letter:')).lower()
        if guess in str(wrong)+str(dashword):
            print ""
            print "Sorry but you have already guessed that letter.  Please guess again."
            print ""
            continue
        if guess not in word:
            hangmanmap=addbodypart(remaining, hangmanmap)
            remaining-=1
            wrong.append(guess)
        else:
            for i in range(0, len(word)):
                if word[i]==guess:
                    dashword[i]=guess
    if '_' not in dashword:
        for i in range(5):
            print ""
        print "You WIN!  Congrats"
        print "The word was %s" %(word)
        print showmap(hangmanmap)
        print "Used Letters: %s" %(', '.join(wrong))
        print "Word: %s"%(' '.join(dashword))
    else:
        for i in range(5):
            print ""
        print showmap(hangmanmap)
        print "Word: %s" %(word)
        print "Sorry but you've ran out of guesses! You Lose!  The correct word was %s" %(word)

def main():
    word=str(choice([line.strip() for line in open(sys.argv[1])])).lower()
    hangmanmap="""          _________
          |/      |
          |      6
          |      354
          |       5
          |      1 2
          |
       ___|___"""

    print "Welcome to AmazingReds Hangman Game!"
    print "6 wrong answers and YOU LOSE!  Good Luck."
    StartGame(hangmanmap, word)
if __name__ == '__main__':
    main()
There are 10 types of people in the world. Those who understand binary and those who don't.
User avatar
Amazingred
Experienced User
Experienced User
 
Posts: 74
Joined: Wed Jul 25, 2012 7:10 pm
Location: Wayyyyyy out there
Blog: View Blog (0)


Re: Let's Play Hangman Challenge

Post by -Ninjex- on Fri Sep 20, 2013 9:17 pm
([msg=77439]see Re: Let's Play Hangman Challenge[/msg])

@Amazingred Seems to be the best code I've seen so far, very organized and works well. You will receive an additional 25 points for a total of: +200
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 Amazingred on Fri Sep 20, 2013 10:47 pm
([msg=77440]see Re: Let's Play Hangman Challenge[/msg])

Wow, ty.
There are 10 types of people in the world. Those who understand binary and those who don't.
User avatar
Amazingred
Experienced User
Experienced User
 
Posts: 74
Joined: Wed Jul 25, 2012 7:10 pm
Location: Wayyyyyy out there
Blog: View Blog (0)


Re: Let's Play Hangman Challenge

Post by centip3de on Sat Sep 21, 2013 2:32 am
([msg=77444]see Re: Let's Play Hangman Challenge[/msg])

Done in D:

Code: Select all
import std.stdio;
import std.file;
import std.random;
import std.c.stdlib;
import std.array;
import std.string;
import std.conv;

void draw(int level)
{
    string image;
    if(level >= 1)
    {
        image = "|      (_)\n";
    }
    if(level >= 2)
    {
        image ~= "|      \\|";
    }
    if(level >= 3)
    {
        image ~= "/\n";
    }
    if(level >= 4)
    {
        image ~= "|       |\n";
    }
    if(level >= 5)
    {   
        image ~= "|      /";
    }
    if(level >= 6)
    {
        image ~= "\\\n";
    }
    writeln("_________");
    writeln("|/      |");
    if(image)
    {
        writeln(image);
    }
    for(int i = 0; i < (5 - level); i++)
    {
        writeln("|");
    }
    writeln("|__");
}
           
void main(string args[])
{
    auto gen = Random(unpredictableSeed);;
    string text = toLower(cast(string)read(args[1]));
    auto tokens = text.split();
    auto random = uniform(0, tokens.length, gen);
    string originalWord = tokens[random];
    char[] word = to!(char[])(tokens[random]);
    int guesses = 6;
    int wrong = 0;
    int[] guessed;
    char[] display;
    string usedLetters;
    int correct = 0;
    foreach(character; word)
    {
        display ~= "_ ";
    }
    while(guesses != 0)
    {
        writeln("Guesses left: ", guesses);
        draw(wrong);
        writeln("Word:", display);
        auto input = toLower(strip(readln()));
        char guess = input[0];
        if(usedLetters.indexOf(guess) != -1)
        {
            writeln("Cannot use a letter you've already used");
            continue;
        }
        usedLetters ~= guess ~ ", ";
        writeln("Used letters: ", usedLetters);
        while(indexOf(word, guess) != -1)
        {
            correct++;
            auto index = indexOf(word, guess);
            display[index * 2] = guess;
            word[index] = '*';
            if(word.length == correct)
            {
                writeln("You've won!");
                exit(0);
            }
        }
        if(indexOf(word, guess) == -1)
        {
            wrong++;
            guesses--;
        }
    }
    writeln("Game over, the correct word was: ", originalWord);
}


And with your petty comments and good looks (D):
Code: Select all
import std.stdio;
import std.file;
import std.random;
import std.c.stdlib;
import std.array;
import std.string;
import std.conv;

/* Draw the dude and the lynching pole */
void draw(int level)
{
    /* The image is the guy */
    string image;
    /* If we only screwed up once, only add a head */
    if(level >= 1)
    {
        image = "|      (_)\n";
    }
    /* If we screwed up twice, add a head and an arm, etc. */
    if(level >= 2)
    {
        image ~= "|      \\|";
    }
    if(level >= 3)
    {
        image ~= "/\n";
    }
    if(level >= 4)
    {
        image ~= "|       |\n";
    }
    if(level >= 5)
    {   
        image ~= "|      /";
    }
    if(level >= 6)
    {
        image ~= "\\\n";
    }

    /* We're going to need the top to be drawn every time, no matter what. */
    writeln("_________");
    writeln("|/      |");

    /* If image actually contains something, then draw it */
    if(image)
    {
        writeln(image);
    }

    /* For every level we've screwed up, we need 1 less '|' because a body part is occupying that spot, for a total of 5 levels. So
       5 - levels = how many extra '|' we need to draw */
    for(int i = 0; i < (5 - level); i++)
    {
        writeln("|");
    }

    /* We'll also need to draw a floor everytime */
    writeln("|__");
}
           
void main(string args[])
{
    /* Reading in the file specified by argument one. Because it could be binary, we need to specify that we're expecting (and reading in) strings */
    string text = cast(string)read(args[1]);
    text = toLower(text);
   
    /* Split the text up (into tokens) on each whitespace found and return the tokens in an array */
    auto tokens = text.split();

    /* Getting a uniform random number based on an unpredictableSeed (a built in variable) */
    auto gen = Random(unpredictableSeed);
    auto random = uniform(0, tokens.length, gen);

    /* We'll be editting the word later on, so we need to save it in it's current state */
    string originalWord = tokens[random];

    /* Converting the word we'll be editing to a char array */
    char[] word = to!(char[])(tokens[random]);

    /* The amount of guesses allowed */
    int guesses = 6;

    /* The amount of times you've guessed wrong (for the draw function argument), and the amount of times you've guessed right */
    int wrong = 0;
    int correct = 0;
   

    /* The display of letters on the screen, '_ _ e _ a' */
    char[] display;

    /* The letters you've used */
    string usedLetters;

    /* For each character in our word */
    foreach(character; word)
    {
        /* Add another underscore and space */
        display ~= "_ ";
    }

    /* While we still have guesses left */
    while(guesses != 0)
    {

        writeln("Guesses left: ", guesses);

        /* Draw our lynching pole based on how many times we were wrong */
        draw(wrong);

        writeln("Word:", display);

        /* Read in input, strip \r\n and space from it, and make it all lower case */
        auto input = readln();
        input = strip(input);
        input = toLower(input);

        /* Hangman is a character based game, so we only need the first character of input */
        char guess = input[0];

        /* If we've already guessed that letter, display a message and move one */
        if(usedLetters.indexOf(guess) != -1)
        {
            writeln("Cannot use a letter you've already used");
            continue;
        }

        /* Add the letter to letters used, and make i tlook pretty */
        usedLetters ~= guess ~ ", ";
        writeln("Used letters: ", usedLetters);

        /* While there's another letter that matches the guess */
        while(indexOf(word, guess) != -1)
        {
            /* Increase the amount of times we were correct */
            correct++;

            /* Get the character position */
            auto index = indexOf(word, guess);

            /* Change the correct underscore to the correct letter */
            display[index * 2] = guess;

            /* 'null' out the letter in the word array */
            word[index] = '*';

            /* If we've guessed all the letters in the word, then we won! */
            if(word.length == correct)
            {
                writeln("You've won!");
                exit(0);
            }
        }
       
        /* If we guessed wrong, then increase the amount of times we've guessed wrong, and subtract a guess */
        if(indexOf(word, guess) == -1)
        {
            wrong++;
            guesses--;
        }
    }
    /* If we get this far, we must have guessed more than 6 times, and lost :C */
    writeln("Game over, the correct word was: ", originalWord);
}
Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. -Rick Cook
User avatar
centip3de
Addict
Addict
 
Posts: 1479
Joined: Fri Aug 20, 2010 5:46 pm
Blog: View Blog (0)


PreviousNext

Return to User Submitted

Who is online

Users browsing this forum: No registered users and 0 guests