Guest User

Untitled

a guest
Feb 18th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.66 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (C) 2011 by Yu-Jie Lin
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in
  14. # all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. # THE SOFTWARE.
  23.  
  24.  
  25. import sys
  26.  
  27. import urwid
  28.  
  29.  
  30. class Board(object):
  31.  
  32. players = ('X', 'O')
  33.  
  34. class MarkFont1(urwid.Font):
  35. height = 5
  36. data = [u"""
  37. OOOOOOOOOOXXXXXXXXXX
  38. ****** ** **
  39. ** ** ** **
  40. ** ** **
  41. ** ** ** **
  42. ****** ** **
  43. """]
  44.  
  45. class MarkFont2(urwid.Font):
  46. height = 5
  47. data = [u"""
  48. OOOOOOOOOOXXXXXXXXXX
  49. ▄██████▄ ██ ██
  50. ██ ██ ██ ██
  51. ██ ██ ██
  52. ██ ██ ██ ██
  53. ▀██████▀ ██ ██
  54. """]
  55.  
  56. class Cell(urwid.BigText):
  57.  
  58. _selectable = True
  59. signals = ['place']
  60.  
  61. def keypress(self, size, key):
  62.  
  63. if key == ' ' and self.get_text()[0] == ' ':
  64. self._emit('place')
  65. else:
  66. return key
  67.  
  68. def mouse_event(self, size, event, button, col, row, focus):
  69.  
  70. if event == 'mouse press' and button == 1 and self.get_text()[0] == ' ':
  71. self._emit('place')
  72. return True
  73.  
  74. def __init__(self, size=None, winning_pieces=3, font=None):
  75.  
  76. if isinstance(size, int):
  77. size = (size, size)
  78. elif size is None or not isinstance(size, tuple) or len(size) != 2:
  79. size = (3, 3)
  80. self.size = size
  81. self.winning_pieces = winning_pieces
  82. self.font = font if font is not None else Board.MarkFont2()
  83. self.reset()
  84.  
  85. def reset(self):
  86.  
  87. self.ended = False
  88. w, h = self.size
  89. self.marks = ['']*(w*h)
  90. self.player = 0
  91. if self.winning_pieces > max(w, h):
  92. self.winning_pieces = max(w, h)
  93.  
  94. cells = []
  95. for i in range(w * h):
  96. cell = Board.Cell(' ', self.font)
  97. urwid.connect_signal(cell, 'place', self.place)
  98.  
  99. cell = urwid.Padding(cell, align='center', width='clip')
  100. cell = urwid.AttrMap(cell, 'normal', 'select')
  101. cells.append(cell)
  102. self.cells = cells
  103.  
  104. char_width = max(self.font.char_width(char) for char in Board.players)
  105. self._grid = urwid.GridFlow(cells, cell_width=char_width, h_sep=2, v_sep=1, align='center')
  106. self._grid.set_focus(w / 2 + (h / 2) * w)
  107. self.grid = urwid.Padding(self._grid, align='center', width=w*char_width + self._grid.h_sep*(w-1))
  108.  
  109. def place(self, w):
  110.  
  111. if self.ended:
  112. return
  113. for cell in self.cells:
  114. if cell.base_widget is w:
  115. break
  116. index = self.cells.index(cell)
  117. if self.marks[index]:
  118. return
  119.  
  120. mark = Board.players[self.player]
  121. self.marks[index] = mark
  122. cell.base_widget.set_text(mark)
  123. if self.check_win(index):
  124. return
  125.  
  126. self.player += 1
  127. if self.player >= len(Board.players):
  128. self.player = 0
  129. urwid.emit_signal(self, 'player_change')
  130.  
  131. def i_xy(self, index):
  132.  
  133. return index % self.size[0], index / self.size[0]
  134.  
  135. def xy_i(self, x, y):
  136.  
  137. return y * self.size[0] + x
  138.  
  139. def count_pieces(self, x, y, inc_x, inc_y, mark=False):
  140.  
  141. count = 0
  142. p = self.marks[self.xy_i(x, y)]
  143. while self.marks[self.xy_i(x, y)] == p:
  144. if mark:
  145. self.cells[self.xy_i(x, y)].set_attr_map({None: 'win'})
  146. self.cells[self.xy_i(x, y)].set_focus_map({None: 'select win'})
  147. x += inc_x
  148. y += inc_y
  149. count += 1
  150. if x >= self.size[0] or y >= self.size[1]:
  151. break
  152. return count
  153.  
  154. def _check_win(self, ix, iy, chk_X, chk_Y):
  155.  
  156. ip = self.marks[self.xy_i(ix, iy)]
  157. x, y = ix, iy
  158. while (not chk_X or x >= 0) and (not chk_Y or (y >= 0 and y < self.size[1])):
  159. if self.marks[self.xy_i(x, y)] != ip:
  160. x += 1 if chk_X else 0
  161. y += 1 if chk_Y is True else (0 if chk_Y is not -1 else -1)
  162. break
  163. 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):
  164. break
  165. x -= 1 if chk_X else 0
  166. y -= 1 if chk_Y is True else (0 if chk_Y is not -1 else -1)
  167. 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:
  168. self.ended = True
  169. 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)
  170. return True
  171.  
  172. def check_win(self, index):
  173.  
  174. ip = self.marks[index]
  175. ix, iy = self.i_xy(index)
  176.  
  177. if self._check_win(ix, iy, True, False) or \
  178. self._check_win(ix, iy, False, True) or \
  179. self._check_win(ix, iy, True, True) or \
  180. self._check_win(ix, iy, True, -1):
  181. urwid.emit_signal(self, 'game_ended')
  182. return True
  183.  
  184. if len(filter(None, self.marks)) == len(self.marks):
  185. self.ended = -1
  186. urwid.emit_signal(self, 'game_ended')
  187. return True
  188.  
  189.  
  190. urwid.register_signal(Board, ['player_change', 'game_ended'])
  191.  
  192.  
  193. class Game(object):
  194.  
  195. palette = [
  196. ('normal', 'light blue', 'dark gray'),
  197. ('select', 'light blue', 'dark green'),
  198. ('win', 'light red', 'dark gray'),
  199. ('select win', 'light red', 'dark green'),
  200. ('status bar', 'white', 'dark blue'),
  201. ('status bar player', 'light red', 'dark blue'),
  202. ('keyhint bar', 'white', 'dark blue'),
  203. ('key', 'light blue', 'white'),
  204. ]
  205.  
  206. def update_footer(self):
  207.  
  208. def _get_keyhint_text(keys):
  209.  
  210. return [
  211. _item
  212. for _tuple in ((('key', ' %s ' % key), ' %s ' % desc) for key, desc in keys)
  213. for _item in _tuple
  214. ]
  215.  
  216. if self.board.ended:
  217. if self.board.ended == -1:
  218. self.status.set_text("Draw!")
  219. else:
  220. self.status.set_text("Player %s won!" % self.board.players[self.board.player])
  221. self.keyhint.set_text(_get_keyhint_text((
  222. ('Arrow keys', 'Move cursor'),
  223. ('w/W', 'Width'),
  224. ('h/H', 'Height'),
  225. ('-/+', 'Pieces'),
  226. ('R/Right Button', 'Restart'),
  227. ('Q', 'Quit'),
  228. ))
  229. )
  230. else:
  231. self.status.set_text([
  232. '%d pieces to win. ' % self.board.winning_pieces,
  233. ('status bar player', '%s' % self.board.players[self.board.player]),
  234. " player's turn..."
  235. ])
  236. self.keyhint.set_text(_get_keyhint_text((
  237. ('Arrow keys', 'Move cursor'),
  238. ('Space/Left Button', 'Place'),
  239. ('w/W', 'Width'),
  240. ('h/H', 'Height'),
  241. ('-/+', 'Pieces'),
  242. ('R/Right Button', 'Restart'),
  243. ('Q', 'Quit'),
  244. ))
  245. )
  246.  
  247. def unhandled_input(self, key):
  248.  
  249. if key in ('q', 'Q', 'esc'):
  250. raise urwid.ExitMainLoop
  251.  
  252. if key in ('r', 'R') or (urwid.is_mouse_event(key) and key[1] == 3):
  253. pass
  254. elif key in ('w', 'W', 'h', 'H'):
  255. w, h = self.board.size
  256. if key in ('w', 'W'):
  257. w += -1 if key == 'w' else 1
  258. else:
  259. h += -1 if key == 'h' else 1
  260. w = max(1, w)
  261. h = max(1, h)
  262. self.board.size = (w, h)
  263. elif key in ('-', '+'):
  264. self.board.winning_pieces += -1 if key == '-' else 1
  265. self.board.winning_pieces = max(1, self.board.winning_pieces)
  266. else:
  267. return
  268.  
  269. self.board.reset()
  270. self.board_filler.set_body(self.board.grid)
  271. self.update_footer()
  272.  
  273. def run(self):
  274.  
  275. self.board = Board(size=(3, 3))
  276. urwid.connect_signal(self.board, 'player_change', self.update_footer)
  277. urwid.connect_signal(self.board, 'game_ended', self.update_footer)
  278. self.board_filler = urwid.Filler(self.board.grid)
  279. self.keyhint = urwid.Text('')
  280. self.status = urwid.Text('')
  281. self.footer = urwid.Pile([urwid.AttrMap(self.status, 'status bar'),
  282. urwid.AttrMap(self.keyhint, 'keyhint bar')])
  283. self.update_footer()
  284.  
  285. self.loop = urwid.MainLoop(urwid.Frame(self.board_filler,
  286. footer=self.footer), Game.palette, unhandled_input=self.unhandled_input)
  287. self.loop.run()
  288.  
  289.  
  290. def main():
  291.  
  292. try:
  293. Game().run()
  294. except KeyboardInterrupt:
  295. pass
  296.  
  297.  
  298. if __name__ == '__main__':
  299. main()
Add Comment
Please, Sign In to add comment