TDT4109/Exercise 3/task10.py

58 lines
1.4 KiB
Python
Raw Normal View History

2020-09-14 15:58:36 +02:00
import os
2020-09-14 16:36:09 +02:00
2020-09-14 15:58:36 +02:00
class game():
def __init__(self):
self.secret_word = input('Skriv inn det hemmelige ordet: ')
self.lives = int(input('Hvor mange forsøk får brukeren? '))
self.lettersLeft = list(self.secret_word)
os.system('clear')
def getWord(self):
2020-09-14 16:36:09 +02:00
return ''.join([('*' if (ch in self.lettersLeft) else ch)
for ch in list(self.secret_word)])
2020-09-14 15:58:36 +02:00
def removeLetterFromLettersLeft(self, letter):
2020-09-14 16:36:09 +02:00
self.lettersLeft = list(
filter(lambda leftLetter: leftLetter != letter, self.lettersLeft))
2020-09-14 15:58:36 +02:00
def gameOver(self):
print('Du har ingen liv igjen.')
exit(0)
2020-09-14 16:36:09 +02:00
2020-09-14 15:58:36 +02:00
def gameWon(self):
print(f'Gratulerer. Ordet var {self.secret_word}')
exit(0)
def wrongLetter(self, letter):
print(f'Bokstaven {letter} er ikke i ordet.')
self.lives -= 1
if self.lives == 0:
self.gameOver()
print(f'Du har {self.lives} liv igjen, prøv på nytt.')
def rightLetter(self, letter):
print('Stemmer, bokstaven er i ordet')
self.removeLetterFromLettersLeft(letter)
if self.lettersLeft == []:
self.gameWon()
def update(self):
print(self.getWord())
letter = input('Gjett på én bokstav i ordet: ')
if letter in self.lettersLeft:
self.rightLetter(letter)
else:
self.wrongLetter(letter)
2020-09-14 16:36:09 +02:00
2020-09-14 15:58:36 +02:00
def loop(self):
while True:
os.system('clear')
self.update()
input("Trykk enter for å fortsette...")
2020-09-14 16:36:09 +02:00
2020-09-14 15:58:36 +02:00
if __name__ == "__main__":
2020-09-14 16:36:09 +02:00
myGame = game()
myGame.loop()