Skip to content

Instantly share code, notes, and snippets.

@tshirtman
Last active April 7, 2021 15:43
Show Gist options
  • Save tshirtman/d14837a06d64b481e1a5dca71c46b1c6 to your computer and use it in GitHub Desktop.
Save tshirtman/d14837a06d64b481e1a5dca71c46b1c6 to your computer and use it in GitHub Desktop.
langton ant example using kivy
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
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 = SIZE[0] // 2, SIZE[1] // 2
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'
compute = Thread(target=compute_langton)
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