翻转格子版本2

python flip grid game 翻转格子

python flip grid game 翻转格子

"""
   翻转格子版本2。单击格子会翻转颜色的鼠标交互程序。 
   本程序实现矩形逻辑与重画分开,结构更加清晰!
   
"""
__author__ = '李兴球'
__date__ = '2019/10/5'

from turtle import *

def main():
    
    """主要执行函数"""
    
    width,height = 600,600

    screen = Screen()
    screen.setup(width+100,height+100)
    screen.tracer(0,0)

    t = Turtle(visible=False)   
    t.penup()
        
    rects = make_rects(10,10,500,500) # 生成10行10列的矩形

    [r.draw(t) for r in rects]        # 用海龟t把每个矩形画出来

    def event_handler(x,y):
        """单击鼠标时进行以下处理"""
        for r in rects:
            if r.collidepoint((x,y)): # 判断鼠标单击点是否在矩形r内           
               r.draw(t)
               i = str(rects.index(r)) # 只是为了缩短下一行代码长度
               screen.title(str(x) + "," + str(y) + ",index=" + i)
               screen.update()
               return
        screen.title(str(x) + "," + str(y))
        
    screen.onclick(event_handler)

    screen.mainloop()

class Rect:
    """定义矩形类"""
    def __init__(self,x,y,width,height):
        """
           x,y:左上角坐标
           width,height:宽度和高度
        """
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.right = x + width     # 最右边x坐标
        self.bottom = y - height   # 最下边y坐标               
        self.flag = 0              # 决定采用什么颜色的标志
        self.colors = ['light green','light blue']
    

You must log in to read the rest of this article. Please log in or register as a user.