Skip to content Skip to sidebar Skip to footer

For Loop Functions In Python

I am continuing with a Hangman project, and I have encountered a problem with a for loop and performing a function inside it. For example, if you press in a level named 'CANADA', a

Solution 1:

I made a functioning hangman program just now. Perhaps looking at this logic will help:

Ignore this:

#!/usr/bin/pythonimport string
alphabet = string.ascii_lowercase

# represents drawing routinesdefhangman1():
    print(1)
defhangman2():
    print(2)
defhangman3():
    print(3)
# ignore this, never do this:defmyprint(x): #python2 hack, unnecessary in python3print(x)
for i inrange(1,10):
    globals()['hangman{}'.format(i)] = lambda i=i: myprint('bodypart#{}'.format(i))

# ignore thisclassEnumItem(object):
    def__init__(self, namespace, namespace_name, value):
        self.namespace = namespace
        self.namespace_name = namespace_name
        self.value = value
    def__repr__(self):
        return'{}.{}'.format(self.namespace_name, self.value)
classEnumeration(object):
    def__init__(self, prefix, names):
        prefix = prefix.upper().replace(' ','_')
        globals()[prefix] = self  #don't do this with locals()

        self.items = names
        for i,name inenumerate(names.strip().splitlines()):
            name = name.strip().upper().replace(' ','_')
            value = EnumItem(self, prefix, name)
            setattr(self, name, value)
            #globals()[name] = value  #optional, also don't do this with locals()

Some enums:

Enumeration('GAME_STATE', '''
    active 
    lost 
    won
''')
Enumeration('GUESS', '''
    invalid not a letter
    invalid already guessed
    correct
    correct win
    incorrect
    incorrect loss
''')

Game logic - look at this part if you have trouble thinking through the rules of hangman (I left out a few things to make it run entirely correctly with spaces, to make it easier to understand):

classHangmanGame(object):
    MAX_INCORRECT_GUESSES = 10

    _bodyparts = [
        hangman1, hangman2, hangman3 #...
    ]

    def__init__(self, hidden_goal_phrase):
        self.phrase = hidden_goal_phrase.lower()    # e.g. batman
        self.revealed = '?'*len(hidden_goal_phrase) # e.g. ??????
        self.guessed = set()                        # e.g. {'b', 't'}
        self.num_incorrect_guesses = 0
        self.game_state = GAME_STATE.ACTIVE

    defguess(self, letter):
        """
            Interact with game by calling this function repeatedly with user's guesses
             letter - the letter the player has guessed
        """ifnot letter in alphabet ornotlen(letter)==1:
            return GUESS.INVALID_NOT_A_LETTER

        if letter in self.guessed:
            return GUESS.INVALID_ALREADY_GUESSED  # or throw a custom exception class HangmanIncorrectGuessException(Exception): pass# else guess is legitimate

        self.guessed.add(letter)
        if letter in self.phrase:  # if guess was correct# update internal state
            self.revealed = ''.join((c if c in self.guessed else (' 'if c==' 'else'?')) for c in self.phrase)

            # check for winprint(set(self.guessed), set(self.phrase))
            if self.guessed>=set(self.phrase):  # non-strict superset, see set.__ge__ etc.
                self.game_state = GAME_STATE.WON
                self.redraw
                return GUESS.CORRECT_WIN
            else:
                return GUESS.CORRECT
        else:  # if guess was incorrect
            self.num_incorrect_guesses += 1# check for lossif self.num_incorrect_guesses==HangmanGame.MAX_INCORRECT_GUESSES:
                self.game_state = GAME_STATE.LOST
                self.redraw()
                return GUESS.INCORRECT_LOSS
            else:
                self.redraw()
                return GUESS.INCORRECT

    defredraw(self):
        '''
            updates canvas to reflect current game state
        '''# pygame.clearcanvasorsomething()for bodypart in HangmanGame._bodyparts[:self.num_incorrect_guesses]:
            bodypart()

        if self.game_state==GAME_STATE.LOST:
            pass#draw appropriate GAME OVERelif self.game_state==GAME_STATE.WON:
            pass#draw appropriate CONGRATULATIONS

Interactive loop:

while True:
    print('NEW GAME')
    game = HangmanGame('penguin')
    while game.game_state==GAME_STATE.ACTIVE:
        result = game.guess(raw_input('Guess a letter: '))
        print(game.revealed, result)
        print('')

Demo games:

NEWGAMEGuessaletter: p
(set(['p']), set(['e', 'g', 'i', 'n', 'p', 'u']))
('p??????', GUESS.CORRECT)

Guessaletter: e
(set(['p', 'e']), set(['e', 'g', 'i', 'n', 'p', 'u']))
('pe?????', GUESS.CORRECT)

Guessaletter: n
(set(['p', 'e', 'n']), set(['e', 'g', 'i', 'n', 'p', 'u']))
('pen???n', GUESS.CORRECT)

Guessaletter: guin
('pen???n', GUESS.INVALID_NOT_A_LETTER)

Guessaletter: 7
('pen???n', GUESS.INVALID_NOT_A_LETTER)

Guessaletter:  
('pen???n', GUESS.INVALID_NOT_A_LETTER)

Guessaletter: zbodypart#1
('pen???n', GUESS.INCORRECT)

Guessaletter: xbodypart#1bodypart#2
('pen???n', GUESS.INCORRECT)

Guessaletter: cbodypart#1bodypart#2bodypart#3
('pen???n', GUESS.INCORRECT)

Guessaletter: i
(set(['p', 'c', 'e', 'i', 'x', 'z', 'n']), set(['e', 'g', 'i', 'n', 'p', 'u']))
('pen??in', GUESS.CORRECT)

Guessaletter: u
(set(['c', 'e', 'i', 'n', 'p', 'u', 'x', 'z']), set(['e', 'g', 'i', 'n', 'p', 'u']))
('pen?uin', GUESS.CORRECT)

Guessaletter: g
(set(['c', 'e', 'g', 'i', 'n', 'p', 'u', 'x', 'z']), set(['e', 'g', 'i', 'n', 'p', 'u']))
('penguin', GUESS.CORRECT_WIN)

NEWGAMEGuessaletter: qbodypart#1
('???????', GUESS.INCORRECT)

Guessaletter: wbodypart#1bodypart#2
('???????', GUESS.INCORRECT)

Guessaletter: rbodypart#1bodypart#2bodypart#3
('???????', GUESS.INCORRECT)

...moreincorrectguesses...

('???????', GUESS.INCORRECT_LOSS)

Post a Comment for "For Loop Functions In Python"