← RU Pythoncursus

Uitwerking: Teken de galg

import random
import turtle

def hangman():
# if n == 10:
    turtle.left(180)
    turtle.forward(r*100)
# if n == 9:
    yield
    turtle.backward(r*20)
    turtle.right(90)
    turtle.forward(r*150)
# if n == 8:
    yield
    turtle.backward(r*100)
    turtle.right(135)
    turtle.forward(r*70)
# if n == 7:
    yield
    turtle.backward(r*70)
    turtle.left(135)
    turtle.forward(r*100)
    turtle.right(90)
    turtle.forward(r*50)
# if n == 6:
    yield
    turtle.right(90)
    turtle.forward(r*30)
    yield
    turtle.color('black')
    turtle.width(1)
    turtle.right(90)
    turtle.circle(r*10)
    turtle.circle(r*10, 180)
    yield
    turtle.left(15)
    turtle.forward(r*18)
    turtle.backward(r*18)
    yield
    turtle.left(150)
    turtle.forward(r*18)
    turtle.backward(r*18)
    yield
    turtle.left(105)
    turtle.forward(r*20)
    yield
    turtle.left(15)
    turtle.forward(r*30)
    turtle.backward(r*30)
    yield
    turtle.right(30)
    turtle.forward(r*30)
    # backward(r*30)
    yield
    yield

def replace(s, p, c):
    return s[:p] + c + s[p+1:]

turtle.position()
turtle.color('brown')
turtle.width(3)
turtle.speed(10)
r = 2

words = [word.strip() for word in open('woordenlijst/woordenlijst.txt')]
word = random.choice(words)

guessed = '.' * len(word)
guesses = 11
attempts = ''
gallow = hangman()
while guesses > 0 and word != guessed:
    print('=====')
    print('Het woord is nu:', guessed)
    print('Je hebt nog', guesses, 'pogingen' if guesses > 1 else 'poging')
    print('Raad een letter ')
    letter = input()[0]
    if letter in attempts:
        print('Die hadden we al:', attempts)
        continue
    attempts += letter
    if letter not in word:
        print('Die zit er niet in!')
        next(gallow)
        guesses -= 1
    else:
        print('Die zit er wel in!')
        for i in range(len(word)): # dit kan eventueel ook met enumerate()
            if word[i] == letter:
                guessed = replace(guessed, i, letter)

if guessed == word:
    print('Je hebt gewonnen!')
elif guesses == 0:
    print('Je hebt verloren!')
print('Het woord was:', word)
turtle.done()