Last active
August 4, 2019 11:18
-
-
Save tshirtman/2f67b725de060d84a22b910d20434447 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from array import array | |
from itertools import chain | |
from random import randint, random | |
from kivy.app import App | |
from kivy.clock import Clock | |
from kivy.uix.widget import Widget | |
from kivy.properties import NumericProperty, ListProperty | |
from kivy.graphics.texture import Texture | |
from kivy.graphics import Rectangle | |
class Dedale(Widget): | |
cols = NumericProperty(10) | |
rows = NumericProperty(10) | |
data = ListProperty([]) | |
def __init__(self, **kwargs): | |
super(Dedale, self).__init__(**kwargs) | |
self._build() | |
self.bind( | |
cols=self._build, # to rebuild the texture if you change the size | |
rows=self._build, | |
pos=self._move_rectangle, # to move the rect when the widget moves | |
size=self._move_rectangle, | |
) | |
self._update_texture() | |
Clock.schedule_interval(self._update_data, 1/60) | |
Clock.schedule_interval(self._update_texture, 0) | |
def _build(self): | |
self._texture = Texture.create(size=(self.cols, self.rows)) | |
self._texture.mag_filter = 'nearest' | |
self.data = [] | |
for row in range(self.rows): | |
r = [] | |
for col in range(self.cols): | |
r.append((col * 10, row * 20, 120)) | |
self.data.append(r) | |
with self.canvas: | |
self._rectangle = Rectangle( | |
pos=self.pos, | |
size=self.size, | |
texture=self._texture | |
) | |
def _update_data(self, *dt): | |
data = [] | |
for row in range(self.rows): | |
r = [] | |
for col in range(self.cols): | |
r.append((randint(0, 255), randint(0, 255), randint(0, 255))) | |
data.append(r) | |
self.data = data | |
def _update_texture(self, *dt): | |
arr = list(chain(*chain(*self.data))) | |
buf = array('B', arr) | |
self._texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte') | |
# NOTE needed as we don't have anything else going in that would be | |
# detected as triggering a canvas change, so it would only | |
# trigger once per second | |
self.canvas.ask_update() | |
def _move_rectangle(self, *args): | |
self._rectangle.pos = self.pos | |
self._rectangle.size = self.size | |
class MyApp(App): | |
def build(self): | |
return Dedale() | |
if __name__ == '__main__': | |
MyApp().run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment