Suche nach Möglichkeiten, mein Henkers Code zu verbessern
-
05-09-2019 - |
Frage
Just in Python bekommen, und so habe ich beschlossen, einen Henker Spiel zu machen. Funktioniert gut, aber ich frage mich, ob es irgendeine Art von Optimierungen war ich machen oder Wege könnte den Code zu bereinigen. Auch, wenn jemand ein Projekt empfehlen könnte, die ich tun könnte neben das wäre cool.
import sys
import codecs
import random
def printInterface(lst, attempts):
""" Prints user interface which includes:
- hangman drawing
- word updater """
for update in lst:
print (update, end = '')
if attempts == 1:
print ("\n\n\n\n\n\n\n\n\n\n\n\t\t _____________")
elif attempts == 2:
print ("""
|
|
|
|
|
|
|
|
|
______|______""")
elif attempts == 3:
print ("""
______
|
|
|
|
|
|
|
|
|
______|______""")
elif attempts == 4:
print ("""
______
| |
| |
(x_X) |
|
|
|
|
|
|
______|______""")
elif attempts == 5:
print ("""
______
| |
| |
(x_X) |
| |
| |
| |
|
|
|
______|______""")
elif attempts == 6:
print ("""
______
| |
| |
(x_X) |
| |
/| |
| |
|
|
|
______|______""")
elif attempts == 7:
print ("""
______
| |
| |
(x_X) |
| |
/|\ |
| |
|
|
|
______|______""")
elif attempts == 8:
print ("""
______
| |
| |
(x_X) |
| |
/|\ |
| |
/ |
|
|
______|______""")
elif attempts == 9:
print ("""
______
| |
| |
(x_X) |
| |
/|\ |
| |
/ \ |
|
|
______|______""")
def main():
try:
wordlist = codecs.open("words.txt", "r")
except Exception as ex:
print (ex)
print ("\n**Could not open file!**\n")
sys.exit(0)
rand = random.randint(1,5)
i = 0
for word in wordlist:
i+=1
if i == rand:
break
word = word.strip()
wordlist.close()
lst = []
for h in word:
lst.append('_ ')
attempts = 0
printInterface(lst,attempts)
while True:
guess = input("Guess a letter: ").strip()
i = 0
for letters in lst:
if guess not in word:
print ("No '{0}' in the word, try again!".format(guess))
attempts += 1
break
if guess in word[i] and lst[i] == "_ ":
lst[i] = (guess + ' ')
i+=1
printInterface(lst,attempts)
x = lst.count('_ ')
if x == 0:
print ("You win!")
break
elif attempts == 9:
print ("You suck! You iz ded!")
break
if __name__ == '__main__':
while True:
main()
again = input("Would you like to play again? (y/n): ").strip()
if again.lower() == "n":
sys.exit(1)
print ('\n')
Lösung
Erste Idee: ASCII-Kunst
Die Dinge etwas Besonderes zu Python sind Syntax für reguläre Ausdrücke und range()
Funktion sowie [xxx for yyy in zzz]
Array Füllstoff.
import re
def ascii_art(attempt):
return re.sub(r'\d', '', re.sub('[0{0}].' \
.format(''.join([str(e) for e in range(attempt + 1, 10)])), ' ', """
3_3_3_3_3_3_
4| 2|
4| 2|
4(4x4_4X4) 2|
5| 2|
6/5|7\ 2|
5| 2|
8/ 9\ 2|
2|
2|
1_1_1_1_1_1_1|1_1_1_1_1_1_
"""))
for i in range(1, 10):
print(ascii_art(i))
Zweite Idee: Schleifen
Mit enumerate
für Wort Leseschleife. Mit
for attempt in range(1, 10):
# inside main loop
...
print ('you suck!')
als Hauptschleife zurück. Operator break
sollte mit Vorsicht und nicht als Ersatz für for
verwendet werden!
Wenn ich etwas vermissen, die Struktur von
for letters in lst:
if guess not in word:
...
break
if guess in word[i]:
...
wird transparenter als
if guess not in word:
...
else:
index = word.find (guess)
...
Andere Tipps
Ich habe nicht versucht, den Code, aber hier ist einige zufälligen Tipps:
-
Versuchen Sie den Code entsprechend zu formatieren, um PEP 8 (verwenden
i += 1
statti+=1
). PEP 8 ist die Standard-Styleguide für Python. -
Mit
lst = ['_ '] * len(word)
anstelle der for-Schleife.
-
Verwenden Sie enumerate wie in:
for i, word in enumerate(wordlist)
anstelle von Spur
i
in der Schleife von Hand zu halten. -
Der Standardmodus für das Öffnen von Dateien ist
'r'
, gibt es keine Notwendigkeit, es zu spezifizieren. Verwenden Siecodecs.open
anstelle des eingebauten inopen
um zurück Unicode-Strings zu bekommen? Versuchen Sie auch, eine spezifischere Ausnahme zu fangen, dieException
-. WahrscheinlichIOError
Ich würde Liste verwenden, statt, wenn .. else-Anweisung in printInterface.