파이썬 터틀을 이용한 간단한 행맨게임
Result :
Code :
import random
import turtle
screen = turtle.Screen()
at = turtle.Turtle()
word_list = ["테스트", "oriel", "PHENOMENA"]
def get_word():
word = random.choice(word_list)
return word.upper()
def play(word):
at.reset()
at.pencolor('black')
at.pensize(10)
at.pu()
at.goto(-120, 20)
at.pd()
word_completion = "_" * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
exec(display_hangman(tries))
print(word_completion)
print("\n")
while not guessed and tries > 0:
guess = screen.textinput("Input", "한 글자만 입력해주세요 : ")
if guess is None:
break
guess = guess.upper()
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print("그 글자는 사용했던 글자입니다. 다른 글자를 입력해주세요 : ")
elif guess not in word:
print(guess, "틀렸습니다.")
tries -= 1
exec(display_hangman(tries))
guessed_letters.append(guess)
else:
print("축하합니다.", guess, "맞는 글자입니다!")
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
elif len(guess) == len(word) and guess.isalpha():
if guess in guessed_words:
print("", guess)
elif guess != word:
print(guess, "틀렸습니다.")
tries -= 1
exec(display_hangman(tries))
guessed_words.append(guess)
else:
guessed = True
word_completion = word
else:
print("졌습니다.")
exec(display_hangman(tries))
print(word_completion)
print("\n")
if guessed:
print("축하합니다! 게임에서 승리하셨습니다.")
else:
print("당신은 기회를 다 쓰셨습니다. 단어는 " + word + ". 다음 기회에!")
turtle.title("PHENOMENA.COM")
turtle.addshape('분필.gif')
turtle.shape('분필.gif')
turtle.bgpic('칠판.gif')
turtle.pu()
turtle.goto(-120, 100)
turtle.pencolor('black')
turtle.pensize(10)
turtle.pd()
turtle.lt(90)
turtle.fd(50)
turtle.lt(90)
turtle.fd(100)
turtle.lt(90)
turtle.fd(350)
turtle.penup()
turtle.goto(-150, -205)
turtle.pd()
turtle.right(90)
turtle.fd(130)
turtle.pu()
turtle.goto(-120, 100)
turtle.pd()
def display_hangman(tries):
stages = [ # final state:
'''
at.pu()
at.goto(-120,-100)
at.pd()
at.lt(90)
at.fd(75)
''',
# head, torso, both arms, and one leg
'''
at.pu()
at.goto(-120,-100)
at.pd()
at.rt(90)
at.fd(75)
''',
# head, torso, and both arms
'''
at.pu()
at.goto(-120,-20)
at.pd()
at.lt(90)
at.fd(70)
''',
# head, torso, and one arm
'''
at.pu()
at.goto(-120,-20)
at.pd()
at.rt(45)
at.fd(70)
''',
# head and torso
'''
at.pu()
at.goto(-120,-100)
at.pd()
at.lt(90)
at.fd(115)
''',
# head
'''
at.circle(40)
''',
''
]
return stages[tries]
def main():
word = get_word()
play(word)
while screen.textinput("Next Game", "Play Again? (Y/N) ") in ["y", "Y"]:
word = get_word()
play(word)
if __name__ == "__main__":
main()