Skip to content

Instantly share code, notes, and snippets.

@tshirtman
Last active September 25, 2019 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tshirtman/12ea3258908d4cdf08f866d94d11e920 to your computer and use it in GitHub Desktop.
Save tshirtman/12ea3258908d4cdf08f866d94d11e920 to your computer and use it in GitHub Desktop.
from threading import Thread
import numpy as np
from time import sleep
from kivy.app import App
from kivy.graphics.texture import Texture
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.properties import ObjectProperty
from kivy.core.window import Window
ANTS = 2
SIZE = 1000, 1000
KV = '''
ScatterPlane:
Widget:
id: world
size_hint: None, None
size: {SIZE}
pos_hint: {{'center': (.5, .5)}}
canvas:
Line:
rectangle: self.pos + self.size
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
'''.format(**locals())
world = np.array(
[0. for i in range(SIZE[0] * SIZE[1])],
dtype=np.float32,
)
def compute_langton(x, y):
direction = 0
# 0 = left, 1 = down, 2 = right, 3 = up
while True:
sleep(.0001)
XY = y * SIZE[0] + x
val = world[XY]
direction += 1 if val else -1
direction %= 4
world[XY] = 1 - val
x += (direction - 1) if not direction % 2 else 0
y += (direction - 2) if direction % 2 else 0
x %= SIZE[0]
y %= SIZE[1]
class Langton(App):
texture = ObjectProperty()
def build(self):
Clock.schedule_interval(self.refresh, 0)
self.texture = Texture.create(size=SIZE, colorfmt='luminance')
self.texture.min_filter = 'nearest'
self.texture.mag_filter = 'nearest'
for i in range(ANTS):
compute = Thread(
target=compute_langton,
args=(
(i + 1) * SIZE[0] // (ANTS + 1),
SIZE[1] // 2
),
)
compute.daemon = True
compute.start()
return Builder.load_string(KV)
def refresh(self, dt):
self.texture.blit_buffer(world, colorfmt='luminance', bufferfmt='float')
self.root.ids.world.canvas.flag_update()
if __name__ == '__main__':
Langton().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment