May 22, 2015

Tetris in clojurescript and re-frame Part 2 - Basic Layout


First he starts with the HTML part for the application. This is the code:

{% extends "base.html" %}
{% block content %}

<div id="tetris-main"></div>
{% endblock %}

{% block js-bottom %}
<script type="text/javascript">de.sveri.omtet.tetris.core.main();</script>
{% endblock %}    
I am using selmer as a templating engine, so all you see here is the main div where the clojurescript will attach toand the call of the clojurescript tetris main function.
You can find the code here: index.html


This is where we are already starting to use clojurescript and this differs from the original tutorial. Instead of defining the canvas in plain html we will use reagent for this.

(defn ^:export main []
  (rf/dispatch [:initialise-db])
  (reagent/render-component (fn [] [core]) (h/get-elem "tetris-main")))   
This is the main function that is called from the html file. It will render a core function on the tetris-main html div. The ^export directive says that the main functions name should not be minimized so that it can be called from the html file.

This is the core function:

(defn core []
  (let [tet-width "200px"]
      [:canvas#tetris-canv {:height "400px" :width tet-width :style {:background-color "#444444"}}]
      [:div#score {:style {:background-color "#CCCCCC" :width tet-width}} "Score: "]]
        {:on-click #(rf/dispatch [:start-game])} "Start"]
       [:button.btn.btn-primary {:on-click #(rf/dispatch [:restart-game])} "Restart"]]]]))
This just defines the HTML structure of the canvas and two buttons. One to start the game and one to restart the game.There is also a Score panel beneath the canvas.

One thing to note here are the #(rf/dispatch... functions. rf is the re-frame namespace and dispatch will be called when a click on the respective button was done.

Every dispatch function takes 1..n arguments whereas the first one is always a vector containing the event id path. In these cases: :start-game and :restart-game, which do what their name implies.

We will not init the canvas itself yet. This will be done as part of the application state initalization.

Tags: tetris clojuresrcipt