Exemple #1
0
def main():
    hangman = Hangman()
    while True:
        won, state = hangman.begin()
        if won:
            print("Won! The string is: " + state)
        else:
            print("Could not win. Starting again")
        hangman = Hangman()
Exemple #2
0
class TestHangmanMaskedWords(unittest.TestCase):
    def setUp(self):
        self.game = Hangman(None, "kotik")

    def test_masked_word(self):
        self.assertEqual(self.game.masked_word, "*****",
                         "Masked word isn't correct")

    def test_right_letter(self):
        self.game.check_letter("t")
        self.assertEqual(self.game.masked_word, "**t**",
                         "Masked word isn't correct")

    def test_wrong_letter(self):
        self.game.check_letter("j")
        self.assertEqual(self.game.masked_word, "*****",
                         "Masked word isn't correct")

    def test_right_word(self):
        self.game.check_word("kotik")
        self.assertEqual(self.game.masked_word, "kotik",
                         "Masked word isn't correct")

    def test_wrong_word(self):
        self.game.check_word("pesik")
        self.assertEqual(self.game.masked_word, "*****",
                         "Masked word isn't correct")
Exemple #3
0
 def test_import_std_file(self):
     std_file = open("words.txt")
     std_words = std_file.readlines()
     std_file.close()
     self.game = Hangman()
     self.assertEqual(len(self.game.words), len(std_words),
                      "Imported word isn't correct")
Exemple #4
0
def main():
    choice = 0

    while choice != 6:
        '''Main menu screen.'''
        print("\nWelcome to the Python Fair.")
        print("1. Higher or lower?")
        print("2. Rock, Paper, Scissors")
        print("3. Counting jar")
        print("4. Hangman")
        print("5. Trivia")
        print("6. Leave")
        '''User input on the main menu.'''
        while True:
            try:
                choice = int(input("What do you want to do? "))
                break
            except ValueError:
                print("Not proper input.")
        '''Navigation to a selected game.'''
        if choice == 1:
            HighLow()
        elif choice == 2:
            RockPaperScissors()
        elif choice == 3:
            CountingJar()
        elif choice == 4:
            Hangman()
        elif choice == 5:
            Trivia()
        elif choice == 6:
            print("Goodbye.")
        else:
            print("Not a option.")
Exemple #5
0
class HangmanGame:
    def __init__(self):
        self.hangman = Hangman()

    def play(self):
        while True:
            print(f'Pozostała liczba szans: {self.hangman.get_chances()}')
            print(self.hangman.get_word_to_guess())
            letter = input('Podaj literę lub słowo: ')

            if self.hangman.is_it_word_to_find(letter):
                # jeśli wpisane słowo jest tym, którego szukamy, to wygrana
                self.win()
                break
                # jeśli wpisana jest litera, a więc nie słowo, to leci dalej

            try:
                # decreasa_chances rzuca wyjątek, który trzeba przechwycić i rzucić dalej (pokazać)
                self.hangman.guess_letter(letter)
            except ChancesError:
                self.lose()
                break

            if self.hangman.are_all_letters_found():
                # nie można tego połączyć z self.hangman.are_all_letters_found()
                # bo nie uzna, że całe słowo jest odgadnięte, kiedy litera nie jest jeszcze wsdtawiona
                self.win()
                break


    def lose(self):
        print('\nSłabiaku!!!')
        self.print_word_to_find()

    def win(self):
        print("\nGratulacje!!!")
        self.print_word_to_find()

    def print_word_to_find(self):
        print(f'Szukane słowo to: {self.hangman.get_word_to_find()}')
    def startGame(self):
        while True:
            picked_word = None
            while True:
                self.hangman = Hangman()

                min_length = input("Enter Minimum Length : ")
                max_length = input("Enter Maximum Length : ")

                if not min_length.isdigit() or not max_length.isdigit() or\
                        int(min_length) <= 0 or int(max_length) <= 0:
                    print("Please Enter a Positive Integer")
                    continue

                picked_word = self.word.randFromDB(int(min_length),
                                                   int(max_length))
                if picked_word is None:
                    print("No Words Found")
                    continue
                break
            self.guess = Guess(picked_word)
            self.gameOver = False
            while not self.gameOver:
                self.guessClicked()
Exemple #7
0
import argparse
from Hangman import Hangman

parser = argparse.ArgumentParser(
    description='TheHangman:\n1-tryb standardowy\n2-tryb artystyczny')
parser.add_argument('mode',
                    nargs='?',
                    const=1,
                    type=int,
                    help='default: 1',
                    default=1)

hangman = Hangman(parser.parse_args().mode)
Exemple #8
0
 def setUp(self):
     self.game = Hangman(None, "kotik")
     self.saved_stdout = sys.stdout
Exemple #9
0
class TestHangmanGameplay(unittest.TestCase):
    def setUp(self):
        self.game = Hangman(None, "kotik")
        self.saved_stdout = sys.stdout

    def test_is_word_opened(self):
        self.game.check_word("kotik")
        self.assertTrue(self.game.is_word_opened())

    def test_the_word_guessed(self):
        try:
            out = io.StringIO()
            sys.stdout = out
            self.game.check_word("kotik")
            output = out.getvalue().strip()
            self.assertTrue(output.endswith("The word: kotik"))
        finally:
            sys.stdout = self.saved_stdout

    def test_the_word_missed(self):
        try:
            out = io.StringIO()
            sys.stdout = out
            self.game.check_word("pesik")
            output = out.getvalue().strip()
            self.assertTrue(output.endswith("The word: *****"))
        finally:
            sys.stdout = self.saved_stdout

    def test_the_letter_guessed(self):
        try:
            out = io.StringIO()
            sys.stdout = out
            self.game.check_letter("k")
            output = out.getvalue().strip()
            self.assertTrue(output.endswith("The word: k***k"))
        finally:
            sys.stdout = self.saved_stdout

    def test_the_letter_missed(self):
        try:
            out = io.StringIO()
            sys.stdout = out
            self.game.check_letter("p")
            output = out.getvalue().strip()
            self.assertTrue(output.endswith("The word: *****"))
        finally:
            sys.stdout = self.saved_stdout
Exemple #10
0
 def test_imported_word(self):
     self.game = Hangman("test.txt")
     self.assertEqual(self.game.word, "test", "Imported word isn't correct")
Exemple #11
0
# Imports
from Hangman import Hangman

# FileName: Driver.py
# Author: Anthony Pompili
# Date: February 14, 2020
# Description: This file is the main driver for the "Hangman" game. This will initialize the game, and prompt
# the user if they want to play a game and then create a game for them to play with a phrase.

user_input = input("Do you want to play Hangman? (Type \"yes\" to play, otherwise the game will quit): ")

while (user_input.lower() == "yes"):
    print("Ok, lets play!")
    game_instance = Hangman()
    user_input = input("Would you like to play again? (Type \"yes\" to play, otherwise the game will quit): ")

