build a python memory game, and I have done the first part that goes like: def c
ID: 3758849 • Letter: B
Question
build a python memory game, and I have done the first part that goes like: def create_board(size): '''int->list (of str) Precondition: size is even positive integer between 2 and 52 ''' board = [None]*size letter='A' for i in range(len(board)//2): board[i]=letter board[i+len(board)//2 ]=board[i] letter=chr(ord(letter)+1) random.shuffle(board) return board when done the function should run like this How many cards do you want to play with? Enter an even number between 2 and 52: Player: 5 Your program: How many cards do you want to play with? Enter an even number between 2 and 52: Player: 6 Your program: * * * * * * 1 2 3 4 5 6 Enter two distinct locations on the board that you want revealed. i.e two integers in the range [1, 6] Player: 1 2 Your program: C B * * * * 1 2 3 4 5 6 Press enter to continue Player: presses enter Your program: clears the screen (so that the above board is not visible) and prints * * * * * * 1 2 3 4 5 6
Explanation / Answer
import simplegui
import random
turns=0
def new_game():
global listOfCards,exposed,openedCard,clickCounter,turns
listOfCards=[i for i in range(8)]+[i for i in range(8)]
random.shuffle(listOfCards)
exposed=[False for i in range(16)]
openedCard=[]
clickCounter=0
turns=0
def mouseclick(pos):
global clickCounter,turns
if clickCounter==0:
openedCard.append(pos[0]//50)
exposed[pos[0]//50]=True
clickCounter+=1
turns=1
elif clickCounter==1:
if not (pos[0]//50 in openedCard):
openedCard.append(pos[0]//50)
clickCounter+=1
exposed[pos[0]//50]=True
else:
if not (pos[0]//50 in openedCard):
if listOfCards[openedCard[-1]]!=listOfCards[openedCard[-2]]:
exposed[openedCard[-1]]=False
exposed[openedCard[-2]]=False
openedCard.pop()
openedCard.pop()
clickCounter=1
turns+=1
exposed[pos[0]//50]=True
openedCard.append(pos[0]//50)
def draw(canvas):
label.set_text("Turns = "+str(turns))
for i in range(16):
canvas.draw_line([50*(i%15+1),0], [50*(i%15+1),100], 2, "pink")
if exposed[i]:
canvas.draw_text(str(listOfCards[i]), [15+50*i,70], 40, "Red")
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Restart", new_game)
label=frame.add_label("Turns = 0")
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
new_game()
frame.start()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.