Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Compile: coffee -c game.coffee
- # Run: coffee game.coffee
- # Dependencies: underscore.js / userscore.coffee and backbone.js
- # Check if the libs we need are already defined
- # When running in browser you will need to bundle or add script tags to include these libs
- if not _?
- require('underscore')
- if Backbone?
- Events = Backbone.Events
- else
- {Events} = require('./backbone.js')
- class GameTimer
- constructor: (@time, @interval) ->
- _.extend(this, Events)
- @interval ?= 1000
- start: ->
- @counter = 0
- @ticker = setInterval( (=> @tick()) , @interval)
- @trigger('start')
- tick: ->
- @counter++
- @trigger('tick', {total: @time, counter: @counter, remaining: @time-@counter})
- if @counter >= @time
- clearInterval(@ticker)
- @trigger('finished')
- pause: ->
- clearInterval(@ticker)
- @trigger('paused')
- resume: ->
- @ticker = setInterval( (=> @tick()) , @interval)
- @trigger('resume')
- class Game
- constructor: (@data)->
- console.log("new game, game has " + @data['levels'].length+ " levels")
- startLevel: (level)->
- @level = _(@data['levels']).select((x)->x['name']==level)[0]
- @position = 0
- @score = 0
- @timer = new GameTimer(@level['time'])
- @timer.start()
- @timer.pause()
- @timer.bind('finished', (=> @outOfTime()))
- @showQuestion()
- showQuestion: ->
- @timer.resume()
- @question = @level['questions'][@position]
- console.log(@question['question'])
- _(@question['answers']).each (answer) ->
- console.log(answer)
- @score++
- answer: (idx)->
- if @question['answer'] is idx
- console.log('Correct answer!')
- @timer.pause()
- else
- console.log('Incorrect answer! Try again??')
- @timer.pause()
- outOfTime: ->
- console.log("Too slow!")
- @gameOver()
- gameOver: ->
- console.log("You scored: "+@score)
- data =
- levels: [
- {
- name: 'easy',
- time: 10,
- questions: [
- { question: "what is ?", answers: ['foo','boo','coo'], answer: 0 }
- { question: "what are ?", answers: ['foo','boo','coo'], answer: 2 }
- { question: "what do ?", answers: ['foo','boo','coo'], answer: 1 }
- ]
- },{
- name: 'medium'
- time: 120,
- questions: [
- { question: "what is ?", answers: ['foo','boo','coo'], answer: 0 }
- { question: "what are ?", answers: ['foo','boo','coo'], answer: 2 }
- { question: "what do ?", answers: ['foo','boo','coo'], answer: 1 }
- ],
- }
- ]
- if not window?
- game = new Game(data)
- game.startLevel('easy')
Add Comment
Please, Sign In to add comment