pngs/quiz.js

111 lines
2.3 KiB
JavaScript
Raw Normal View History

2010-09-20 02:27:28 +02:00
var keyHandler;
$(document).bind('keydown', function(event) {
if (keyHandler)
keyHandler(String.fromCharCode(event.keyCode));
});
2010-09-20 00:55:40 +02:00
$(window).bind('load', function() {
$('#game').hide();
$('#scoreboard').hide();
2010-09-20 02:10:26 +02:00
loadQuizData(function() {
// Quiz data has initialized
$('#setup').show();
$('#start').bind('click', function() {
try {
startQuiz();
} catch (e) {
console.error(e.stack);
}
return false; // don't submit <form>
});
});
2010-09-20 00:55:40 +02:00
});
2010-09-20 02:10:26 +02:00
var questions;
var currentQuestion = 0;
function loadQuizData(done) {
$.ajax({ url: 'data/questions.json',
contentType: 'json',
success: function(data, status) {
if (typeof data === 'string')
data = JSON.parse(data);
console.log(status);
questions = data;
done();
},
error: function(req, status, e) {
console.error(status);
console.log(e.stack);
}
});
}
2010-09-20 02:27:28 +02:00
var playerNames = [], playerScores = [];
2010-09-20 00:55:40 +02:00
function startQuiz() {
var i;
console.log('startQuiz');
2010-09-20 02:10:26 +02:00
questions.forEach(function(q) {
$('#tiers').append('<li></li>');
$('#tiers li').last().text(q.tier);
});
2010-09-20 00:55:40 +02:00
2010-09-20 02:10:26 +02:00
for(i = 0; i < 5; i++) {
var name = $('#playername' + i).val();
if (!name)
continue; // skip empty players
playerNames[i] = name;
2010-09-20 02:27:28 +02:00
playerScores[i] = 0;
2010-09-20 02:10:26 +02:00
$('#scoreboard dl').append('<dt></dt><dd>0</dd>');
$('#scoreboard dl dt').last().text(name);
$('#players').append('<li class="player'+i+'"><span class="name"></span><span class="score">0</span></li>');
$('#players li.player'+i+' span.name').text(name);
}
2010-09-20 02:27:28 +02:00
$('#setup').fadeOut(700, function() {
2010-09-20 02:10:26 +02:00
switchToScoreboard();
});
2010-09-20 00:55:40 +02:00
}
2010-09-20 02:10:26 +02:00
function switchToScoreboard() {
2010-09-20 02:27:28 +02:00
keyHandler = function(key) {
if (key === ' ') {
$('#scoreboard').fadeOut(500, function() {
switchToGame();
});
}
};
$('#scoreboard').fadeIn(300);
}
// Game screen is the one with the question in question
function switchToGame() {
var i, q = questions[currentQuestion];
$('#tier').text(q.tier);
$('#question').empty();
if (q.text) {
$('#question').append('<p></p>');
$('#question p').text(q.text);
}
for(i = 0; i < 4; i++) {
var answer = q.answers[i];
var li = $('#answers li').eq(i);
li.text(answer.text);
}
keyHandler = function(key) {
};
// Instantly show the question:
$('#game').show();
}