print("Ok, bye then!")
Exemple #12
0
  def __init__(self):
    # Game controller.
    self.controller = Hangman()

    # This keeps a reference to the last style menu widget selected so that it can be
    # set inactive when a new one is selected.
    self.currentStyle = None

    # Set up the window.
    self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    self.window.set_title("Hangman")

    # Default window size.
    self.window.set_default_size(640, 480)

    self.window.connect("delete_event", self.destroy)

    # Text entry field for entering guesses.
    self.guessField = gtk.Entry(1)
    self.guessField.connect("activate", self.GuessCheck, self.guessField)
    self.guessField.set_editable(gtk.FALSE)

    # Label to display the correctly guessed letters.
    self.correctText = gtk.Label(" ".join(self.controller.correct))
    self.correctText.set_justify(gtk.JUSTIFY_CENTER)

    # Label to display the incorrect guesses.
    guessFrame = gtk.Frame("Missed Guesses")
    self.guessedText = gtk.Label(None)
    self.guessedText.set_justify(gtk.JUSTIFY_CENTER)
    self.guessedText.set_line_wrap(gtk.TRUE)
    guessFrame.add(self.guessedText)
    self.guessedText.show()

    # Clue field.
    self.clueFrame = gtk.Frame("Clue")
    self.clue = gtk.Label(None)
    self.clue.set_line_wrap(gtk.TRUE)
    self.clueFrame.add(self.clue)
    self.clue.show()

    # New game button.
    self.newGame = gtk.Button("New Game for Justice",gtk.STOCK_NEW)
    self.newGame.connect("clicked", self.NewGame)

    # Open new file button.
    self.openButton = gtk.Button(stock=gtk.STOCK_OPEN)
    self.openButton.connect("clicked", self.openFile)

    # Quit button.
    self.quit = gtk.Button(stock=gtk.STOCK_QUIT)
    self.quit.connect("clicked", self.Quit)

    # Gallows.
    self.gallows = Gallows()
    self.gallowsFrame = gtk.AspectFrame(ratio=self.gallows.imageAspect,obey_child=gtk.FALSE)
    self.gallowsFrame.set_shadow_type(gtk.SHADOW_IN)
    self.gallowsFrame.add(self.gallows)
    self.gallows.show()
    self.gallowsFrame.show()

    # Boxes for window layout.

    # buttonBox: contains the New Game button to the left of the Quit button.
    buttonBox = self.Pack(gtk.HBox,
        [None, self.newGame, self.openButton, self.quit],
        [gtk.TRUE, 5])
    buttonBox.show()

    # box1: text entry field for entering guesses to the left of the buttonBox.
    box1 = self.Pack(gtk.HBox,
        [self.guessField, None, buttonBox],
        packArgs=[gtk.TRUE, gtk.TRUE, 5])
    box1.show()

    # clueBox: correctText packed above clues.
    clueBox = self.Pack(gtk.VBox,
                        [self.correctText, self.clueFrame],
                        packArgs=[gtk.TRUE, gtk.TRUE])

    # textBox: correctText to the left of guessedText.
    textBox = self.Pack(gtk.HBox,
        [clueBox, None, guessFrame],
        packArgs=[gtk.TRUE, gtk.TRUE, 20])
    textBox.show()

    # Default has clues hidden.
    self.clueFrame.hide()

    # Pack the textBox, gallowsFrame and box1 into a box with a 15 pixel
    # border around it.
    box2 = gtk.VBox()
    box2.set_border_width(15)
    box2.pack_start(textBox, gtk.FALSE, gtk.FALSE, 5)
    box2.pack_start(self.gallowsFrame, gtk.TRUE, gtk.TRUE, 5)
    box2.pack_start(box1, gtk.FALSE, gtk.FALSE)
    box2.show()

    # Create a menu bar.
    self.makeMenu()

    # Final box.  Pack the menubar into the top, so it spans the entire width
    # of the window.  Pack box2 underneath it.
    box3 = gtk.VBox()
    box3.pack_start(self.menuBar, gtk.FALSE, gtk.TRUE, 0)
    box3.pack_start(box2, gtk.TRUE, gtk.TRUE, 0)
    box3.show()

    # Add the outer box to the window.
    self.window.add(box3)

    # Last thing, show the window.
    self.window.show()
    # Gather the settings info
    settings = HangmanSettings()
    display = settings.display
    max_incorrect = settings.max_incorrect
    count = 0
    total = 0

    display.clock("Start time")

    HangmanWordPassEngine.initialize(settings)

    # Grab the given secret from the generator function to start the game play!
    # No more secrets, no more play
    for secret in settings.get_secrets():

        hangman = Hangman(settings)

        score = hangman.play(secret, max_incorrect)
        total += score
        count += 1

        display.bare("{}: {}\n".format(secret.upper(), score))

        #display.clock("Finished game\n")

    # Compute the average score
    avg = float(total) / float(count)

    display.clock("End time")

    HangmanWordPassEngine.cleanup()
