Friends recommended me
to read The Clean Coder: A Code of Conduct for Professional Programmers by Robert C. Martin.
And recently I read it. The book explains some parts of engineer's work, makes some useful points. And proves
them with real life stories. Most of things in the book are well known, but it's nice
that author describes not only "good path", but also situations when something gone wrong.
I have pyboard, OLED display (SSD1306) and joystick (Keyes_SJoys),
so I decided to try to make breakout clone. First of all I decided to create
something like a little framework, that will be a bit similar to React, and all game
can be formalized just in two functions:
(state) → new-state – controller that updates state;
(state) → primitives – view that converts state to generator of primitives.
For example, code that draws chess cells and invert it on click, will be like:
from lib.ssd1306 import Display
from lib.keyes import Joystick
from lib.engine import Game, rectangle, text
defis_filled(x, y, inverted):
fill =(x + y)%40==0if inverted:returnnot fill
else:return fill
defview(state):# Display data available in state['display']for x inrange(0, state['display']['width'],20):for y inrange(0, state['display']['height'],20):# rectangle is bundled view that yields pointsyieldfrom rectangle(x=x, y=y, w=20, h=20,
fill=is_filled(x, y, state['inverted']))defcontroller(state):# Joystick data available in state['display']if state['joystick']['clicked']:returndict(state, inverted=not state['inverted'])else:return state
initial_state ={'inverted':False}
chess_deck = Game(display=Display(pinout={'sda':'Y10','scl':'Y9'},
height=64,
external_vcc=False),
joystick=Joystick('X1','X2','X3'),
initial_state=initial_state,
view=view,
controller=controller)if __name__ =='__main__':
chess_deck.run()
In action:
From the code you can see, that views can be easily nested with yield from. So if we want to move
cell to separate view:
defcell(x, y, inverted):yieldfrom rectangle(x=x, y=y, w=20, h=20,
fill=is_filled(x, y, inverted))defview(state):for x inrange(0, state['display']['width'],20):for y inrange(0, state['display']['height'],20):yieldfrom cell(x, y, state['inverted'])
And another nice thing about this approach, is that because of generators we consume not a lot of memory,
if we'll make it eager, we'll fail with MemoryError: memory allocation failed soon.
Back to breakout, let's start with views, first of all implement splash screen:
defsplash(w, h):for n inrange(0, w,20):yieldfrom rectangle(x=n, y=0, w=10, h=h, fill=True)yieldfrom rectangle(x=0, y=17, w=w, h=30, fill=False)# text is bundled viewyieldfrom text(x=0, y=20, string='BREAKOUT', size=3)defview(state):yieldfrom splash(state['display']['width'],
state['display']['height'])
It will draw a nice splash screen:
On splash screen game should be started when user press joystick, so we should update code a bit:
GAME_NOT_STARTED =0
GAME_ACTIVE =1
GAME_OVER =2defcontroller(state):if state['status']== GAME_NOT_STARTED and state['joystick']['clicked']:
state['status']= GAME_ACTIVE
return state
initial_state ={'status': GAME_NOT_STARTED}
Now when joystick is pressed, game changes status to GAME_ACTIVE. And now it's time to create view
for game screen:
So we ended up with views, now we should add ability to move paddle with joystick:
defupdate_paddle(paddle, joystick, w):
paddle['x']+=int(joystick['x']/10)if paddle['x']<0:
paddle['x']=0elif paddle['x']>(w - PADDLE_W):
paddle['x']= w - PADDLE_W
return paddle
defcontroller(state):if state['status']== GAME_NOT_STARTED and state['joystick']['clicked']:
state = get_initial_game_state(state)elif state['status']== GAME_ACTIVE:
state['paddle']= update_paddle(state['paddle'], state['joystick'],
state['display']['width'])return state
Never mind performance, it'll be fixed in the end of the article:
Now it's time for the hardest thing – moving and bouncing ball, so there's no real physics, for simplification
ball movements will be represented as vx and vy, so when ball:
So now the last part, we should show "Game Over" when ball hits the bottom wall or when all bricks destroyed,
and then start game again if user clicks joystick:
defis_game_over(state):returnnot state['bricks']or state['ball']['y']> state['display']['height']defcontroller(state):if state['status']in(GAME_NOT_STARTED, GAME_OVER)\
and state['joystick']['clicked']:
state = get_initial_game_state(state)elif state['status']== GAME_ACTIVE:
state['paddle']= update_paddle(state['paddle'], state['joystick'],
state['display']['width'])
state = update_ball(state)if is_game_over(state):
state['status']= GAME_OVER
return state
And it works too:
Performance so bad because drawing pixel on the screen is relatively time consuming operation,
and we can easily fix performance by just decreasing count of bricks:
In rerenderer I need an intermediate language that can be interpreted in browser
and on Android. For browser part I chose ClojureScript. Quick note about the language,
it's an EDSL on Clojure macros, for example:
It contains only .., set! and new macros. It's very similar to Clojure interop with java and ClojureScript
interop with JavaScript. This code is an equivalent of JavaScript code:
[:free <object-var>] – removes reference from registry.
Variable can be in three forms:
[:val <value>] – value of primitive type, like double, string or bool, aka pass by value;
[:static <value>] – value from global scope, like window or document, similar to pass by reference;
[:ref <reference>] – reference to value in registry, aka pass by reference.
So, let's start with variables and implement function that returns variable value, there we'll use match macro
from core.match:
(defn extract-var
[registry var](match var
[:static x](aget js/window x); variable from global scope, from `window`[:ref x](registry x); variable from registry[:val x] x)); value
It's simple, now it's time to functions that'll handle instructions. All that functions should have
signature like (registry, *instruction-params) -> registry. We start with function that'll handle :new:
We need this because we can't use apply with new, like (apply new cls args) and also not all
constructors have apply method, so we can't just call (new (.apply cls js-args)). Interop isn't nice here
and this code is an equivalent of JavaScript:
So now it's time to write function, that can handle all instructions, it should have signature like
(registry, instruction) -> registry. And it's very easy to write it with match:
(defn interpret-instruction
[registry instruction](try(match instruction
[:new result-var cls args](create-instance registry result-var cls args)[:set var attr value](set-attr registry var attr value)[:get result-var var attr](get-attr registry result-var var attr)[:call result-var var method args](call-method registry result-var var
method args)[:free var](free registry var))(catch js/Error e
(.warn js/console "Can't execute instruction" instruction ":" e)(throw e))))
So now we can interperete instructions one by one, and interpret script with reduce:
(reduce interpret-instruction {} script)
But we forgot about one significant part. How we handle references registry? It'll be just atom with hash-map:
(def registry-cache (atom{}))
And function, that interpret script and update registry will be just:
Sometimes I need to insert youtube video looped, without sound and without controls, basically it
should work like a gif. I've tried imgur video to gif, but it limited to 15 seconds
video and a bit buggy (need to use http link instead of https).
And I thought that it would be easier
to just insert youtube player without controls and info, and use IFrame API
for looping (loop param works only with flash player) and muting.
So we need to insert IFrame API script and our script:
<scriptsrc="//www.youtube.com/iframe_api"></script><script>functiononYouTubeIframeAPIReady(){// called automatically when IFrame API loaded[].forEach.call(document.querySelectorAll('.gifify'),function(el){var player =newYT.Player(el,{events:{'onReady':function(){
player.mute();
player.playVideo();},'onStateChange':function(state){if(state.data ===0){// video ended
player.seekTo({seconds:0});
player.playVideo();}}}});});}</script>
And then insert video with ?enablejsapi=1&showinfo=0&controls=0 params and gifify class, like:
Sometimes I need to test content of a big structure, where not all content meaningful,
so I need something like fuzzy assertions. And I use core.match for that, like:
But it's redundant, and failure messages are a bit ugly and it doesn't even show content of not matched structure:
That can be easily fixed, because cljs.test is very extendable. So we just need to create macros
for simpler matching and implement assert-expr method for it:
Lately I'm working a lot with
React, and mobile development looks interesting to me. So I decided
to read something about React Native and chosen
Learning React Native by Bonnie Eisenman.
It's a short book, mostly in tutorial format. Explains differences with React and
platform specific things.
But the book have a few downsides, there's too much screenshots of XCode and app stores, book mostly written for OS X
users and contains not so much info for Android development.
Sums up everything, it seems to be a nice introductory book.
For testing ClojureScript code I use cljs.test
with figwheel. It's very cool, tests runs when
every .cljs file changed, but frequently output in DevTools is a mess. And it would be nice to
have highlighted code in expected/actual part.
It's nice, but it doesn't work with print/println, only with console.log. And only when clojure
data structures passed to console.log. cljs.test uses print and formatters for printing expected/actual. So
we need to hack cljs.test a bit. Assume your test runner looks like:
I'm a bit interested in game development and LibGDX
seems to be a good framework,
so I read Learning LibGDX Game Development by Andreas Oehlke.
I've planned to read about best practices, edge cases and how it works inside. And
it's not that kind of book. It's just an entry level tutorial with a lot of printed code.
But the author described development of a little game touching almost all LibGDX parts. So maybe it's a
nice tutorial for newcomers.
Yesterday I've finished reading
Programming Language Pragmatics by Michael L. Scott
and it's a big book with a lot of exercises (I've tried to do most of them) and with a ton of additional
material on PLP CD. This book covers most of PL related concepts from grammar to concurrency and
memory management. Also it explains why something implemented the way it implemented in exists
programming languages. And has information about ton of languages, from Algol to Haskell.
But some chapters is outdated, for example chapter about in-browser scripting. And some chapters
covers not all aspects, it's like 50 pages about mutexes and locks and only 2 pages about
message passing in chapter about concurrency.
Despite this, I guess it's must read book for software developers.
For home automation I use Hubot, it's something like a framework
for creating chat bots, it's very easy to use
and rules for it can be written in CoffeeScript, like:
So I planned to create an app for phone, which would allow me to say "Ok Google, Hubot, next song",
or something similar. But it's not possible, Android API not allow
to create custom voice actions like "Hubot",
only commands from predefined list allowed.
But I remembered that I have useless Google Glass, which GDK API allows to
create custom "Ok Glass" commands, like "Ok Glass, Hubot, next song", at least in development mode with:
And it's very great combination, with them making http request is much nicer than with java and just DefaultHttpClient, like:
Fuel.post("$url/polling/message/").body(jsonObject("user" to user,"text" to text).toString()).header("Content-Type" to "application/json").jsonPromise().success { info("Message $text sent")}.fail { warn("Can't send message $text because $it")}
Just promises in comparison with Clojure core.async
and Scala Akka it's a bit way back, it's like writing in pre ES7 JavaScript.
So why Kotlin? It's simpler to use on Android, struggling with dex errors with Scala isn't fun. Performance
is similar to apps written in Java, sometimes startup time of Clojure apps is annoying. And
there's far less magic then in Scala scaloid and Clojure Neko.