Hangman Projekt

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
jagr29
User
Beiträge: 2
Registriert: Donnerstag 20. Januar 2022, 18:42

Hallo, ich habe eine Frage zu diesem Programm. Teilweise habe ich es selbst geschrieben, aber zwei Parts habe ich von einer Quelle und verstehe sie nicht ganz. Vielleicht kann mir jemand erklären, was dabei genau passiert.

Außerdem habe ich eine komische Linie, wenn die Zeichnung von turtle zwischen den if, elif und else auf das letzte else springt.

Vielleicht kann mir jemand hier helfen.
Vielen dank und LG

#import the necessary modules
import random
import turtle

#import the lists out of a seperate file
from categories import categorie_animal
from categories import categorie_flower
from categories import categorie_vehicle
from categories import categorie_clothes
from categories import categorie_colour
from categories import categorie_emotions


#Creat a turtle and hide the symbol
bob = turtle.Turtle()
bob.hideturtle()



def getLength():
wordLength = []
for i in range(len(randomWord)):
wordLength.append('_ ')
return wordLength



#ask the user which categorie he/she wants to play
randomWord = input("What categorie do you want to play? animal, flower, vehicle, clothes, colour or emotions? \n").lower()

#Check if the input is correct
while randomWord not in ["animal","flower","vehicle","clothes","colour","emotions"]:
print ("Invalid input, please try again: \n")
randomWord = input("What categorie do you want to play? animal, flower, vehicle, clothes, colour or emotions? \n ").lower()

else:
print ("The categorie "+randomWord+" is a great choice!")

#Get a random word out of the chosen categorie
if randomWord == "animal":
randomWord = random.choice(categorie_animal)
wordLength = getLength()
print("" . join(wordLength))

elif randomWord == "flower":
randomWord = random.choice(categorie_flower)
wordLength = getLength()
print("" . join(wordLength))

elif randomWord == "vehicle":
randomWord = random.choice(categorie_vehicle)
wordLength = getLength()
print("" . join(wordLength))

elif randomWord == "clothes":
randomWord = random.choice(categorie_clothes)
wordLength = getLength()
print("" . join(wordLength))

elif randomWord == "colour":
randomWord = random.choice(categorie_colour)
wordLength = getLength()
print("" . join(wordLength))

else:
randomWord = random.choice(categorie_emotions)
wordLength = getLength()
print("" . join(wordLength))


tries = 8

gussedWord = list(getLength())

#Game
while tries > 0:
if "".join(gussedWord) == randomWord:
print("You are awesome! You gussed the correct word!")
break

print("You get "+ str(tries) + " tries ")
gussedLetter = input("Guess a letter: \n").lower()


if gussedLetter in randomWord:
print("Correct!")
for i in range(len(randomWord)):
if list(randomWord) == gussedLetter:
gussedWord = gussedLetter
print("".join(gussedWord))


else:
print("That´s a wrong letter!") #Print it ´s wrong
tries -= 1 #Reduce the tries

#Draw the hangman lines
if tries == 7:
bob.forward(100)

elif tries == 6:
bob.backward(50)
bob.left(90)
bob.forward(200)

elif tries == 5:
bob.right(90)
bob.forward(100)

elif tries == 4:
bob.right(90)
bob.forward (40)

elif tries == 3:
bob.right(90)
bob.circle(15)

elif tries == 2:
bob.pencolor("white")
bob.left(90)
bob.forward(30)
bob.pencolor("black")
bob.forward(40)

else:
bob.backward(20)
bob.right(135)
bob.forward(20)
bob.backward(20)
bob.right(90)
bob.forward(20)

#Game over
else:
bob.left(90)
bob.forward(30)
bob.right(45)
bob.forward(20)
bob.backward(20)
bob.right(-90)
bob.forward(20)

print("You ran out of tries! The searched word is: "+randomWord)
Sirius3
User
Beiträge: 17754
Registriert: Sonntag 21. Oktober 2012, 17:20

Eingerückt wird immer mit 4 Leerzeichen pro Ebene. Nicht mal 8 und mal 4. Variablennamen schreibt man immer komplett klein, Konstanten komplett GROSS.
Statt 6 separate Variablen für die Kategorien nimmt man ein Wörterbuch. Das macht das Erweitern viel einfacher, und reduziert den Code enorm.

`getLength` ist ein falscher Name, weil da wird keine Länge ermittelt, sondern eine Liste mit Platzhaltern. Alles was eine Funktion braucht, muß sie über ihre Argumente bekommen, `randomWord` kommt aus dem nichts.