Exemple #14
0
 def __init__(self):
     self.game = Hangman()
     self.phrase = "Hello World"
Exemple #15
0
    word_generator = OxfordRequest()

    # English alphabet.
    alphabet = [
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
        "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
    ]

    # Game loop...
    while True:
        # Initialize Hangman Model with word (new) & alphabet. Must validate all characters are within alphabet.
        while True:
            try:
                word = word_generator.get_random_word()
                word = word.upper()
                hangman = Hangman(word, alphabet)
                break
            except:
                print(word + " is not valid.")

        game_view.update_image(0)

        # Draw buttons to their initial state.
        for i in range(0, len(alphabet)):
            game_view.draw_button(i, gv.BUTTON_ACTIVE, alphabet[i])

        # Draw initial word blanks.
        for i in range(0, len(word)):
            if (word[i] == ' '):
                game_view.draw_character(i, ' ')
            else:
Exemple #16
0
 def __init__(self):
     self.hangman = Hangman()
Exemple #17
0
from Hangman import Hangman

game = Hangman()
game.play()
Exemple #18
0
print('Hello! Would you like to play hangman?')
response = input('y/n?')

if response == 'n':
    print('Goodbye!')
    sys.exit()

#prompt user for a word
word = input('What word or phrase would you like to use?')
while len(word) > 25:
    print(
        'Your word/phrase is too long. The maximum number of characters is 25.'
    )
    word = input('Please type in a new word.')

#main game loop
os.system('cls')
print("Let's play hangman!")
hangman = Hangman(word)
while (hangman.get_life != 0):
    print()
    print()
    print()
    guess = input('Guess a letter:')
    hangman.find_letter(guess)
    if hangman.check_gameover() == True:
        sys.exit()
    if hangman.check_win() == True:
        sys.exit()
    hangman.print_word()
    hangman.print_hangman()
class HangmanGame:
    def __init__(self):
        # Initialize word database
        self.word = Word('words.txt')

        # Start a new game on application launch!
        self.startGame()

    def startGame(self):
        while True:
            picked_word = None
            while True:
                self.hangman = Hangman()

                min_length = input("Enter Minimum Length : ")
                max_length = input("Enter Maximum Length : ")

                if not min_length.isdigit() or not max_length.isdigit() or\
                        int(min_length) <= 0 or int(max_length) <= 0:
                    print("Please Enter a Positive Integer")
                    continue

                picked_word = self.word.randFromDB(int(min_length),
                                                   int(max_length))
                if picked_word is None:
                    print("No Words Found")
                    continue
                break
            self.guess = Guess(picked_word)
            self.gameOver = False
            while not self.gameOver:
                self.guessClicked()

    def guessClicked(self):
        guessedChar = input("Enter a Character : ")
        guessedChar = guessedChar.lower()
        if self.gameOver is True:
            print("Please Start New Game")
            return

        if len(guessedChar) != 1:
            print("Please Enter a Character")
            return

        for char in self.guess.guessedChars:
            if char == guessedChar:
                print("Please Enter New Character")
                return

        if not guessedChar.isalpha():
            print("Please Enter an Alphabet")
            return

        success = self.guess.guess(guessedChar)
        if success == False:
            self.hangman.life_decrease()
            print(str(self.hangman.get_life()) + " Lives Remain")
            # 메시지 출력
        else:
            print("Correct!")

        print(self.hangman.current_shape())
        # 현재 hangman 상태 그림을 출력
        print("Current : ", (self.guess.displayCurrent()))
        # 현재까지 부분적으로 맞추어진 단어 상태를 출력
        print("Guessed Characters : ", (self.guess.displayGuessed()))
        # 지금까지 이용한 글자들의 집합을 출력
        print("Lives : ", str(self.hangman.get_life()))

        if self.guess.finished():
            print("Success!")
            self.gameOver = True
            # 메시지 ("Success!") 출력하고, self.gameOver 는 True 로

        elif self.hangman.get_life() == 0:
            print("Fail! - " + self.guess.secretWord)
            self.gameOver = True
