Tuesday, April 6, 2010

Some innocent fun with Scala and Swing

Preamble: For the coming codefest organized by devnology (Dutch programming community) everybody was supposed to write some tetris-like application in the language of their choice. After some painful speculations in which of the existing languages I can appear less ignorant than I am, I have decided to use this as a pretext for learning how Swing framework works, and to remember (a.k.a. learn once more) some Scala that I have tried to learn for a while.

I ended up installing Scala 2.8 (because the swing representation in Scala 2.7 is very inconsistent and you can't get away from mixing in quite some amounts of java code, which makes is less interesting) and NetBeans (because I wanted some context help as looking into scarce 2.8 docs now and then makes the whole task compatible with trying to read "The Woman in White" in the original language armed only with the course of "technical English" - I did that very long time ago, it proved to be my real starting point on the way to more or less decent knowledge of this human language, but it's not that story).

In short: it was doable (may be I'll add the details later), took me several days to hack something together, and provided a funny discovery.

In my MainFrame object I have the following code:
def doStart = {
  timer = new Timer
  timer.scheduleAtFixedRate (new TimerTask {
   def run() = {
  }, 0, 1000)
def doStop = {
  matrix.inGame = false
def DoShift(a:Move) = {matrix.shiftElem(a);mypanel.repaint}
reactions += {
case KeyPressed(src, key, mod, value) =>
 key match {  case Key.Right => DoShift(RIGHT)
  case Key.Left => DoShift(LEFT)
  case Key.Space => DoShift(DROP)
  case Key.Enter => DoShift(FLIP)
  case Key.Up => DoShift(ROTATELEFT)
  case Key.Down => DoShift(ROTATERIGHT)
  case Key.S => if(matrix.inGame) doStop else doStart
 The fun fact: omitting the curly braces in DoShift method made the reactions to the key strokes something like 10 times slower on my machine (Ubuntu 9.10 with 2 GB RAM and NetBeans running in the background). Why?

1 comment:

  1. I guess removing the curlies changes your doshift function to:

    def DoShift(a:Move) = matrix.shiftElem(a)

    and moves the "mypanel.repaint" outside the function.
    Just a tip, I think it is very bad practice to put variables and functions in capital starting letters. If you do so, the line:


    tells me that the variable matrix has a nested class called StartGame when it is probably a functioncall. Also, I think you can leave out "do" in your function names, i generally assume that functions "do" :)