Skip to main content

Score your game

Posted by malenkov on August 4, 2009 at 3:33 AM PDT

In a game the score refers to the amount of points gained by a player or a team. Consider a JavaFX component that shows the score and enables its smooth changing.

The value variable of the Score class starts a timeline on replace that smoothly changes the old value to a new one. The width and height variables define a size of a character cell. The score representation depends on the radix variable that is 10 by default. Additionally, you can provide custom images for every digit by using the images variable. In that case, the radix variable will be automatically recalculated. If you do not want to create custom images you can use the creator function. It should create nodes to insert into the component. Note that the Score class is implemented to display right-to-left oriented numbers, so that new digit orders are added to the left.

Look at the Main class that shows how to use the score counter. The following code creates the binary representation with the default font settings:

Score {
  radix: 2
  width: 15
  height: 6
}

The following code creates the octal representation with the images:

Score {
  width: 30
  height: 45
  images: for (i in [0..7]) Image {
    url: "{__DIR__}{i}.png"
  }
}

The following code uses colored text nodes for every digit:

Score {
  def color = for (hue in [36..360 step 36]) Color.hsb(hue, .9, .9);
  creator: function(index) {
    Text {
      content: "{index}"
      fill: color[index]
      font: Font {
        name: "Arial Bold"
      }
    }
  }
}

Now look at the buttons. I used the Tile container to arrange them. This container automatically resizes nodes that implement the Resizable interface. However, it doesn't resize the buttons created by my custom wrapper of the Button class. To make my wrapper resizable I implemented the following methods:

class MyButton extends CustomNode, Resizable {
  ...
  def button = Button {
    width: bind width
    height: bind height
    ...
  }
  override function create() {
    button
  }
  override function getPrefHeight(width) {
    button.getPrefHeight(width)
  }
  override function getPrefWidth(height) {
    button.getPrefWidth(height)
  }
}

original post

Related Topics >>

Comments

Hi Sergey, This is an interesting code sample. I was hoping you could provide more detail about the code, particularly in relation to the animation of the numbers. Thanks! Jonathan Giles