# implementation of card game - Memory
#http://www.codeskulptor.org/#user41_oSKP1kMsCCysSMt.py
import simplegui
import random
card_width = 50
click_count = 0
# helper function to initialize globals
def new_game():
global cards, dcard, card1, card2, state, click_count
card1 = []
card2 = []
state = 0
click_count = 0
label.set_text("Turns = " + str(click_count))
cards = [[1,1,False], [2,2,False], [3,3,False], [4,4,False], [5,5,False], [6,6,False], [7,7,False], [8,8,False],
[9,1,False], [10,2,False], [11,3,False], [12,4,False], [13,5,False], [14,6,False], [15,7,False], [16,8,False]]
#card list includes 16 cards. True = exposed, False = Hidden.
#i don't think the first index of each card is actually necessary, but I'm going to leave them in for now.
random.shuffle(cards)
# define event handlers
def mouseclick(pos):
# add game state logic here
global cards, state, card1, card2, click_count
for card in cards:
if state == 0:
#only for initial click of the game.
if pos[0] > cards.index(card)*card_width + 0 and pos[0] < cards.index(card)*card_width +card_width and card[2] == False:
card[2] = True
state = 1
card1 = card
click_count = click_count
print click_count
elif state == 1:
#for when only one card is exposed.
if pos[0] > cards.index(card)*card_width + 0 and pos[0] < cards.index(card)*card_width +card_width and card[2] == False:
card[2] = True
state = 2
card2 = card
click_count = click_count + 1
label.set_text("Turns = " + str(click_count))
elif state == 2:
#for when two cards are exposed
if pos[0] > cards.index(card)*card_width + 0 and pos[0] < cards.index(card)*card_width +card_width and card[2] == False:
if card1[1] == card2[1]:
#clears card 1 and card 2, leaving them True. And returns game to state 1
state = 1
card1 = []
card2 = []
else:
#since cards don't match, they are turned back over. Retrurns game to state 1.
card1[2] = False
card2[2] = False
state = 1
card[2] = True
card1 = card
card2 = []
# cards are logically 50x100 pixels in size
def draw(canvas):
for card in cards:
canvas.draw_text(str(card[1]), [cards.index(card)*card_width + card_width/2.5, 50], 20, 'White')
if not card[2]:
canvas.draw_polygon([[cards.index(card)*card_width , 0], [cards.index(card)*card_width + card_width, 0],
[cards.index(card)*card_width + card_width , 100], [cards.index(card)*card_width, 100]],
1, "White", "Green")
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = " + str(click_count))
label.set_text("Turns = " + str(click_count))
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start()
print cards
# Always remember to review the grading rubric
Comments