Skip to content

Instantly share code, notes, and snippets.

@struts2spring
Last active December 28, 2015 11:49
Show Gist options
  • Save struts2spring/7496238 to your computer and use it in GitHub Desktop.
Save struts2spring/7496238 to your computer and use it in GitHub Desktop.
Memory game in python
http://www.codeskulptor.org/#user24_SyOHBQnx3L_15.py
# implementation of card game - Memory
import simplegui
import random
lst = range(0, 8)
deck=lst+list(lst)
myDeck={}
restoreList=[]
turns=0
turnsLable="Turns = "+str(turns)
countClick=0
# helper function to initialize globals
def new_game():
global myDeck,restoreList,turnsLable,countClick
countClick=0
restoreList=[]
turns=0
random.shuffle(deck)
turnsLable="Turns = "+str(turns)
label.set_text(turnsLable)
for i in range(16):
point_list=[[i*50, 0], [i*50+50, 0], [i*50+50, 100], [i*50, 100]]
ls=[deck[i]]+[True]
ls.append(point_list)
myDeck[i]=ls
# define event handlers
def mouseclick(pos):
# add game state logic here
global myDeck,restoreList, turns, turnsLable,countClick
turnsLable="Turns = "+str(turns)
if(myDeck[pos[0]//50][1]):
countClick +=1
turns=(countClick+1)//2
if(len(restoreList)<2):
restoreList.append(pos[0]//50)
else:
if(myDeck[restoreList[0]][0]!= myDeck[restoreList[1]][0]):
myDeck[restoreList[0]][1]=True
myDeck[restoreList[1]][1]=True
#turns +=1
restoreList=[]
restoreList.append(pos[0]//50)
myDeck[pos[0]//50][1]=False
turnsLable="Turns = "+str(turns)
label.set_text(turnsLable)
pass
# cards are logically 50x100 pixels in size
def draw(canvas):
global myDeck
for i in range(16):
point_list=myDeck[i][2]
point=[(point_list[0][0]+ point_list[1][0])//2,50]
#print point
canvas.draw_text(str(myDeck[i][0]), point, 42, "White")
if(myDeck[i][1]):
canvas.draw_polygon(point_list, 4, "Black", "Green")
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Restart", new_game)
label = frame.add_label(turnsLable)
# 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