Created
July 15, 2011 05:13
-
-
Save livibetter/1084116 to your computer and use it in GitHub Desktop.
my urwid tiny files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# | |
# Using new Terminal widget for a simple text viewer with ANSI escape code. | |
# ONLY read from pipe. This is just an sample code, not gonna to be developed | |
# further. | |
# | |
# Copyright (C) 2011 by Yu-Jie Lin | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy | |
# of this software and associated documentation files (the "Software"), to deal | |
# in the Software without restriction, including without limitation the rights | |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
# copies of the Software, and to permit persons to whom the Software is | |
# furnished to do so, subject to the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included in | |
# all copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
# THE SOFTWARE. | |
import os | |
import sys | |
import urwid | |
class ANSIColorText(urwid.BoxWidget): | |
def __init__(self, text): | |
self.__super.__init__() | |
self.term = None | |
self.term_modes = urwid.TermModes() | |
self.term_size = None | |
self.text = text | |
def render(self, size, focus=False): | |
if not self.term or self.term_size != size: | |
width, height = size | |
self.term = urwid.TermCanvas(width, height, self) | |
self.term.modes.lfnl = True | |
self.term.modes.visible_cursor = False | |
self.term.addstr(self.text) | |
self.term_size = size | |
return self.term | |
def keypress(self, size, key): | |
if 'up' in key or 'down' in key: | |
if 'page' in key: | |
lines = self.term_size[1] | |
else: | |
lines = 5 if 'meta' in key else 1 | |
self.term.scroll_buffer(up=True if 'up' in key else False, lines=lines) | |
elif 'home' in key or 'end' in key: | |
lines = len(self.term.scrollback_buffer) | |
self.term.scroll_buffer(up=True if 'home' in key else False, lines=lines) | |
else: | |
return key | |
self._invalidate() | |
def mouse_event(self, size, event, button, col, row, focus): | |
if 'mouse press' in event and button in (4, 5): | |
key = 'up' if button == 4 else 'down' | |
if 'meta' in event: | |
key = 'meta ' + key | |
elif 'ctrl' in event: | |
key = 'page ' + key | |
self.keypress(size, key) | |
else: | |
return False | |
def unhandled_input(key): | |
if key in ('q', 'Q'): | |
raise urwid.ExitMainLoop | |
# Read from pipe and apply line no | |
s = sys.stdin.readlines() | |
s[-1] = s[-1].rstrip('\n') | |
w = len(str(len(s))) | |
lfmt = '%%0%dd %%s' % w | |
s = ''.join([lfmt % l for l in enumerate(s, start=1)]) | |
txt = ANSIColorText(s) | |
# Reopen the stdin for urwid or will get an error as follows: | |
# | |
# File "/home/livibetter/path/to/urwid/raw_display.py", line 174, in start | |
# self._old_termios_settings = termios.tcgetattr(0) | |
# termios.error: (22, 'Invalid argument') | |
# | |
# Reference: http://stackoverflow.com/questions/3999114/linux-pipe-into-python-ncurses-script-stdin-and-termios/4000997#4000997 | |
sys.__stdin__.close() | |
sys.__stdin__ = sys.stdin = open('/dev/tty') | |
os.dup2(sys.stdin.fileno(), 0) | |
palette = [ | |
('key hints', 'light blue', 'white'), | |
('key', 'white', 'light blue'), | |
] | |
def addkey(k, desc): | |
return [('key', ' %s ' % k), ' %s ' % desc if desc else ' '] | |
footer = urwid.Text([ | |
addkey('q', 'Quit'), | |
addkey('Up/Down/Wheel', ''), | |
addkey('Alt+Up/Down/Wheel', ''), | |
addkey('Page Up/Down|Ctrl+Wheel', ''), | |
addkey('Home/End', ''), | |
]) | |
footer = urwid.AttrMap(footer, 'key hints') | |
frame = urwid.Frame(txt, footer=footer) | |
loop = urwid.MainLoop(frame, palette=palette, unhandled_input=unhandled_input) | |
loop.run() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# Copyright (C) 2011 by Yu-Jie Lin | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy | |
# of this software and associated documentation files (the "Software"), to deal | |
# in the Software without restriction, including without limitation the rights | |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
# copies of the Software, and to permit persons to whom the Software is | |
# furnished to do so, subject to the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included in | |
# all copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
# THE SOFTWARE. | |
import urwid | |
class MyBigText(urwid.BigText): | |
_selectable = True | |
signals = ['keypress', 'mouse_event'] | |
def keypress(self, size, key): | |
# self._emit(), i.e. Widget._emit(), does not handle/return return value of | |
# event handler. | |
if urwid.emit_signal(self, 'keypress', self, size, key): | |
return key | |
def mouse_event(self, *args): | |
self._emit('mouse_event', *args) | |
return True | |
def main(): | |
TEXT = 'MyBigText [F10 to Quit]' | |
palette = [ | |
('bigtext', 'white', 'dark gray'), | |
('bigtext focus', 'light red', 'white'), | |
('listbox header', 'light blue', 'dark green'), | |
('listbox', 'white', 'dark gray'), | |
('listbox focus', 'light red', 'white'), | |
] | |
def event_handler(w, *args): | |
if args[1] == 'f10': | |
return True | |
btevts.append(urwid.Text(repr(args))) | |
btevts.set_focus(len(btevts) - 1) | |
def unhandled_input(inp): | |
if inp == 'f10': | |
raise urwid.ExitMainLoop | |
uhevts.append(urwid.Text(repr(inp))) | |
uhevts.set_focus(len(uhevts) - 1) | |
font = urwid.HalfBlock5x4Font() | |
btxt = MyBigText(TEXT, font) | |
urwid.connect_signal(btxt, 'keypress', event_handler) | |
urwid.connect_signal(btxt, 'mouse_event', event_handler) | |
try: | |
if urwid.AttrMap.pack.__func__ is urwid.Widget.pack.__func__: | |
urwid.AttrMap.pack = property(lambda self:self._original_widget.pack) | |
except: | |
pass | |
btxt = urwid.AttrMap(btxt, 'bigtext', 'bigtext focus') | |
btxt_p = urwid.Padding(btxt, width='clip') | |
btxt_f = urwid.Filler(btxt_p, height=font.height) | |
btevts = urwid.SimpleListWalker([]) | |
uhevts = urwid.SimpleListWalker([]) | |
pile = urwid.Pile([ | |
('fixed', font.height, btxt_f), | |
('fixed', 1, urwid.AttrMap(urwid.Filler(urwid.Text('MyBigText Events')), 'listbox header')), | |
('weight', 1, urwid.AttrMap(urwid.ListBox(btevts), 'listbox', 'listbox focus')), | |
('fixed', 1, urwid.AttrMap(urwid.Filler(urwid.Text('Unhandled Events')), 'listbox header')), | |
('weight', 1, urwid.AttrMap(urwid.ListBox(uhevts), 'listbox', 'listbox focus')), | |
]) | |
loop = urwid.MainLoop(pile, palette=palette, unhandled_input=unhandled_input) | |
loop.run() | |
if __name__ == '__main__': | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# Copyright (C) 2011 by Yu-Jie Lin | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy | |
# of this software and associated documentation files (the "Software"), to deal | |
# in the Software without restriction, including without limitation the rights | |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
# copies of the Software, and to permit persons to whom the Software is | |
# furnished to do so, subject to the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included in | |
# all copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
# THE SOFTWARE. | |
import time | |
import urwid | |
class double_press_input_filter: | |
''' | |
A filter generates new mouse event, double press. | |
Usage: | |
loop = urwid.MainLoop(..., input_filter=double_press_input_filter(), ...) | |
When double-press the mouse buttons (1, 2, and 3. Wheels are ignored), the | |
handler shall receive events as follow, in order: | |
('mouse press', 1, 21, 14) | |
('mouse release', 0, 21, 14) | |
('mouse press', 1, 21, 14) | |
('mouse double press', 1, 21, 14) | |
('mouse release', 0, 21, 14) | |
''' | |
last_press = None | |
last_press_time = -1 | |
double_press_timing = 0.25 | |
@classmethod | |
def __call__(cls, events, raw): | |
i = 0 | |
while i < len(events): | |
e = events[i] | |
i += 1 | |
if not urwid.is_mouse_event(e) or not urwid.is_mouse_press(e[0]): | |
continue | |
if cls.last_press and \ | |
time.time() > cls.last_press_time + cls.double_press_timing: | |
cls.last_press = None | |
if cls.last_press: | |
if cls.last_press[1] == e[1]: | |
events.insert(i, (e[0].replace('press', 'double press'),) + e[1:]) | |
i += 1 | |
elif urwid.is_mouse_press(e[0]) and e[1] not in (4, 5): | |
cls.last_press = e | |
cls.last_press_time = time.time() | |
continue | |
cls.last_press = None | |
return events | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff -r 1a1111fa4d13 urwid/raw_display.py | |
--- a/urwid/raw_display.py Sat Jul 16 12:25:31 2011 -0400 | |
+++ b/urwid/raw_display.py Sun Jul 17 09:43:45 2011 +0800 | |
@@ -69,6 +69,10 @@ | |
self._cy = 0 | |
self.bright_is_bold = os.environ.get('TERM',None) != "xterm" | |
self._next_timeout = None | |
+ self._emulate_double_press = True | |
+ self._double_press_timing = 0.2 | |
+ self._last_mouse_press = None | |
+ self._last_mouse_release = None | |
self._term_output_file = sys.stdout | |
self._term_input_file = sys.stdin | |
# pipe for signalling external event loops about resize events | |
@@ -348,9 +352,54 @@ | |
original_codes = codes | |
try: | |
+ if self._last_mouse_press and not codes: | |
+ processed.append(self._last_mouse_press) | |
+ self._last_mouse_press = None | |
+ if self._last_mouse_release: | |
+ processed.append(self._last_mouse_release) | |
+ self._last_mouse_release = None | |
while codes: | |
run, codes = escape.process_keyqueue( | |
codes, True) | |
+ new_run = [] | |
+ if self._emulate_double_press: | |
+ while run: | |
+ one_run = run.pop(0) | |
+ if self._last_mouse_press: | |
+ # Has one previous mouse press | |
+ if util.is_mouse_event(one_run): | |
+ if self._last_mouse_press == one_run: | |
+ # The second press enters, we have a double press | |
+ new_run.append((one_run[0].replace('press', 'double press'),) + tuple(one_run[1:])) | |
+ self._last_mouse_press = None | |
+ self._last_mouse_release = None | |
+ elif self._last_mouse_press[0].replace('press', 'release') == one_run[0] and \ | |
+ self._last_mouse_press[2:] == one_run[2:]: | |
+ # Release event with exactly same x, y. Button is ignored due to release button is zero. | |
+ # Discard this release event | |
+ self._last_mouse_release = one_run | |
+ else: | |
+ # Not a mouse event, can't be double press this round | |
+ new_run.append(self._last_mouse_press) | |
+ self._last_mouse_press = None | |
+ if self._last_mouse_release: | |
+ new_run.append(self._last_mouse_release) | |
+ self._last_mouse_release = None | |
+ new_run.append(one_run) | |
+ else: | |
+ # Not a mouse event, can't be double press this round | |
+ new_run.append(self._last_mouse_press) | |
+ self._last_mouse_press = None | |
+ if self._last_mouse_release: | |
+ new_run.append(self._last_mouse_release) | |
+ self._last_mouse_release = None | |
+ new_run.append(one_run) | |
+ elif util.is_mouse_event(one_run) and 'mouse press' in one_run[0] and one_run[1] not in (4, 5): | |
+ # No previous mouse press event and here comes one | |
+ self._last_mouse_press = one_run | |
+ else: | |
+ new_run.append(one_run) | |
+ run = new_run | |
processed.extend(run) | |
except escape.MoreInputRequired: | |
k = len(original_codes) - len(codes) | |
@@ -371,7 +420,10 @@ | |
processed.append('window resize') | |
self._resized = False | |
- yield (self.max_wait, processed, original_codes) | |
+ if self._last_mouse_press: | |
+ yield (self._double_press_timing, processed, original_codes) | |
+ else: | |
+ yield (self.max_wait, processed, original_codes) | |
empty_resize_pipe() | |
def _fake_input_iter(self): |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
GemFont = ''' | |
12345 | |
xxx | |
xxxxx | |
xxx | |
*** | |
***** | |
* | |
x | |
xxx | |
xxxxx | |
/o\ | |
ooooo | |
\o/ | |
/---\ | |
|xxx| | |
\---/ | |
/|\ | |
< > | |
\|/ | |
@@@ | |
@@@@@ | |
@@@ | |
''' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import pymunk as pm | |
import urwid | |
def update(loop, data): | |
dt = 1.0/100.0 | |
for i in range(10): | |
loop.space.step(dt) | |
loop.widget.align_amount = int(loop.space.ball.position.x) | |
loop.widget.valign_amount = int(loop.screen.get_cols_rows()[1] - loop.space.ball.position.y) | |
loop.widget._invalidate() | |
loop.set_alarm_in(0.1, update) | |
def create_pm_objects(space): | |
# Creating the floor | |
floor_body = pm.Body(pm.inf, pm.inf) | |
floor_body.position = 0, 0 | |
floor_sgs = [pm.Segment(floor_body, a, b, 0.5) for a, b in [ | |
((0, 4.5), (2.5, 4.5)), | |
((2.5, 4.5), (6.5, 0.5)), | |
((6.5, 0.5), (24.5, 0.5)), | |
((24.5, 0.5), (31.5, 7.5)), | |
((31.5, 7.5), (34.5, 7.5)), | |
((34.5, 7.5), (34.5, 9.5)), | |
]] | |
for sg in floor_sgs: | |
sg.elasticity = 0.7 | |
sg.friction = 0.2 | |
space.add_static(floor_sgs) | |
# Creating a ball | |
mass = 10.0 | |
radius = 0.5 | |
inertia = pm.moment_for_circle(mass, 0, radius, (0, 0)) | |
ball_body = pm.Body(mass, inertia) | |
ball_body.position = 5, 20 | |
ball = pm.Circle(ball_body, radius, (0, 0)) | |
ball.elasticity = 0.9 | |
space.add(ball_body, ball) | |
space.ball = ball_body | |
return space | |
def create_ur_objects(space, screen): | |
floor = urwid.Text(('floor', ''' | |
| | |
| | |
---+ | |
/ | |
/ | |
--- / | |
\ / | |
\ / | |
\ / | |
-------------------''')) | |
ball = urwid.Text(('ball', 'o')) | |
return urwid.Overlay(ball, urwid.Filler(floor, valign='bottom'), | |
('fixed left', int(space.ball.position.x)), 1, | |
('fixed top', int(screen.get_cols_rows()[1] - space.ball.position.y)), None, | |
) | |
def main(): | |
pm.init_pymunk() | |
space = pm.Space() | |
space.gravity = (0.0, -9.81) | |
create_pm_objects(space) | |
screen = urwid.raw_display.Screen() | |
olay = create_ur_objects(space, screen) | |
palette = [ | |
('ball', 'light red', ''), | |
('floor', 'brown', ''), | |
] | |
loop = urwid.MainLoop(olay, screen=screen, palette=palette) | |
loop.space = space | |
loop.set_alarm_in(0.1, update) | |
loop.run() | |
if __name__ == '__main__': | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
print('moved to https://bitbucket.org/livibetter/urtimer') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# | |
# Copyright (C) 2011 by Yu-Jie Lin | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy | |
# of this software and associated documentation files (the "Software"), to deal | |
# in the Software without restriction, including without limitation the rights | |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
# copies of the Software, and to permit persons to whom the Software is | |
# furnished to do so, subject to the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included in | |
# all copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
# THE SOFTWARE. | |
import sys | |
import urwid | |
class Board(object): | |
players = ('X', 'O') | |
class MarkFont1(urwid.Font): | |
height = 5 | |
data = [u""" | |
OOOOOOOOOOXXXXXXXXXX | |
****** ** ** | |
** ** ** ** | |
** ** ** | |
** ** ** ** | |
****** ** ** | |
"""] | |
class MarkFont2(urwid.Font): | |
height = 5 | |
data = [u""" | |
OOOOOOOOOOXXXXXXXXXX | |
▄██████▄ ██ ██ | |
██ ██ ██ ██ | |
██ ██ ██ | |
██ ██ ██ ██ | |
▀██████▀ ██ ██ | |
"""] | |
class Cell(urwid.BigText): | |
_selectable = True | |
signals = ['place'] | |
def keypress(self, size, key): | |
if key == ' ' and self.get_text()[0] == ' ': | |
self._emit('place') | |
else: | |
return key | |
def mouse_event(self, size, event, button, col, row, focus): | |
if event == 'mouse press' and button == 1 and self.get_text()[0] == ' ': | |
self._emit('place') | |
return True | |
def __init__(self, size=None, winning_pieces=3, font=None): | |
if isinstance(size, int): | |
size = (size, size) | |
elif size is None or not isinstance(size, tuple) or len(size) != 2: | |
size = (3, 3) | |
self.size = size | |
self.winning_pieces = winning_pieces | |
self.font = font if font is not None else Board.MarkFont2() | |
self.reset() | |
def reset(self): | |
self.ended = False | |
w, h = self.size | |
self.marks = ['']*(w*h) | |
self.player = 0 | |
if self.winning_pieces > max(w, h): | |
self.winning_pieces = max(w, h) | |
cells = [] | |
for i in range(w * h): | |
cell = Board.Cell(' ', self.font) | |
urwid.connect_signal(cell, 'place', self.place) | |
cell = urwid.Padding(cell, align='center', width='clip') | |
cell = urwid.AttrMap(cell, 'normal', 'select') | |
cells.append(cell) | |
self.cells = cells | |
char_width = max(self.font.char_width(char) for char in Board.players) | |
self._grid = urwid.GridFlow(cells, cell_width=char_width, h_sep=2, v_sep=1, align='center') | |
self._grid.set_focus(w / 2 + (h / 2) * w) | |
self.grid = urwid.Padding(self._grid, align='center', width=w*char_width + self._grid.h_sep*(w-1)) | |
def place(self, w): | |
if self.ended: | |
return | |
for cell in self.cells: | |
if cell.base_widget is w: | |
break | |
index = self.cells.index(cell) | |
if self.marks[index]: | |
return | |
mark = Board.players[self.player] | |
self.marks[index] = mark | |
cell.base_widget.set_text(mark) | |
if self.check_win(index): | |
return | |
self.player += 1 | |
if self.player >= len(Board.players): | |
self.player = 0 | |
urwid.emit_signal(self, 'player_change') | |
def i_xy(self, index): | |
return index % self.size[0], index / self.size[0] | |
def xy_i(self, x, y): | |
return y * self.size[0] + x | |
def count_pieces(self, x, y, inc_x, inc_y, mark=False): | |
count = 0 | |
p = self.marks[self.xy_i(x, y)] | |
while self.marks[self.xy_i(x, y)] == p: | |
if mark: | |
self.cells[self.xy_i(x, y)].set_attr_map({None: 'win'}) | |
self.cells[self.xy_i(x, y)].set_focus_map({None: 'select win'}) | |
x += inc_x | |
y += inc_y | |
count += 1 | |
if x >= self.size[0] or y >= self.size[1]: | |
break | |
return count | |
def _check_win(self, ix, iy, chk_X, chk_Y): | |
ip = self.marks[self.xy_i(ix, iy)] | |
x, y = ix, iy | |
while (not chk_X or x >= 0) and (not chk_Y or (y >= 0 and y < self.size[1])): | |
if self.marks[self.xy_i(x, y)] != ip: | |
x += 1 if chk_X else 0 | |
y += 1 if chk_Y is True else (0 if chk_Y is not -1 else -1) | |
break | |
if (not chk_X or x == 0) or (chk_Y is True and y == 0) or (chk_Y is -1 and y == self.size[1] - 1): | |
break | |
x -= 1 if chk_X else 0 | |
y -= 1 if chk_Y is True else (0 if chk_Y is not -1 else -1) | |
if self.count_pieces(x, y, 1 if chk_X else 0, 1 if chk_Y is True else (0 if chk_Y is not -1 else -1)) >= self.winning_pieces: | |
self.ended = True | |
self.count_pieces(x, y, 1 if chk_X else 0, 1 if chk_Y is True else (0 if chk_Y is not -1 else -1), True) | |
return True | |
def check_win(self, index): | |
ip = self.marks[index] | |
ix, iy = self.i_xy(index) | |
if self._check_win(ix, iy, True, False) or \ | |
self._check_win(ix, iy, False, True) or \ | |
self._check_win(ix, iy, True, True) or \ | |
self._check_win(ix, iy, True, -1): | |
urwid.emit_signal(self, 'game_ended') | |
return True | |
if len(filter(None, self.marks)) == len(self.marks): | |
self.ended = -1 | |
urwid.emit_signal(self, 'game_ended') | |
return True | |
urwid.register_signal(Board, ['player_change', 'game_ended']) | |
class Game(object): | |
palette = [ | |
('normal', 'light blue', 'dark gray'), | |
('select', 'light blue', 'dark green'), | |
('win', 'light red', 'dark gray'), | |
('select win', 'light red', 'dark green'), | |
('status bar', 'white', 'dark blue'), | |
('status bar player', 'light red', 'dark blue'), | |
('keyhint bar', 'white', 'dark blue'), | |
('key', 'light blue', 'white'), | |
] | |
def update_footer(self): | |
def _get_keyhint_text(keys): | |
return [ | |
_item | |
for _tuple in ((('key', ' %s ' % key), ' %s ' % desc) for key, desc in keys) | |
for _item in _tuple | |
] | |
if self.board.ended: | |
if self.board.ended == -1: | |
self.status.set_text("Draw!") | |
else: | |
self.status.set_text("Player %s won!" % self.board.players[self.board.player]) | |
self.keyhint.set_text(_get_keyhint_text(( | |
('Arrow keys', 'Move cursor'), | |
('w/W', 'Width'), | |
('h/H', 'Height'), | |
('-/+', 'Pieces'), | |
('R/Right Button', 'Restart'), | |
('Q', 'Quit'), | |
)) | |
) | |
else: | |
self.status.set_text([ | |
'%d pieces to win. ' % self.board.winning_pieces, | |
('status bar player', '%s' % self.board.players[self.board.player]), | |
" player's turn..." | |
]) | |
self.keyhint.set_text(_get_keyhint_text(( | |
('Arrow keys', 'Move cursor'), | |
('Space/Left Button', 'Place'), | |
('w/W', 'Width'), | |
('h/H', 'Height'), | |
('-/+', 'Pieces'), | |
('R/Right Button', 'Restart'), | |
('Q', 'Quit'), | |
)) | |
) | |
def unhandled_input(self, key): | |
if key in ('q', 'Q', 'esc'): | |
raise urwid.ExitMainLoop | |
if key in ('r', 'R') or (urwid.is_mouse_event(key) and key[1] == 3): | |
pass | |
elif key in ('w', 'W', 'h', 'H'): | |
w, h = self.board.size | |
if key in ('w', 'W'): | |
w += -1 if key == 'w' else 1 | |
else: | |
h += -1 if key == 'h' else 1 | |
w = max(1, w) | |
h = max(1, h) | |
self.board.size = (w, h) | |
elif key in ('-', '+'): | |
self.board.winning_pieces += -1 if key == '-' else 1 | |
self.board.winning_pieces = max(1, self.board.winning_pieces) | |
else: | |
return | |
self.board.reset() | |
self.board_filler.set_body(self.board.grid) | |
self.update_footer() | |
def run(self): | |
self.board = Board(size=(3, 3)) | |
urwid.connect_signal(self.board, 'player_change', self.update_footer) | |
urwid.connect_signal(self.board, 'game_ended', self.update_footer) | |
self.board_filler = urwid.Filler(self.board.grid) | |
self.keyhint = urwid.Text('') | |
self.status = urwid.Text('') | |
self.footer = urwid.Pile([urwid.AttrMap(self.status, 'status bar'), | |
urwid.AttrMap(self.keyhint, 'keyhint bar')]) | |
self.update_footer() | |
self.loop = urwid.MainLoop(urwid.Frame(self.board_filler, | |
footer=self.footer), Game.palette, unhandled_input=self.unhandled_input) | |
self.loop.run() | |
def main(): | |
try: | |
Game().run() | |
except KeyboardInterrupt: | |
pass | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Related blog post and screenshots.