Jeopardy structure (in CoffeeScript)

by thirdender

CoffeeScript

# Extend the global Array prototype with a new `shuffle` method
do -> Array::shuffle ?= ->
  for i in [@length-1..1]
    j = Math.floor Math.random() * (i + 1)
    [@[i], @[j]] = [@[j], @[i]]
  @



class JeopardyQuestion
  constructor: (@value, @question, @answer) ->
  checkAnswer: (answerToCheck) =>
    answerToCheck is @answer



class JeopardyCategory
  constructor: (@name, @questions) ->

  setQuestionByValue: (value) =>
    for question in @questions
      if value is question.value
        return @question = question
    false



class JeopardyRound
  constructor: (@name, @categories) ->

  setCategory: (name) =>
    for category in @categories
      if name is category.name
        return @category = category
    false



class Jeopardy
  roundIndex = 0
  categoryIndex = 0
  constructor: (@rounds) ->
    @round = @rounds[roundIndex]
    
  nextRound: () =>
    @round = @rounds[++roundIndex]



# Instantiate our game
game = new Jeopardy(
  [
    new JeopardyRound(
      'Jeopardy'
      [
        new JeopardyCategory(
          'Potent Potables'
          [
            new JeopardyQuestion 100, 'What is a potent potable?', '42'
            new JeopardyQuestion 200, 'What would you do for a potent potable?', '42'
            new JeopardyQuestion 300, 'Would you like a potent potable?', '42'
          ]
        )
        new JeopardyCategory(
          'Famous \'Kareem Abdul-Jabbars\''
          [
            new JeopardyQuestion 100, 'This man was famous for being who?', '42'
          ]
        )
        new JeopardyCategory(
          'I Have A Glass of Chardonnay'
          [
            new JeopardyQuestion 100, 'How did you get a marker past the guards?', '42'
          ]
        )
        new JeopardyCategory(
          'S Words'
        )
        new JeopardyCategory(
          'The Color Purple'
        )
      ]
    )
    new JeopardyRound('Double Jeopardy')
    new JeopardyRound('Final Jeopardy')
  ]
)

# Check an answer
$("body").text(
   ...