Skip to content

Commit

Permalink
Garante que as características do terminal são restauradas.
Browse files Browse the repository at this point in the history
Na implementação anterior o terminal podia ficar zoado em caso de erro
enquanto estava em modo Raw. Assim devemos estar mais seguros.
  • Loading branch information
flavioamieiro committed Mar 28, 2012
1 parent d790d82 commit 0b80a76
Showing 1 changed file with 19 additions and 18 deletions.
37 changes: 19 additions & 18 deletions snake_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,24 +135,25 @@ def read_key(self):
# term input and output is disabled.
tty.setraw(sys.stdin)

# get the key (using select for timeout) select() needs three
# lists of file descriptors to poll, and an optional
# timeout. It returns a tuple of three lists of fd's as soon
# as one of them has seen some action, or 'timeout' has
# passed.
inpt, outpt, excpt = select.select([sys.stdin], [], [], self.timeout)

# we need to check if there was input
if inpt:
key = inpt[0].read(1)
# or the timeout was reached (and we pretend a 'random' key
# was pressed)
else:
key = '?'

# return to old attributes after everything from fd was read
# (TCSADRAIN)
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty_attr)
try:
# get the key (using select for timeout) select() needs three
# lists of file descriptors to poll, and an optional
# timeout. It returns a tuple of three lists of fd's as soon
# as one of them has seen some action, or 'timeout' has
# passed.
inpt, outpt, excpt = select.select([sys.stdin], [], [], self.timeout)

# we need to check if there was input
if inpt:
key = inpt[0].read(1)
# or the timeout was reached (and we pretend a 'random' key
# was pressed)
else:
key = '?'
finally:
# return to old attributes after everything from fd was read
# (TCSADRAIN)
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty_attr)

return key

Expand Down

0 comments on commit 0b80a76

Please sign in to comment.