scripting - Hangman in python: have lines be replaced? -
i'm working on writing simple hangman game in python know far (i'm doing learn python hard way) , far have this:
from sys import argv import random script_name, dict_file = argv hang_list = open(dict_file).read().splitlines() hang_list = filter(none, hang_list) word = random.choice(hang_list) guesses = '' def compare_words(): global guesses new_word = '' char in word: if char in guesses: new_word += char else: new_word += "_" return new_word def test_letter(): global guesses letter = raw_input("guess letter: ") guesses += letter new_word = compare_words() print "\ncurrent guesses: %s" % guesses print "%s\n\n" % new_word if new_word == word: print "you won!" else: test_letter() test_letter()
i've yet implement scoring system (piece of cake) have issue layout. can tell, print "current guesses: " , new word each time; however, want 4 lines like:
guess letter: guesses: abczy __c__b_
and have 3 lines keep updating. however, having trouble figuring out how make print replace stdout. believe need use \r
escape character, yet i've tried placing in various places can't work. so, how should modify replace? prefer not clear, still makes things bit messy; want replace what's there. thanks!
it bit tricky make work terminals, if yours understands ansi escape codes mine does, might work:
... if new_word == word: print "you won!" else: print '\033[f'*7 print ' '*17 + '\b'*17 + '\033[f' test_letter()
this relies on ansi code f
: move cursor 1 line; backspaces (\b
) alone have no effect once beginning of line reached. first print
takes input line , second deletes character entered.
Comments
Post a Comment