Friday, August 2, 2013

Memory with Python (for codeskulptor)

1:  import simplegui  
2:  import random  
3:    
4:    
5:    
6:  # helper function to initialize globals  
7:  def init():  
8:    global lst1, lst2, deck, exposed, state, flipt1, flipt2, moves  
9:    moves = 0  
10:    flipt1 = -1  
11:    flipt2 = -2  
12:    state = 0  
13:    exposed = [False]*16  
14:    lst1 = range(8)  
15:    lst2 = range(8)  
16:    random.shuffle(lst1)  
17:    random.shuffle(lst2)  
18:    deck = lst1 + lst2  
19:    random.shuffle(deck)  
20:    pass   
21:    
22:       
23:  # define event handlers  
24:  def mouseclick(pos):  
25:    global moves, exposed, state, deck, flipt1, flipt2  
26:    a = 0  
27:    b = 0  
28:    # add game state logic here  
29:    moves += 1  
30:    num = pos[0] // 50  
31:    if exposed[num] == False:  
32:      if state == 0:  
33:        exposed[num] = True  
34:        state = 1  
35:        flipt1 = num  
36:          
37:      elif state == 1:  
38:        exposed[num] = True  
39:        state = 2  
40:        flipt2 = num  
41:          
42:      else:  
43:        state = 1  
44:        if deck[flipt1] != deck[flipt2]:  
45:          exposed[flipt1] = False  
46:          exposed[flipt2] = False  
47:        exposed[num] = True  
48:        flipt1 = num  
49:        flipt2 = -2  
50:          
51:      print num, exposed[num], state, flipt1, flipt2, moves  
52:    pass  
53:      
54:                
55:  # cards are logically 50x100 pixels in size    
56:  def draw(canvas):  
57:    spc = 0  
58:    x = 0  
59:    label.set_text("Moves =" + str(moves))  
60:    for crd in deck:  
61:      global exposed, state, flipt1, flipt2  
62:      if exposed[x] == True:  
63:        canvas.draw_text(str(crd), (spc, 80), 50, "white")  
64:          
65:      else:  
66:        canvas.draw_line((spc + 25, 0), (spc + 25, 100), 50, "Green")  
67:     
68:      x += 1  
69:      spc += 50  
70:      canvas.draw_polyline([(spc, 0), (spc, 100)], 2, "Red")  
71:    pass  
72:    
73:    
74:  # create frame and add a button and labels  
75:  frame = simplegui.create_frame("Memory", 800, 100)  
76:  frame.add_button("Restart", init)  
77:  label = frame.add_label("Moves = 0")  
78:    
79:  # initialize global variables  
80:  init()  
81:    
82:  # register event handlers  
83:  frame.set_mouseclick_handler(mouseclick)  
84:  frame.set_draw_handler(draw)  
85:    
86:  # get things rolling  
87:  frame.start()  
88:    
89:    

No comments:

Post a Comment

Linguistics and Information Theory