Ansonsten fehlen noch viele Funktionen. Jeder Programmteil muß in eine eigene Funktion. Das ersetzt die Kommentar, weil die Funktionsnamen schon sagen was da passiert.

`randomWord` ist dann der falsche Name für eine Kategorie.
Der Code für `input` kommt zweimal im Code vor. Besser wäre es, wenn es ihn nur einmal gäbe. Das erreicht man dadurch, dass man die while-Schleife umstellt.

Strings setzt man nicht mit + zusammen, sondern benutzt Formatstrings.
`wordLength` wird nur einmal benutzt, danach wechselst Du zu `gussedWord`. Eigentlich ist nur eins davon nötig.
`gussedWord` ist dann schon eine Liste.

Eine Schleife über einen Index macht man in Python nicht, weil man direkt über die Elemente iterieren kann. In jedem Schleifendurchgang per `list(randomWord)` den String in eine Liste umzuwandeln, nur um einen Buchstaben herauszuholen, ist ziemliche Verschwendung, zumal man auf Strings genauso per [] zugreifen kann.

Code: Alles auswählen

import random
import turtle

#import the lists out of a seperate file
from categories import (categorie_animal, categorie_flower, categorie_vehicle,
        categorie_clothes, categorie_colour, categorie_emotions)

WORDS_IN_CATEGORIES = {
    "animal": categorie_animal,
    "flower": categorie_flower,
    "vehicle": categorie_vehicle,
    "clothes": categorie_clothes,
    "colour": categorie_colour,
    "emotions": categorie_emotions,
}

def get_placeholders(word):
    return list('_' * len(word))

def ask_for_category():
    while True:
        category = input(f"What categorie do you want to play? {', '.join(WORDS_IN_CATEGORIES)}? \n").lower()
        if category in WORDS_IN_CATEGORIES:
            break
        print ("Invalid input, please try again: \n")
    print (f"The category {category} is a great choice!")
    return category

def get_random_word():
    category = ask_for_category()
    return random.choice(WORDS_IN_CATEGORIES[category])

def draw_hangman(bob, tries):
    if tries == 7:
        bob.forward(100)
    elif tries == 6:
        bob.backward(50)
        bob.left(90)
        bob.forward(200)
    elif tries == 5:
        bob.right(90)
        bob.forward(100)
    elif tries == 4:
        bob.right(90)
        bob.forward (40)
    elif tries == 3:
        bob.right(90)
        bob.circle(15)
    elif tries == 2:
        bob.pencolor("white")
        bob.left(90)
        bob.forward(30)
        bob.pencolor("black")
        bob.forward(40)
    else:
        bob.backward(20)
        bob.right(135)
        bob.forward(20)
        bob.backward(20)
        bob.right(90)
        bob.forward(20)

def draw_gameover(bob):
    bob.left(90)
    bob.forward(30)
    bob.right(45)
    bob.forward(20)
    bob.backward(20)
    bob.right(-90)
    bob.forward(20)

def main():
    #Creat a turtle and hide the symbol
    bob = turtle.Turtle()
    bob.hideturtle()

    word = get_random_word()
    guessed_word = get_placeholders(word)
    print(" ".join(guessed_word))

    tries = 8
    while tries > 0:
        if "".join(guessed_word) == word:
            print("You are awesome! You gussed the correct word!")  
            break
    
        print(f"You get {tries} tries ")             
        guessed_letter = input("Guess a letter: \n").lower()    

        if guessed_letter in word:
            print("Correct!")
            for i, letter in enumerate(word):
                if letter == guessed_letter:
                    guessed_word[i] = letter
            print(" ".join(guessed_word))
        else: 
            print("That´s a wrong letter!")
            tries -= 1
            draw_hangman(bob, tries)
    else:
        draw_gameover(bob)
        print(f"You ran out of tries! The searched word is: {word}")

if __name__ == "__main__":
    main()
Und was konkret verstehst Du an den eingefärbten Stellen nicht?
jagr29
User
Beiträge: 2
Registriert: Donnerstag 20. Januar 2022, 18:42

Hallo,

vielen Dank für deine sehr ausführliche Antwort. Es hat mir sehr weitergeholfen.
Nun verstehe ich den Code komplett.

Bin noch eine Anfängerin und kenne manche Regeln noch nicht ;)

LG und Danke Jagr29
Antworten