2021-05-31 生命模拟游戏

本文介绍了约翰·康威在1970年创建的经典细胞自动机——生命游戏。通过Python实现,你可以观察到静态生存状态、振荡器和太空船等模式。挑战包括加快模拟速度、扩大规模以及修改初始状态和规则,引导读者深入理解这一模拟过程。
摘要由CSDN通过智能技术生成
"""Game of Life simulation.

Conway's game of life is a classic cellular automation created in 1970 by John
Conway. https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life

Exercises

1. Can you identify any Still Lifes, Oscillators, or Spaceships?
2. How can you make the simulation faster? Or bigger?
3. How would you modify the initial state?
4. Try changing the rules of life :)

"""

from random import choice
from turtle import *
from freegames import square

cells = {}


def initialize():
    """Randomly initialize the cells."""
    #  初始化
    for x in range(-200, 200, 10):
        for y in range(-200, 200, 10):
            cells[x, y] = False

    for x in range(-100, 100, 10):
        for y in range(-100, 100, 10):
            cells[x, y] = choice([True, False])


def step():
    """Compute one step in the Game of Life."""
    #  生活方式
    neighbors = {}

    for x in range(-190, 190, 10):
        for y in range(-190, 190, 10):
            count = -cells[x, y]
            for h in [-10, 0, 10]:
                for v in [-10, 0, 10]:
                    count += cells[x + h, y + v]
            neighbors[x, y] = count

    for cell, count in neighbors.items():
        if cells[cell]:
            if count < 2 or count > 3:
                cells[cell] = False
        elif count == 3:
            cells[cell] = True


def draw():
    """Draw all the squares."""
    step()
    clear()
    for (x, y), alive in cells.items():
        # print(x, y)
        colo = 'black' if alive else 'red'
        square(x, y, 10, colo)
    update()
    ontimer(draw, 100)  # 模拟速度


setup(420, 420, 370, 0)
hideturtle()
speed(10)
tracer(False)
initialize()
draw()
done()

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值