Created
July 22, 2015 18:26
-
-
Save fsjoyti/fd36e2b54b7b1b2b4646 to your computer and use it in GitHub Desktop.
Memory game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# implementation of card game - Memory | |
import simplegui | |
import random | |
turns = 0 | |
deck = [] | |
state = 0 | |
exposed = [] | |
cardWidth = 34 | |
cardHeight = 92 | |
firstCardIndex = 0 | |
secondCardIndex = 0 | |
# helper function to initialize globals | |
def new_game(): | |
global deck,exposed,state,selectedCard,turns | |
exposed =[] | |
deck = range(0,8) + range (0,8) | |
random.shuffle(deck) | |
for i in range(16): | |
exposed.append(False) | |
state = 0 | |
turns = 0 | |
# define event handlers | |
def mouseclick(pos): | |
# add game state logic here | |
global state,turns,firstCardIndex,secondCardIndex | |
if state == 0 : | |
currentIndex = pos[0]//50 | |
state = 1 | |
turns = 1 | |
exposed[currentIndex] = True | |
firstCardIndex = currentIndex | |
elif state == 1 : | |
currentIndex = pos[0]//50 | |
if not exposed[currentIndex]: | |
state = 2 | |
secondCardIndex = currentIndex | |
exposed[currentIndex] = True | |
elif state == 2: | |
currentIndex = pos[0]//50 | |
turns = turns +1 | |
if not exposed[currentIndex]: | |
if (deck[firstCardIndex]!=deck[secondCardIndex]): | |
exposed[firstCardIndex] = False | |
exposed[secondCardIndex] = False | |
firstCardIndex = 0 | |
secondCardIndex = 0 | |
state =1 | |
exposed[currentIndex]= True | |
firstCardIndex = currentIndex | |
# cards are logically 50x100 pixels in size | |
def draw(canvas): | |
global exposed | |
label.set_text("Turns = "+str(turns)) | |
for i in range(16): | |
if (exposed[i]): | |
canvas.draw_polygon([[40-cardWidth/2+48*i, 47-cardHeight/2], [40+cardWidth/2+48*i, 47-cardHeight/2], [40+cardWidth/2+48*i, 47+cardHeight/2], [40-cardWidth/2+48*i, 47+cardHeight/2]], 5, "Teal") | |
canvas.draw_text(str(deck[i]), (34+48*i, 60), 26, "Blue") | |
else: | |
canvas.draw_polygon([[40-cardWidth/2+48*i, 47-cardHeight/2], [40+cardWidth/2+48*i, 47-cardHeight/2], [40+cardWidth/2+48*i, 47+cardHeight/2], [40-cardWidth/2+48*i, 47+cardHeight/2]], 10, "Yellow", "Red") | |
# 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 = 0") | |
# register event handlers | |
frame.set_mouseclick_handler(mouseclick) | |
frame.set_draw_handler(draw) | |
# get things rolling | |
new_game() | |
frame.start() | |
# Always remember to review the grading rubric | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment