r/badcode • • Apr 22 '19

[deleted by user]

[removed]

22 Upvotes

13 comments sorted by

11

u/Cakeofdestiny Apr 22 '19 edited Apr 22 '19

I call it High Stakes Hangman. This will seriously BSOD your machine if you kill the hangman, so don't be surprised when that happens. Also obviously will only build in Windows

Play at your own risk :)

Edit: After trying to compile it with a variety of different of configurations, I can't get it to compile on g++ with the BSOD enabled, so I modified it to disable the BSOD with any non-MSVC compiler. You can also disable the BSOD yourself if you #define DONT_BSOD at the top. To compile with g++:

g++ HighStakesHangman.cpp -o HighStakesHangman.exe --std=c++11 -static-libstdc++

/u/Vusys

4

u/sac_boy Apr 23 '19

All my hats off to you for using SetLastError/GetLastError to grab random words from Windows error strings. My god.

0

u/[deleted] Apr 22 '19

[deleted] — view deleted comment

2

u/Cakeofdestiny Apr 22 '19 edited Apr 22 '19

I edited the code, so now you can just uncomment line 31 (#define DONT_BSOD), and it will disable the BSOD code. As for the rest, the entire word generation is WINAPI, so I'm afraid that if you're using a Linux VM you will not be able to experience its magnificence :(

Edit: See original post in a bit

2

u/sac_boy Apr 23 '19 edited Apr 23 '19

Alright, here we go. Here's a hangman implementation in pure, classic, no-nonsense C. It compiles, it plays well...but it is a homage to those classic horror codebases that were acceptable in the dark past.

In other words, this is exactly the sort of thing I would write 20 years ago.

In further homage to the games of the past, I have put a game-breaking bug in there for attentive readers to spot, a memory leak under certain conditions, and a buffer overflow. Further explanation down in the hidden comment below.

// ULTIMATE HANGMAN (c) sac_boy 2019
// For /r/badcode
// Compile with...any C compiler you have handy I suppose

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

static char wordList[] =
    " " // DO NOT REMOVE
    "nonphf\0nppvqrag\0nssrpgvba\0nypbuby\0nccyr\0nccyvpngvba\0nccyl\0nfgbavfu\0nf"
    "gebabzl\0nibvq\0oreel\0oyrffrq\0pneany\0purjl\0penzc\0pebffsvg\0phovp\0phefrq"
    "\0qribvq\0qverpgrq\0rkphfr\0rkgehqr\0sngure\0sberfxva\0tenaqvbfr\0urnqybpx\0v"
    "aprfg\0whvpr\0whvpl\0xabjyrqtr\0xbnyn\0ylapu\0abmmyr\0bzyrggr\0bibvq\0bihyngr"
    "\0crggvat\0culyhz\0cevfba\0cebqhprq\0cebtenzzvat\0dhnaghz\0eviny\0fnzcyr\0frp"
    "hevgl\0fyvpx\0fzrtzn\0fzryy\0fcnz\0fgno\0fcbegfzna\0fhcresyhbhf\0gnoyr\0gbhpu"
    "vat\0genssvp\0ghzhyg\0ghezbvy\0haphefrq\0haqrentr\0hasvg\0haynjshy\0hafgnoyr"
    "\0ivfvgngvba\0jrrxyl\0mroen\0";

static char gallows[] =
    "+--+\n"
    "|    \n"
    "|    \n"
    "|    \n"
    "|  _ \n"
    "| | |\n"
    "=======";

static char* hangingStages =
    "|\x08\0O\x0e\0/\x13\0|\x14\0\\\x15\0/\x19\0\\\x1b\0X\x0e";

int main()
{
    puts("ULTIMATE HANGMAN (c) sac_boy 2019");
    puts("-------- ------- --- ------- ----");
        
    // Count the words we have available and decode the buffer
    int wordCount = 0;
    char* wordCounterPtr = &wordList[0];
    while (!(*wordCounterPtr++ == 0 && *wordCounterPtr == 0)) {
        if (*wordCounterPtr == 0) {
            wordCount++;
        } else {
            *wordCounterPtr = (((*wordCounterPtr - 'a') + 13) % 26) + 'a';
        }
    }

    // Choose a random word
    time_t seed;
    time(&seed);
    srand(seed);
    int wordIndex = rand() % wordCount;
    int zeroesCounted = 0;
    char* word = &wordList[0];
    while (zeroesCounted != wordIndex)
    {
        word++;
        if (*word == 0) { zeroesCounted++; }
    }
    word++;

    // Initalize guess buffer
    int wordLen = strlen(word);
    char* guess = malloc(wordLen + 1);
    for (unsigned int i = 0; i < wordLen; i++) { guess[i] = '_'; }
    guess[wordLen] = 0;

    // Initialize incorrect guess history
    char history[] = "\0\0\0\0\0\0\0\0\0";
    char* historyPtr = &history[8];

    // Game loop
    int failures = 0;
    int foundAll = 0;

    while (foundAll == 0 && failures < 8)
    {
        char inputBuf[2];
        puts("Guess a character (a-z) (q to quit):");
        scanf("%s", inputBuf);
        
        if (inputBuf[0] == 'q') { exit(1); }
        if (inputBuf[0] < 'a' || inputBuf[0] > 'z') {
            puts("Skipping non-alphabetic character!");
            continue;
        }

        int found = 0;
        foundAll = 1;

        // Scan word for occurrences of inputBuf[0]
        char* scanPos = word;
        while (*scanPos != 0) {
            char* guessPos = &guess[scanPos - word];

            if (*scanPos == inputBuf[0])
            {
                *guessPos = *scanPos;
                found = 1;
            }

            if (*guessPos != *scanPos)
            {
                foundAll = 0;
            }

            scanPos++;
        };  

        if (!found)
        {
            // Update history
            *--historyPtr = inputBuf[0];

            // Update gallows
            char* hangingStagePtr = hangingStages;
            int hangingStageCounter = 0;
           
            while (hangingStageCounter < failures) {
                if (*hangingStagePtr == 0) { hangingStageCounter++; }
                hangingStagePtr++;
            }
            
            gallows[*(hangingStagePtr + 1)] = *hangingStagePtr;

            failures++;

            // Kick away the stool if we have failed too many times
            if (failures == 8) {
                gallows[0x1a] = ' '; 
                gallows[0x1f] = ' ';
                gallows[0x21] = ' '; 
            }
        }

        puts(gallows);
        printf("%s | history: %s\n", guess, historyPtr);
    }

    if (!foundAll) {
        puts("Sorry, looks like you got hung!");
        printf("The word was '%s'...maybe you need to improve your vocabulary!", word);
    } else {
        puts("CONGRATULATIONS! You have been pardoned!");
    }

    free(guess);

    return 0;
}
→ More replies (3)

5

u/wyom1ng Apr 22 '19

Python 3.7

"I wanna hang myself reading this code"-hangman

_, h, ha, han, hang, hangm, hangma, hangman = "_________\n  |/\n  |\n  |\n  |\n  |\n  |\n  |___\n", "_________\n  |/   |\n  |\n  |\n  |\n  |\n  |\n  |___\n  H", "_________\n  |/   |\n  |   (_)\n  |\n  |\n  |\n  |\n  |___\n  HA", "_________\n  |/   |\n  |   (_)\n  |   /|\n  |\n  |\n  |\n  |___\n  HAN", "_________\n  |/   |\n  |   (_)\n  |   /|\n  |    |\n  |\n  |\n  |___\n  HANG", "_________\n  |/   |\n  |   (_)\n  |   /|\\\n  |    |\n  |\n  |\n  |___\n  HANGM", "_________\n  |/   |\n  |   (_)\n  |   /|\\\n  |    |\n  |   / \n  |\n  |___\n  HANGMA", "_________\n  |/   |\n  |   (_)\n  |   /|\\\n  |    |\n  |   / \\\n  |\n  |___\n  HANGMAN"

mysteryword = ''
print("-----Welcome to HANGMAN, You get seven chances to guess the mystery word-----")
print()
mysteryword = input('Enter the mystery word: ')
from os import name
mysteryword = mysteryword.lower()
guess = '_' * len(mysteryword)
guesses = 0
usedletters = []

from os import system
while 1:
    if name == 'nt':
        system('cls')
    else:
        system('clear')

    print(guess)

    if guesses == 0:
        print(_)
    else:
        print(eval("hangman"[:guesses]))

    if guess == mysteryword.upper():
        print('YOU WIN!')
        quit()
    try:
        l = input('Enter your guess: ').lower()[0]
    except:
        l = ''

    if l in mysteryword and l not in usedletters:
        usedletters.append(l)

        temporarycounter = 0
        for letter in mysteryword:
            if letter == l:
                new = list(guess)
                new[temporarycounter] = letter.upper()
                guess = ''.join(new)
            temporarycounter = temporarycounter + 1

    else:
        guesses += 1
        print("You guessed wrong", guesses, "time(s)!")

        if guesses > len('hangman'):
            print()
            print('YOU LOSE!')
            quit()

        input('Press ENTER to continue')

2

u/EkskiuTwentyTwo i -= (i - (-1)) - i Apr 23 '19
import random

def Assign(Pleh):
    return Pleh
def Spit(*saliva):
    print(*saliva)
def Gobble(request):
    return input(request)
def StirFry(meat,veggies,spoon):
    return [meat,veggies][spoon]
def Hangman():
    possibleWords = Assign(["CHEESE","EGG","FEDORA","ABACUS","BAD","DRAWER","GINGER","HAT","IGNEOUS","JACKET","KILLER","LACKEY","MONKS","NO","OMICRON","PUZZLE","QUESTIONABLE","ROTARY","SENTIMENT","TOFU","UNDER","VISIER","WISDOM","EXACT","YES","ZED","SILLY","HANGMAN"])
    p = Assign(8)
    guessed = Assign(False)
    word = Assign(possibleWords[random.randint(0,25)])
    dispword = Assign("_" * len(word))
    while (not guessed) and (not p == 0):
        Spit("Life left:","#"*p)
        Spit("Word known:",dispword)
        letter = Assign(Gobble("Enter a letter to guess (Use capitals): "))
        squid = Assign(1234)
        wordycount = Assign(0)
        while wordycount < len(word):
            fillyMcFillface = StirFry(dispword[wordycount],word[wordycount],(letter == word[wordycount]))
            dispword = Assign(dispword[:wordycount]+fillyMcFillface+dispword[wordycount+1:])
            squid = StirFry(squid,4321,letter == word[wordycount])
            wordycount = Assign(wordycount + 666//666) # I put it in a form with only the number 666 to make sure that this code is cursed
        CrazyLongMess = Assign([420] * 1234 + [p-1] + [69] * (4321-1235) + [p])
        p = Assign(CrazyLongMess[squid])
        guessed = StirFry(False,True,dispword==word)
    Spit(StirFry("Y'lost. The word was "+word,"Y'won!\nThe word indeed was "+word,guessed))
Hangman()

A bunch of redundant functions and perhaps the worst possible selection system you could design. Also, the choice of number representation for some increments is cursed.

0

u/[deleted] Apr 22 '19

[deleted] — view deleted comment

3

u/sac_boy Apr 23 '19

There's something liberating about writing terrible procedural C again like it's my bedroom in 1998. No pondering class structures. No dealing with other programmers. No self-judgement. Catharsis.

1

u/Average_Manners Apr 26 '19

I'm very tempted to design something flawless, then eviscerate and desecrate, as my form of catharsis.