Coursera_An Introduction to Interactive Programming in Python_Mini-project # 5 Memory

来源:互联网 发布:直接购买已备案域名 编辑:程序博客网 时间:2024/06/07 18:24

http://www.codeskulptor.org/#user38_6vsNKw1hBx_9.py


# implementation of card game - Memoryimport simpleguiimport randomcard_list = []click_index=[] # record the index of first two mouse clickstate = 0counter = 0# To indicate the draw handler to either draw a blank green rectangle or the card's value# True means card is face up# False means card is face downexposed = [False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False] # helper function to initialize globalsdef new_game():    global state, card_list, counter, exposed,click_index    state = 0    counter = 0    click_index = []    label.set_text("Turns = 0")    # create the deck of cards    card_list = range(8)    card_list.extend(range(8))    random.shuffle(card_list)    exposed = [False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False] # define event handlersdef mouseclick(pos):    global state,click_index,counter    # find the mouse click which card    for i in range(0,16):        if i*50 < pos[0] and pos[0] < (i+1)*50:            if not exposed[i]:               if state == 0:                   state = 1                   exposed[i] = True                   click_index.append(i)               elif state ==1:                   state = 2                   exposed[i] = True                   click_index.append(i)                   counter += 1                   label.set_text("Turns = "+str(counter))               else:                    state = 1                    exposed[i] = True                    if card_list[click_index[0]] == card_list[click_index[1]]:                        exposed[click_index[0]] = True                        exposed[click_index[1]] = True                        click_index = []                        click_index.append(i)                    else:                        exposed[click_index[0]] = False                        exposed[click_index[1]] = False                        click_index = []                        click_index.append(i)                     # cards are logically 50x100 pixels in size    def draw(canvas):       for i in range(0,16):        if not exposed[i]:            canvas.draw_polygon([(i*50, 0), (i*50, 100), ((i+1)*50, 100),((i+1)*50, 0)], 3, 'Grey', 'Green')        else:            canvas.draw_text(str(card_list[i]), ((2*i+1)*50/2-10, 50+15),44, 'White')# create frame and add a button and labelsframe = simplegui.create_frame("Memory", 800, 100)frame.add_button("Reset", new_game)label = frame.add_label("Turns = 0")# register event handlersframe.set_mouseclick_handler(mouseclick)frame.set_draw_handler(draw)# get things rollingnew_game()frame.start()


0 0
原创粉丝点击