Jump To …

hiscore.coffee

@copy 2012 Thomas Poter (www.thomporter.com)

Stores hi scores in a local database in the browser.

class Hiscore

  constructor: (game, game_key) ->
    @options =
    @g = game
    @game_key = game_key
    @dbSize = 1024*1024
    @webdb =
      db: null
    @webdb.db = openDatabase('h5hs', '1.0', 'Hiscore Manager', @dbSize)


    @webdb.db.transaction( (tx) ->
      tx.executeSql('CREATE TABLE IF NOT EXISTS hiscores(ID integer primary key asc, game_key text, score integer, added_on DATETIME)', [])
    )

    @createModal()


  createModal: ->
    $('<div id="hsModal" class="modal hide fade" tabindex="-1" role="dialog"' +
      'aria-labelledby="myModalLabel" aria-hidden="true">' +
      '<div class="modal-header">' +
      '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
      '<h3 id="myModalLabel">Personal Hi Scores</h3>' +
      '</div>' +
      '<div class="modal-body">' +
      '<ul class="hsitems"><li>Loading...</li></ul>' +
      '</div><div class="modal-footer">' +
      '<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>' +
      '</div>' +
      '</div>'
    ).appendTo(document.body);
    $('#hsModal').modal('hide')

  show: =>
    @getScores()
    $('#hsModal').modal('show')

  hide: ->
    $('#hsModal').modal('hide')

  addScore: (score) ->
    @webdb.db.transaction( (tx) =>
      d = new Date()
      tx.executeSql(
        'INSERT INTO hiscores (game_key,score,added_on) VALUES (?,?,?)',
        [@game_key,score,d],
        (tx, r) ->
          $.g.hi.onSuccess(tx,r)
        , (tx, e) ->
          $.g.hi.onErrors(tx, e)
        )
    )

  onSuccess: (tx, r) =>


  getScores: ->
    game_key = @game_key
    @webdb.db.transaction( (tx) =>
      tx.executeSql(
        'SELECT * FROM hiscores WHERE game_key = ? ORDER BY score DESC limit 10',
        [@game_key],
        (tx,rs) ->
          $.g.hi._receiveScores(tx,rs)
        , (tx,e) ->
          $.g.hi.onErrors(tx, e)
      )
    )


  _receiveScores: (tx, rs) ->

    rows = '';
    if rs.rows.length
      for i in [0..rs.rows.length-1] by 1
        rows += @_renderHSRow(rs.rows.item(i))
    else
      rows += '<li>You have no hiscores yet.</li>'
    $('.hsitems').html(rows)


  _renderHSRow: (item) ->
    h = '<li>' + item.score + ' <span>(' + item.added_on.substr(0,15) + ')</span></li>'
    h


  onErrors: (tx, e) =>
    alert("There has been an error: " + e.message)