/Demo/tkinter/guido/solitaire.py

http://unladen-swallow.googlecode.com/ · Python · 637 lines · 575 code · 22 blank · 40 comment · 18 complexity · b1e05b02ef721cb0af3e301688a2702f MD5 · raw file

  1. #! /usr/bin/env python
  2. """Solitaire game, much like the one that comes with MS Windows.
  3. Limitations:
  4. - No cute graphical images for the playing cards faces or backs.
  5. - No scoring or timer.
  6. - No undo.
  7. - No option to turn 3 cards at a time.
  8. - No keyboard shortcuts.
  9. - Less fancy animation when you win.
  10. - The determination of which stack you drag to is more relaxed.
  11. Apology:
  12. I'm not much of a card player, so my terminology in these comments may
  13. at times be a little unusual. If you have suggestions, please let me
  14. know!
  15. """
  16. # Imports
  17. import math
  18. import random
  19. from Tkinter import *
  20. from Canvas import Rectangle, CanvasText, Group, Window
  21. # Fix a bug in Canvas.Group as distributed in Python 1.4. The
  22. # distributed bind() method is broken. Rather than asking you to fix
  23. # the source, we fix it here by deriving a subclass:
  24. class Group(Group):
  25. def bind(self, sequence=None, command=None):
  26. return self.canvas.tag_bind(self.id, sequence, command)
  27. # Constants determining the size and lay-out of cards and stacks. We
  28. # work in a "grid" where each card/stack is surrounded by MARGIN
  29. # pixels of space on each side, so adjacent stacks are separated by
  30. # 2*MARGIN pixels. OFFSET is the offset used for displaying the
  31. # face down cards in the row stacks.
  32. CARDWIDTH = 100
  33. CARDHEIGHT = 150
  34. MARGIN = 10
  35. XSPACING = CARDWIDTH + 2*MARGIN
  36. YSPACING = CARDHEIGHT + 4*MARGIN
  37. OFFSET = 5
  38. # The background color, green to look like a playing table. The
  39. # standard green is way too bright, and dark green is way to dark, so
  40. # we use something in between. (There are a few more colors that
  41. # could be customized, but they are less controversial.)
  42. BACKGROUND = '#070'
  43. # Suits and colors. The values of the symbolic suit names are the
  44. # strings used to display them (you change these and VALNAMES to
  45. # internationalize the game). The COLOR dictionary maps suit names to
  46. # colors (red and black) which must be Tk color names. The keys() of
  47. # the COLOR dictionary conveniently provides us with a list of all
  48. # suits (in arbitrary order).
  49. HEARTS = 'Heart'
  50. DIAMONDS = 'Diamond'
  51. CLUBS = 'Club'
  52. SPADES = 'Spade'
  53. RED = 'red'
  54. BLACK = 'black'
  55. COLOR = {}
  56. for s in (HEARTS, DIAMONDS):
  57. COLOR[s] = RED
  58. for s in (CLUBS, SPADES):
  59. COLOR[s] = BLACK
  60. ALLSUITS = COLOR.keys()
  61. NSUITS = len(ALLSUITS)
  62. # Card values are 1-13. We also define symbolic names for the picture
  63. # cards. ALLVALUES is a list of all card values.
  64. ACE = 1
  65. JACK = 11
  66. QUEEN = 12
  67. KING = 13
  68. ALLVALUES = range(1, 14) # (one more than the highest value)
  69. NVALUES = len(ALLVALUES)
  70. # VALNAMES is a list that maps a card value to string. It contains a
  71. # dummy element at index 0 so it can be indexed directly with the card
  72. # value.
  73. VALNAMES = ["", "A"] + map(str, range(2, 11)) + ["J", "Q", "K"]
  74. # Solitaire constants. The only one I can think of is the number of
  75. # row stacks.
  76. NROWS = 7
  77. # The rest of the program consists of class definitions. These are
  78. # further described in their documentation strings.
  79. class Card:
  80. """A playing card.
  81. A card doesn't record to which stack it belongs; only the stack
  82. records this (it turns out that we always know this from the
  83. context, and this saves a ``double update'' with potential for
  84. inconsistencies).
  85. Public methods:
  86. moveto(x, y) -- move the card to an absolute position
  87. moveby(dx, dy) -- move the card by a relative offset
  88. tkraise() -- raise the card to the top of its stack
  89. showface(), showback() -- turn the card face up or down & raise it
  90. Public read-only instance variables:
  91. suit, value, color -- the card's suit, value and color
  92. face_shown -- true when the card is shown face up, else false
  93. Semi-public read-only instance variables (XXX should be made
  94. private):
  95. group -- the Canvas.Group representing the card
  96. x, y -- the position of the card's top left corner
  97. Private instance variables:
  98. __back, __rect, __text -- the canvas items making up the card
  99. (To show the card face up, the text item is placed in front of
  100. rect and the back is placed behind it. To show it face down, this
  101. is reversed. The card is created face down.)
  102. """
  103. def __init__(self, suit, value, canvas):
  104. """Card constructor.
  105. Arguments are the card's suit and value, and the canvas widget.
  106. The card is created at position (0, 0), with its face down
  107. (adding it to a stack will position it according to that
  108. stack's rules).
  109. """
  110. self.suit = suit
  111. self.value = value
  112. self.color = COLOR[suit]
  113. self.face_shown = 0
  114. self.x = self.y = 0
  115. self.group = Group(canvas)
  116. text = "%s %s" % (VALNAMES[value], suit)
  117. self.__text = CanvasText(canvas, CARDWIDTH//2, 0,
  118. anchor=N, fill=self.color, text=text)
  119. self.group.addtag_withtag(self.__text)
  120. self.__rect = Rectangle(canvas, 0, 0, CARDWIDTH, CARDHEIGHT,
  121. outline='black', fill='white')
  122. self.group.addtag_withtag(self.__rect)
  123. self.__back = Rectangle(canvas, MARGIN, MARGIN,
  124. CARDWIDTH-MARGIN, CARDHEIGHT-MARGIN,
  125. outline='black', fill='blue')
  126. self.group.addtag_withtag(self.__back)
  127. def __repr__(self):
  128. """Return a string for debug print statements."""
  129. return "Card(%r, %r)" % (self.suit, self.value)
  130. def moveto(self, x, y):
  131. """Move the card to absolute position (x, y)."""
  132. self.moveby(x - self.x, y - self.y)
  133. def moveby(self, dx, dy):
  134. """Move the card by (dx, dy)."""
  135. self.x = self.x + dx
  136. self.y = self.y + dy
  137. self.group.move(dx, dy)
  138. def tkraise(self):
  139. """Raise the card above all other objects in its canvas."""
  140. self.group.tkraise()
  141. def showface(self):
  142. """Turn the card's face up."""
  143. self.tkraise()
  144. self.__rect.tkraise()
  145. self.__text.tkraise()
  146. self.face_shown = 1
  147. def showback(self):
  148. """Turn the card's face down."""
  149. self.tkraise()
  150. self.__rect.tkraise()
  151. self.__back.tkraise()
  152. self.face_shown = 0
  153. class Stack:
  154. """A generic stack of cards.
  155. This is used as a base class for all other stacks (e.g. the deck,
  156. the suit stacks, and the row stacks).
  157. Public methods:
  158. add(card) -- add a card to the stack
  159. delete(card) -- delete a card from the stack
  160. showtop() -- show the top card (if any) face up
  161. deal() -- delete and return the top card, or None if empty
  162. Method that subclasses may override:
  163. position(card) -- move the card to its proper (x, y) position
  164. The default position() method places all cards at the stack's
  165. own (x, y) position.
  166. userclickhandler(), userdoubleclickhandler() -- called to do
  167. subclass specific things on single and double clicks
  168. The default user (single) click handler shows the top card
  169. face up. The default user double click handler calls the user
  170. single click handler.
  171. usermovehandler(cards) -- called to complete a subpile move
  172. The default user move handler moves all moved cards back to
  173. their original position (by calling the position() method).
  174. Private methods:
  175. clickhandler(event), doubleclickhandler(event),
  176. motionhandler(event), releasehandler(event) -- event handlers
  177. The default event handlers turn the top card of the stack with
  178. its face up on a (single or double) click, and also support
  179. moving a subpile around.
  180. startmoving(event) -- begin a move operation
  181. finishmoving() -- finish a move operation
  182. """
  183. def __init__(self, x, y, game=None):
  184. """Stack constructor.
  185. Arguments are the stack's nominal x and y position (the top
  186. left corner of the first card placed in the stack), and the
  187. game object (which is used to get the canvas; subclasses use
  188. the game object to find other stacks).
  189. """
  190. self.x = x
  191. self.y = y
  192. self.game = game
  193. self.cards = []
  194. self.group = Group(self.game.canvas)
  195. self.group.bind('<1>', self.clickhandler)
  196. self.group.bind('<Double-1>', self.doubleclickhandler)
  197. self.group.bind('<B1-Motion>', self.motionhandler)
  198. self.group.bind('<ButtonRelease-1>', self.releasehandler)
  199. self.makebottom()
  200. def makebottom(self):
  201. pass
  202. def __repr__(self):
  203. """Return a string for debug print statements."""
  204. return "%s(%d, %d)" % (self.__class__.__name__, self.x, self.y)
  205. # Public methods
  206. def add(self, card):
  207. self.cards.append(card)
  208. card.tkraise()
  209. self.position(card)
  210. self.group.addtag_withtag(card.group)
  211. def delete(self, card):
  212. self.cards.remove(card)
  213. card.group.dtag(self.group)
  214. def showtop(self):
  215. if self.cards:
  216. self.cards[-1].showface()
  217. def deal(self):
  218. if not self.cards:
  219. return None
  220. card = self.cards[-1]
  221. self.delete(card)
  222. return card
  223. # Subclass overridable methods
  224. def position(self, card):
  225. card.moveto(self.x, self.y)
  226. def userclickhandler(self):
  227. self.showtop()
  228. def userdoubleclickhandler(self):
  229. self.userclickhandler()
  230. def usermovehandler(self, cards):
  231. for card in cards:
  232. self.position(card)
  233. # Event handlers
  234. def clickhandler(self, event):
  235. self.finishmoving() # In case we lost an event
  236. self.userclickhandler()
  237. self.startmoving(event)
  238. def motionhandler(self, event):
  239. self.keepmoving(event)
  240. def releasehandler(self, event):
  241. self.keepmoving(event)
  242. self.finishmoving()
  243. def doubleclickhandler(self, event):
  244. self.finishmoving() # In case we lost an event
  245. self.userdoubleclickhandler()
  246. self.startmoving(event)
  247. # Move internals
  248. moving = None
  249. def startmoving(self, event):
  250. self.moving = None
  251. tags = self.game.canvas.gettags('current')
  252. for i in range(len(self.cards)):
  253. card = self.cards[i]
  254. if card.group.tag in tags:
  255. break
  256. else:
  257. return
  258. if not card.face_shown:
  259. return
  260. self.moving = self.cards[i:]
  261. self.lastx = event.x
  262. self.lasty = event.y
  263. for card in self.moving:
  264. card.tkraise()
  265. def keepmoving(self, event):
  266. if not self.moving:
  267. return
  268. dx = event.x - self.lastx
  269. dy = event.y - self.lasty
  270. self.lastx = event.x
  271. self.lasty = event.y
  272. if dx or dy:
  273. for card in self.moving:
  274. card.moveby(dx, dy)
  275. def finishmoving(self):
  276. cards = self.moving
  277. self.moving = None
  278. if cards:
  279. self.usermovehandler(cards)
  280. class Deck(Stack):
  281. """The deck is a stack with support for shuffling.
  282. New methods:
  283. fill() -- create the playing cards
  284. shuffle() -- shuffle the playing cards
  285. A single click moves the top card to the game's open deck and
  286. moves it face up; if we're out of cards, it moves the open deck
  287. back to the deck.
  288. """
  289. def makebottom(self):
  290. bottom = Rectangle(self.game.canvas,
  291. self.x, self.y,
  292. self.x+CARDWIDTH, self.y+CARDHEIGHT,
  293. outline='black', fill=BACKGROUND)
  294. self.group.addtag_withtag(bottom)
  295. def fill(self):
  296. for suit in ALLSUITS:
  297. for value in ALLVALUES:
  298. self.add(Card(suit, value, self.game.canvas))
  299. def shuffle(self):
  300. n = len(self.cards)
  301. newcards = []
  302. for i in randperm(n):
  303. newcards.append(self.cards[i])
  304. self.cards = newcards
  305. def userclickhandler(self):
  306. opendeck = self.game.opendeck
  307. card = self.deal()
  308. if not card:
  309. while 1:
  310. card = opendeck.deal()
  311. if not card:
  312. break
  313. self.add(card)
  314. card.showback()
  315. else:
  316. self.game.opendeck.add(card)
  317. card.showface()
  318. def randperm(n):
  319. """Function returning a random permutation of range(n)."""
  320. r = range(n)
  321. x = []
  322. while r:
  323. i = random.choice(r)
  324. x.append(i)
  325. r.remove(i)
  326. return x
  327. class OpenStack(Stack):
  328. def acceptable(self, cards):
  329. return 0
  330. def usermovehandler(self, cards):
  331. card = cards[0]
  332. stack = self.game.closeststack(card)
  333. if not stack or stack is self or not stack.acceptable(cards):
  334. Stack.usermovehandler(self, cards)
  335. else:
  336. for card in cards:
  337. self.delete(card)
  338. stack.add(card)
  339. self.game.wincheck()
  340. def userdoubleclickhandler(self):
  341. if not self.cards:
  342. return
  343. card = self.cards[-1]
  344. if not card.face_shown:
  345. self.userclickhandler()
  346. return
  347. for s in self.game.suits:
  348. if s.acceptable([card]):
  349. self.delete(card)
  350. s.add(card)
  351. self.game.wincheck()
  352. break
  353. class SuitStack(OpenStack):
  354. def makebottom(self):
  355. bottom = Rectangle(self.game.canvas,
  356. self.x, self.y,
  357. self.x+CARDWIDTH, self.y+CARDHEIGHT,
  358. outline='black', fill='')
  359. def userclickhandler(self):
  360. pass
  361. def userdoubleclickhandler(self):
  362. pass
  363. def acceptable(self, cards):
  364. if len(cards) != 1:
  365. return 0
  366. card = cards[0]
  367. if not self.cards:
  368. return card.value == ACE
  369. topcard = self.cards[-1]
  370. return card.suit == topcard.suit and card.value == topcard.value + 1
  371. class RowStack(OpenStack):
  372. def acceptable(self, cards):
  373. card = cards[0]
  374. if not self.cards:
  375. return card.value == KING
  376. topcard = self.cards[-1]
  377. if not topcard.face_shown:
  378. return 0
  379. return card.color != topcard.color and card.value == topcard.value - 1
  380. def position(self, card):
  381. y = self.y
  382. for c in self.cards:
  383. if c == card:
  384. break
  385. if c.face_shown:
  386. y = y + 2*MARGIN
  387. else:
  388. y = y + OFFSET
  389. card.moveto(self.x, y)
  390. class Solitaire:
  391. def __init__(self, master):
  392. self.master = master
  393. self.canvas = Canvas(self.master,
  394. background=BACKGROUND,
  395. highlightthickness=0,
  396. width=NROWS*XSPACING,
  397. height=3*YSPACING + 20 + MARGIN)
  398. self.canvas.pack(fill=BOTH, expand=TRUE)
  399. self.dealbutton = Button(self.canvas,
  400. text="Deal",
  401. highlightthickness=0,
  402. background=BACKGROUND,
  403. activebackground="green",
  404. command=self.deal)
  405. Window(self.canvas, MARGIN, 3*YSPACING + 20,
  406. window=self.dealbutton, anchor=SW)
  407. x = MARGIN
  408. y = MARGIN
  409. self.deck = Deck(x, y, self)
  410. x = x + XSPACING
  411. self.opendeck = OpenStack(x, y, self)
  412. x = x + XSPACING
  413. self.suits = []
  414. for i in range(NSUITS):
  415. x = x + XSPACING
  416. self.suits.append(SuitStack(x, y, self))
  417. x = MARGIN
  418. y = y + YSPACING
  419. self.rows = []
  420. for i in range(NROWS):
  421. self.rows.append(RowStack(x, y, self))
  422. x = x + XSPACING
  423. self.openstacks = [self.opendeck] + self.suits + self.rows
  424. self.deck.fill()
  425. self.deal()
  426. def wincheck(self):
  427. for s in self.suits:
  428. if len(s.cards) != NVALUES:
  429. return
  430. self.win()
  431. self.deal()
  432. def win(self):
  433. """Stupid animation when you win."""
  434. cards = []
  435. for s in self.openstacks:
  436. cards = cards + s.cards
  437. while cards:
  438. card = random.choice(cards)
  439. cards.remove(card)
  440. self.animatedmoveto(card, self.deck)
  441. def animatedmoveto(self, card, dest):
  442. for i in range(10, 0, -1):
  443. dx, dy = (dest.x-card.x)//i, (dest.y-card.y)//i
  444. card.moveby(dx, dy)
  445. self.master.update_idletasks()
  446. def closeststack(self, card):
  447. closest = None
  448. cdist = 999999999
  449. # Since we only compare distances,
  450. # we don't bother to take the square root.
  451. for stack in self.openstacks:
  452. dist = (stack.x - card.x)**2 + (stack.y - card.y)**2
  453. if dist < cdist:
  454. closest = stack
  455. cdist = dist
  456. return closest
  457. def deal(self):
  458. self.reset()
  459. self.deck.shuffle()
  460. for i in range(NROWS):
  461. for r in self.rows[i:]:
  462. card = self.deck.deal()
  463. r.add(card)
  464. for r in self.rows:
  465. r.showtop()
  466. def reset(self):
  467. for stack in self.openstacks:
  468. while 1:
  469. card = stack.deal()
  470. if not card:
  471. break
  472. self.deck.add(card)
  473. card.showback()
  474. # Main function, run when invoked as a stand-alone Python program.
  475. def main():
  476. root = Tk()
  477. game = Solitaire(root)
  478. root.protocol('WM_DELETE_WINDOW', root.quit)
  479. root.mainloop()
  480. if __name__ == '__main__':
  481. main()