生命动画模拟_海龟画图版

"""生命动画模拟_海龟画图版"""

__author__ = "lixingqiu"
__date__ = "2018/11/29"

from turtle import Turtle,Screen
from random import randint

def draw_grid(rows,cols,cell_width,cell_height):
    """以海龟画图屏幕为中心点画格子"""
    t = Turtle(visible=False)
    t.screen.mode("standard")
     
    t.penup()
    table_width = cols * cell_width
    table_height = rows  * cell_height
    left =  - table_width // 2
    top = table_height // 2
    t.goto(left,top)

    t.down()
    for i in range(rows):
        t.fd(table_width)
        t.bk(table_width)
        t.sety(t.ycor() - cell_height)

    t.fd(table_width)
    t.left(90)
    t.fd(table_height)
    t.left(90)
    t.fd(cell_width)
     
    t.left(90)
    for i in range(cols-1):
        t.fd(table_height)
        t.bk(table_height)
        t.setx(t.xcor() - cell_width)

    t.left(90)
    t.hideturtle()

def generate_cors(rows,cols,grid_width,grid_height):
    """产生每个格子中心点坐标列表"""
    
    table_width = cols * grid_width
    table_height = rows  * grid_height
    left =  - table_width // 2  + grid_width //2  # 左上角格子中点x坐标
    top = table_height // 2 - grid_height //2     # 左上角格子中点y坐标
    
    grids = []
    for y in range(rows):
        row_cors = []
        for x in range(cols):
            x_cor = left + grid_width * x
            y_cor = top - grid_height * y
            row_cors.append((x_cor,y_cor))
        grids.append(row_cors)

    return grids

def init_grids_value(rows,cols):
    """产生每个格子的值,0或1"""
    grids = []
    for y in range(rows):
        row_cors = []
        for x in range(cols):
            if randint(0,1) :
               row_cors.append(randint(0,1))
            else:
               row_cors.append(randint(0,1))
        grids.append(row_cors)
        
    return grids

本文隐藏内容 登陆 后才可以浏览
if __name__ == "__main__": screen = Screen() screen.delay(0) rows ,cols = 10,10 grid_width,grid_height = 10,10 grids_cors = generate_cors(rows,cols,grid_width,grid_height) grids_value = init_grids_value(rows,cols) # 初始化点 t = Turtle(visible=False) t.penup() while True: for y in range(rows): for x in range(cols): cell = grids_value[x][y] amounts = get_around_dots(rows,cols,x,y) if cell : # 值为1,表示活的 if amounts == 3 or amounts == 2 :continue if amounts < 2 or amounts >3 :grids_value[x][y] = 0 else: if amounts ==3 :grids_value[x][y] = 1 print_dots(t,rows,cols)