Avatar of victorlm125

victorlm125's solution

to Hangman in the Python Track

Published at Sep 24 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Implement the logic of the hangman game using functional reactive programming.

Hangman is a simple word guessing game.

Functional Reactive Programming is a way to write interactive programs. It differs from the usual perspective in that instead of saying "when the button is pressed increment the counter", you write "the value of the counter is the sum of the number of times the button is pressed."

Implement the basic logic behind hangman using functional reactive programming. You'll need to install an FRP library for this, this will be described in the language/track specific files of the exercise.

Hints

Please ignore the part regarding FRP library, a third party library is not required for this exercise.

Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of raise Exception, you should write:

raise Exception("Meaningful message indicating the source of the error")

Running the tests

To run the tests, run the appropriate command below (why they are different):

  • Python 2.7: py.test hangman_test.py
  • Python 3.4+: pytest hangman_test.py

Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version): python -m pytest hangman_test.py

Common pytest options

  • -v : enable verbose output
  • -x : stop running tests on first failure
  • --ff : run failures from previous test before running other test cases

For other options, see python -m pytest -h

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/hangman directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see Running the Tests.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

hangman_test.py

import unittest

import hangman
from hangman import Hangman


# Tests adapted from csharp//hangman/HangmanTest.cs

class HangmanTests(unittest.TestCase):
    def test_initially_9_failures_are_allowed(self):
        game = Hangman('foo')
        self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
        self.assertEqual(game.remaining_guesses, 9)

    def test_initially_no_letters_are_guessed(self):
        game = Hangman('foo')

        self.assertEqual(game.get_masked_word(), '___')

    def test_after_10_failures_the_game_is_over(self):
        game = Hangman('foo')

        for i in range(10):
            game.guess('x')

        self.assertEqual(game.get_status(), hangman.STATUS_LOSE)
        with self.assertRaisesWithMessage(ValueError):
            game.guess('x')

    def test_feeding_a_correct_letter_removes_underscores(self):
        game = Hangman('foobar')

        game.guess('b')
        self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
        self.assertEqual(game.remaining_guesses, 9)
        self.assertEqual(game.get_masked_word(), '___b__')

        game.guess('o')
        self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
        self.assertEqual(game.remaining_guesses, 9)
        self.assertEqual(game.get_masked_word(), '_oob__')

    def test_feeding_a_correct_letter_twice_counts_as_a_failure(self):
        game = Hangman('foobar')

        game.guess('b')
        self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
        self.assertEqual(game.remaining_guesses, 9)
        self.assertEqual(game.get_masked_word(), '___b__')

        game.guess('b')
        self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
        self.assertEqual(game.remaining_guesses, 8)
        self.assertEqual(game.get_masked_word(), '___b__')

    def test_getting_all_the_letters_right_makes_for_a_win(self):
        game = Hangman('hello')

        game.guess('b')
        self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
        self.assertEqual(game.remaining_guesses, 8)
        self.assertEqual(game.get_masked_word(), '_____')

        game.guess('e')
        self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
        self.assertEqual(game.remaining_guesses, 8)
        self.assertEqual(game.get_masked_word(), '_e___')

        game.guess('l')
        self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
        self.assertEqual(game.remaining_guesses, 8)
        self.assertEqual(game.get_masked_word(), '_ell_')

        game.guess('o')
        self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
        self.assertEqual(game.remaining_guesses, 8)
        self.assertEqual(game.get_masked_word(), '_ello')

        game.guess('h')
        self.assertEqual(game.get_status(), hangman.STATUS_WIN)
        self.assertEqual(game.get_masked_word(), 'hello')

        with self.assertRaisesWithMessage(ValueError):
            game.guess('x')

    def test_winning_on_last_guess_still_counts_as_a_win(self):
        game = Hangman('aaa')
        for ch in 'bcdefghij':
            game.guess(ch)
        game.guess('a')
        self.assertEqual(game.remaining_guesses, 0)
        self.assertEqual(game.get_status(), hangman.STATUS_WIN)
        self.assertEqual(game.get_masked_word(), 'aaa')

    # Utility functions
    def setUp(self):
        try:
            self.assertRaisesRegex
        except AttributeError:
            self.assertRaisesRegex = self.assertRaisesRegexp

    def assertRaisesWithMessage(self, exception):
        return self.assertRaisesRegex(exception, r".+")


if __name__ == '__main__':
    unittest.main()
# Game status categories
# Change the values as you see fit
STATUS_WIN = "win"
STATUS_LOSE = "lose"
STATUS_ONGOING = "ongoing"


class Hangman(object):
    def __init__(self, word):
        self.word = word
        self.tried = []
        self.remaining_guesses = 9
        self.status = STATUS_ONGOING

    def guess(self, char):
        if self.remaining_guesses < 0 or self.status == STATUS_WIN:
            raise ValueError("Error")
        else:
            if char in self.tried or char not in self.word:
                self.remaining_guesses -= 1
                if self.remaining_guesses < 0:
                    self.status = STATUS_LOSE
            self.tried.append (char)
            if self.get_masked_word().count('_') == 0:                      
                self.status = STATUS_WIN

    def get_masked_word(self):
        data = ''
        for x in self.word:
            if x not in self.tried:
                data += '_'
            else:
                data += x
        return data

    def get_status(self):
        return self.status

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?