【莱斯大学 Python交互编程入门】 作业Week5 Memory
程序员文章站
2022-06-06 09:49:13
...
这一题还是花了一些时间的,参考了Crystalleaf1989的博客,实现的方法略有不同。
先生成底层的数字,再生成上层的方块,鼠标点击后将方块移除,判断两次点击的数字相同,保持方块不显示的状态。
#!/usr/bin/env python
# encoding: utf-8
"""
@author: steve
@license: Apache Licence
@software: PyCharm Community Edition
@file: week5_Memory.py
@time: 2017/11/4 15:31
"""
# implementation of card game - Memory
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import random
# helper function to initialize globals
def new_game():
global state, numbers, card_pos, exposed, turn
state = 0
turn = 0
numbers = [i for i in range(8)] * 2
random.shuffle(numbers)
exposed = [0 for i in range(16)]
card_pos = [(50 * i) for i in range(16)]
print exposed, state
# define event handlers
def mouseclick(pos):
global exposed, state, n1, n2, turn, numbers
if state == 0:
for i in range(16):
if pos[0] >= 50 * i and pos[0] <= 50 * i + 50:
if exposed[i] == 0:
exposed[i] = 1
n1 = i
state = 1
elif state == 1:
for i in range(16):
if pos[0] >= 50 * i and pos[0] <= 50 * i + 50:
if exposed[i] == 0:
exposed[i] = 1
n2 = i
state = 2
turn += 1
l.set_text("Turns = " + str(turn))
else:
for i in range(16):
if pos[0] >= 50 * i and pos[0] <= 50 * i + 50:
if numbers[n1] == numbers[n2]:
exposed[n1] = 1
exposed[n2] = 1
else:
exposed[n1] = 0
exposed[n2] = 0
if exposed[i] == 0:
exposed[i] = 1
n1 = i
state = 1
print exposed, state
# cards are logically 50x100 pixels in size
def draw(canvas):
global numbers, exposed
n = 0
for i in numbers:
canvas.draw_text(str(i), [15 + n * 50, 60], 50, "White")
n += 1
for i in range(16):
if exposed[i] == 0:
canvas.draw_polygon([[card_pos[i], 0], [card_pos[i] + 50, 0], [card_pos[i] + 50, 100], [card_pos[i], 100]], 2, "Black", "Green")
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Restart", new_game)
l = 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