Exemple #20
0
 def setUp(self):
     self.game = Hangman(None, "kotik")
Exemple #21
0
from Hangman import Hangman
from getpass import getpass
word = getpass("Enter Word Here -> ")
game = Hangman(word)
print("Game has started:\n\n")
print(game.getWord() + "\n\n")
letter = input("Enter a letter (enter only one letter) -> ")

while len(letter) <= 1:
    signal = game.guess(letter)
    print(signal)
    game.displayLettersTried()
    if signal == game.LOSE:
        print("Word was: " + game.word)
        break
    else:
        if not game.getWord().__contains__("_"):
            print(game.WIN)
            break
        else:
            letter = input("Enter a letter (enter only one letter) -> ")
Exemple #22
0
class TestHangman:
    def __init__(self):
        self.game = Hangman()
        self.phrase = "Hello World"

    def test_hangman_init(self):
        isinstance(self.game, Hangman)

    def test_accepts_a_phrase(self):
        self.game.setPhrase(self.phrase)

        assert self.game.realPhrase() == self.phrase

    def test_phrase_is_hidden(self):
        phrases = [
            {'plain': 'Hello World', 'hidden': '_____ _____'},
            {'plain': "It's got an apostrophe", 'hidden': "__'_ ___ __ __________"},
            {'plain': 'The number is 2 (two).', 'hidden': '___ ______ __ 2 (___).}'}
        ]
        for phrase in phrases:
            self.game.setPhrase(phrase.text)
            assert self.game.hiddenPhrase() == phrase.hidden

    def test_has_letter(self):
        self.game.setPhrase(self.phrase)
        guesses = [
            {'value':'e', 'expected': True},  # this is in the string Hello World
            {'value':'h', 'expected': True},  # this exists, but it's upper case, should return True anyway
            {'value':'x', 'expected': False},  # this isn't in the string
            {'value':123, 'expected': False},  # numbers wont exist in our phrase (digits will)
            {'value':(1, 2,), 'expected': False},  # what's this? a tuple or something
        ]
        for guess in guesses:
            assert self.game.hasLetter(guess.value) == guess.expected

    def test_make_guess(self):
        self.game.setPhrase(self.phrase)

        guess = 'e'
        result = self.game.makeGuess(guess)
        assert result == ['e']

        guess = 'x'
        result = self.game.makeGuess(guess)
        assert result == ['e', 'x']
