Debian Codegraph @

examples/memory/memory.py

raw symbols SCIP
1 #
2 # TODO: Add sound effects
3 # Ignore clicks after displaying second card until
4 # either hit or miss is reported.
5 # Consider re-casting the data structure as a dict
6 # with two-element tuple keys.
7 # Configure window size according to COLS and ROWS
8 #
9
10 checkmark = Actor('checkmark')
11 steve = Actor('card_back', (50, 50))
12 steve.topleft = (0, 0)
13
14 import random
15 import time
16
17 COLS = 4
18 ROWS= 3
19 IMSIZE = 200
20 STATUS = [] # cells that have been clicked on
21 ignore = [] # cells that have been matches and are no longer in play
22
23 # Create two of each card image, then randomize before creating the board
24 START_IMAGES= [ "im"+str(i+1) for i in range(COLS*ROWS//2)]*2
25 random.shuffle(START_IMAGES)
26
27 STATUS=[]
28
29 board = [] # initialize the board
30 for row in range(ROWS):
31 new_row=[]
32 for col in range(COLS):
33 image_name = START_IMAGES.pop()
34 temp=Actor(image_name, (col*IMSIZE, row*IMSIZE))
35 temp.image_name = image_name # used to verify matches
36 temp.topleft=(col*IMSIZE, row*IMSIZE)
37 new_row.append(temp)
38 board.append(new_row)
39
40 def draw(): # draw the board when pygame-zero says to
41 screen.clear()
42 for row in range(ROWS):
43 for col in range(COLS):
44 if (row, col) in ignore: # already matched
45 checkmark.topleft = IMSIZE*col, IMSIZE*row
46 checkmark.draw()
47 elif (row, col) in STATUS: # clicked this move: show face
48 board[row][col].draw()
49 else: # regular clickable card
50 steve.topleft = IMSIZE*col, IMSIZE*row
51 steve.draw()
52
53 def findTile(pos):
54 y, x = pos
55 result = x // IMSIZE , y // IMSIZE
56 return result
57
58 def showTile():
59 pass
60
61
62 def on_mouse_down(pos, button):
63 if len(STATUS) == 2: # ignore until timeout redisplays
64 return
65 if pos in ignore: # has already been matched
66 return
67 if button == mouse.LEFT and (pos):
68 # not sure why "and (pos)" - especially the parens!
69 coords = findTile(pos)
70 if coords not in STATUS:
71 STATUS.append(coords) # now they are
72 if len(STATUS) == 1: # 1st click - turn not yet over
73 pass
74 elif len(STATUS) == 2: # 2nd click - check for match
75 (x1, y1), (x2, y2) = STATUS # an "unpacking assignment"
76 if board[x1][y1].image_name == board[x2][y2].image_name:
77 print("Success sound")
78 # add cards to list of non-clickable positions
79 for pos in STATUS:
80 ignore.append(pos)
81 else:
82 print("Failure sound")
83 clock.schedule_unique(next_turn, 2.0)
84
85 def next_turn():
86 del STATUS[:]
87