Exemple #23
0
class HangmanGUI:
  """ Acts as a view and controller for the Hangman class.  __init__ creates
      all the necessary widgets for the main window.  By creating an
      instance of HangmanGUI and starting gtk.main the game is all set up.
      """
  def __init__(self):
    # Game controller.
    self.controller = Hangman()

    # This keeps a reference to the last style menu widget selected so that it can be
    # set inactive when a new one is selected.
    self.currentStyle = None

    # Set up the window.
    self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    self.window.set_title("Hangman")

    # Default window size.
    self.window.set_default_size(640, 480)

    self.window.connect("delete_event", self.destroy)

    # Text entry field for entering guesses.
    self.guessField = gtk.Entry(1)
    self.guessField.connect("activate", self.GuessCheck, self.guessField)
    self.guessField.set_editable(gtk.FALSE)

    # Label to display the correctly guessed letters.
    self.correctText = gtk.Label(" ".join(self.controller.correct))
    self.correctText.set_justify(gtk.JUSTIFY_CENTER)

    # Label to display the incorrect guesses.
    guessFrame = gtk.Frame("Missed Guesses")
    self.guessedText = gtk.Label(None)
    self.guessedText.set_justify(gtk.JUSTIFY_CENTER)
    self.guessedText.set_line_wrap(gtk.TRUE)
    guessFrame.add(self.guessedText)
    self.guessedText.show()

    # Clue field.
    self.clueFrame = gtk.Frame("Clue")
    self.clue = gtk.Label(None)
    self.clue.set_line_wrap(gtk.TRUE)
    self.clueFrame.add(self.clue)
    self.clue.show()

    # New game button.
    self.newGame = gtk.Button("New Game for Justice",gtk.STOCK_NEW)
    self.newGame.connect("clicked", self.NewGame)

    # Open new file button.
    self.openButton = gtk.Button(stock=gtk.STOCK_OPEN)
    self.openButton.connect("clicked", self.openFile)

    # Quit button.
    self.quit = gtk.Button(stock=gtk.STOCK_QUIT)
    self.quit.connect("clicked", self.Quit)

    # Gallows.
    self.gallows = Gallows()
    self.gallowsFrame = gtk.AspectFrame(ratio=self.gallows.imageAspect,obey_child=gtk.FALSE)
    self.gallowsFrame.set_shadow_type(gtk.SHADOW_IN)
    self.gallowsFrame.add(self.gallows)
    self.gallows.show()
    self.gallowsFrame.show()

    # Boxes for window layout.

    # buttonBox: contains the New Game button to the left of the Quit button.
    buttonBox = self.Pack(gtk.HBox,
        [None, self.newGame, self.openButton, self.quit],
        [gtk.TRUE, 5])
    buttonBox.show()

    # box1: text entry field for entering guesses to the left of the buttonBox.
    box1 = self.Pack(gtk.HBox,
        [self.guessField, None, buttonBox],
        packArgs=[gtk.TRUE, gtk.TRUE, 5])
    box1.show()

    # clueBox: correctText packed above clues.
    clueBox = self.Pack(gtk.VBox,
                        [self.correctText, self.clueFrame],
                        packArgs=[gtk.TRUE, gtk.TRUE])

    # textBox: correctText to the left of guessedText.
    textBox = self.Pack(gtk.HBox,
        [clueBox, None, guessFrame],
        packArgs=[gtk.TRUE, gtk.TRUE, 20])
    textBox.show()

    # Default has clues hidden.
    self.clueFrame.hide()

    # Pack the textBox, gallowsFrame and box1 into a box with a 15 pixel
    # border around it.
    box2 = gtk.VBox()
    box2.set_border_width(15)
    box2.pack_start(textBox, gtk.FALSE, gtk.FALSE, 5)
    box2.pack_start(self.gallowsFrame, gtk.TRUE, gtk.TRUE, 5)
    box2.pack_start(box1, gtk.FALSE, gtk.FALSE)
    box2.show()

    # Create a menu bar.
    self.makeMenu()

    # Final box.  Pack the menubar into the top, so it spans the entire width
    # of the window.  Pack box2 underneath it.
    box3 = gtk.VBox()
    box3.pack_start(self.menuBar, gtk.FALSE, gtk.TRUE, 0)
    box3.pack_start(box2, gtk.TRUE, gtk.TRUE, 0)
    box3.show()

    # Add the outer box to the window.
    self.window.add(box3)

    # Last thing, show the window.
    self.window.show()

  def makeMenu(self):
    """ Creates a menu bar and saves it to self.menuBar. """
    accelGroup = gtk.AccelGroup()
    styles = self.getStyles()

    menuItems = (
        ("/_File", None, None, 0, "<Branch>"),
        ("/File/New", None, None, 0, "<Branch>"),
        ("/File/New/_Game from File", "<control>N", self.NewGame, 0, None),
        ("/File/New/_Internet Game", "<control>I", self.NewGame, 1, None),
        ("/File/_Open", "<control>O", self.openFile, 0, None),
        ("/File/sep", None, None, 0, "<Separator>"),
        ("/File/_Quit", "<control>Q", self.Quit, 0, None),
        ("/_Options", None, None, 0, "<Branch>"),
        ("/Options/Enable clues", None, self.toggleClues, 0, "<CheckItem>"),
        ("/Options/Game Style", None, None, 0, "<Branch>"),
        ("/_Help", None, None, 0, "<Branch>"),
        ("/Help/_About Hangman", None, None, 0, None))

    itemFactory = gtk.ItemFactory(gtk.MenuBar, "<main>", accelGroup)
    # Create menu items from menuItems.
    itemFactory.create_items(menuItems)

    self.window.add_accel_group(accelGroup)
    self.menuBar = itemFactory.get_widget("<main>")

    # Now add all the of the style menu items to the menu.
    gameStyle = itemFactory.get_widget("<main>/Options/Game Style")

    for style in styles:
      gameStyle.append(style)
      style.show()

    # Show the menu bar.
    self.menuBar.show()

  def getStyles(self):
    """ Get a list of all the available style directories and create a tuple for the
        menu items from the list, using directory names as the style name.
        """
    # Get the first style so that we'll have a group to assign all of the other
    # RadioMenuItems to.
    styles = [gtk.RadioMenuItem(label=self.gallows.styleList[0])]

    # Create the other RadioMenuItems in the group of the first one.
    for i in range(len(self.gallows.styleList)-1):
      styles.append(gtk.RadioMenuItem(styles[0], self.gallows.styleList[i+1]))

    # Connect, the style's index in the list is passed to setStyle in order to determine
    # which style needs to be set, since the list of menu widgets is created from the
    # list of styles in the Gallows class.
    for style in styles:
      style.connect_object("toggled", self.setStyle, style, styles.index(style))

    self.currentStyle = styles[0]

    return styles

  def setStyle(self, widget, data):
    """ Set the style from the menu check item selected, only if the newly selected
        style isn't the same as the current style.
	"""
    if widget is not self.currentStyle:
      self.currentStyle = widget
      self.gallows.setStyle(data)
      self.gallowsFrame.set(0.5, ratio=self.gallows.imageAspect, obey_child=gtk.FALSE)

  def GuessCheck(self, widget, guessField):
    """ Grab the guess entered by the user and then call update the window
        with the new information.  If the game is over make the text entry
        field uneditable.
        """
    entry = guessField.get_text()
    guessField.select_region(0,1)
    # Check the guess.
    self.controller.correct,self.controller.guesses = self.controller.Guess(entry)
    # Update the window.
    self.Update(self.controller.gameStat())
    # If the game is over, prevent entry of new guesses.
    if self.controller.correct.count('_') == 0 or self.controller.numMissed == 6:
      guessField.set_editable(gtk.FALSE)

  def Quit(self, widget, data=None):
    """ Quit. """
    # Create a dialog to check if the user really wants to quit.
    dialog = gtk.MessageDialog(self.window,
                        gtk.DIALOG_DESTROY_WITH_PARENT|
                        gtk.DIALOG_MODAL,
                        gtk.MESSAGE_QUESTION,
                        gtk.BUTTONS_YES_NO,
                        "Are you sure you want to quit?")
    dialog.set_title("Quit")
    dialog.set_resizable(gtk.FALSE)

    dialog.show()
    response = dialog.run()
    if response == gtk.RESPONSE_YES:
      self.destroy()
    else:
      dialog.destroy()

  def toggleClues(self, widget, data=None):
    """ Toggle clues on and off. """
    if data.get_active():
      self.clueFrame.show()
    else:
      self.clueFrame.hide()

  def destroy(self, widget=None, event=None):
    """ Quit gtk.main. """
    gtk.main_quit()
    return gtk.FALSE

  def Pack(self, boxClass, widgets, boxArgs=[], packArgs=[]):
    """ Packs all the widgets in the last argument into a box of boxClass
        and returns the box.  packArgs are used as the arguments to the pack
        function. widgets is a list of widgets to be packed: everything before
        a 'None' item is packed with pack_start(), everything after is packed
        with pack_end() in reverse order, so that the order the widgets are
        passed is the order they will appear in the box.
        """
    # Create a new box.
    box = boxClass(*boxArgs)

    # Get the index of the None argument.
    if widgets.count(None) == 0:
      split = len(widgets)
    else:
      split = widgets.index(None)

    # Pack the widgets with packArgs using pack_start.
    for child in widgets[:split]:
      box.pack_start(child, *packArgs)
      child.show()

    # Reverse widgets for pack_end.
    endWidgets = widgets[split+1:]
    endWidgets.reverse()

    # Pack the widgets with packArgs using pack_end.
    for child in endWidgets:
      box.pack_end(child, *packArgs)
      child.show()

    return box

  def Update(self, updateString):
    """ Update the window with the new information. """
    self.correctText.set_text(updateString[0])
    self.guessedText.set_text(updateString[1])
    self.gallows.update(self.controller.numMissed)

  def NewGame(self, data=None, widget=None):
    """ Begin a new game. """
    if data == 1:
      self.controller.NetGame()
    else:
      # If there is nothing loaded bring up the file selection widget.
      if self.controller.words == {}:
        self.openFile()
        return
      self.controller.NewGame()

    # Update window.
    self.clue.set_text(self.controller.words[self.controller.answer])
    self.Update(self.controller.gameStat())
    self.gallows.update(0)

    # Clear text entry field, make editable again, and give it focus.
    self.guessField.set_text("")
    self.guessField.set_editable(gtk.TRUE)
    self.guessField.grab_focus()

  def openFile(self, widget=None, data=None):
    """ Load the contents of a file into the game. """
    # File selector.
    fileWindow = gtk.FileSelection("Hangman")
    fileWindow.set_transient_for(self.window)
    fileWindow.set_filename("games/")

    # Set up buttons.
    fileWindow.ok_button.connect("clicked", self.read, fileWindow)
    fileWindow.ok_button.connect("clicked", self.NewGame)
    fileWindow.ok_button.connect("clicked", lambda w: fileWindow.destroy())
    fileWindow.cancel_button.connect("clicked", lambda w: fileWindow.destroy())

    # Show.
    fileWindow.show()

  def read(self, data, widget):
    """ Callback for file selection from openFile().  Get the file name
        and send it to be opened and read into the controller.
        """
    self.controller.openFile(widget.get_filename())

  def error(self, parent=None, data=None):
    """ General error message generator.  data is the text to be printed in
        the dialog box.
        """
    # Create the dialog box.
    errorBox = gtk.MessageDialog(parent, gtk.DIALOG_MODAL,
                                  gtk.MESSAGE_WARNING,
                                  gtk.BUTTONS_OK,
                                  data)

    errorBox.set_resizable(gtk.FALSE)
    errorBox.show()
    if errorBox.run() == gtk.RESPONSE_OK:
      errorBox.destroy()
Exemple #24
0
from Hangman import Hangman
print("Welcome to Hangman!\n")
play = input("Would you like to play a game? (y/N) ")
if play.lower() != "y":
    print("Maybe later! Goodbye!")
    exit()
play_again = True
game = Hangman()
game.initialize_file('words.dat')
while play_again and game.num_words_available > 0:
    print("Starting game.")
    game.display_statistics()
    print("\n")
    game.new_word()
    while not game.game_over:
        game.display_game()
        user_guess = input("Enter a letter to guess. ")
        if not user_guess.isalpha():
            print("Sorry, I don't understand. That's not a letter. \n")
        elif not game.guess(user_guess.upper()):
            print("Sorry, you've alread guessed that letter. \n")
    game.reveal_word()
    game.display_statistics()
    game.game_over = False
    again = input("Would you like to play again? (y/N)")
    if again.lower() != "y":
        play_again = False

print("Thanks for playing! Goodbye!")
exit()
Exemple #25
0
from Hangman import Hangman
test = Hangman("hello")