function write_at(x, y, text, color, font) { ctx.fillStyle = color || "black"; ctx.font = font || "50px Arial"; ctx.fillText(text, x + 50, y + 50); } function write_at_random(text, color, font) { write_at(random_choice(range(0, canvas.width - 250)), random_choice(range(200, canvas.height - 250)), text, color, font); } function random_choice(array) { index = Math.random() * array.length return array[Math.floor(index)] } function range(start, end) { return Array.apply(0, Array(end)) .map(function(element, index) { return index + start; }); } function gen_math_expression() { start = random_choice(range(0, 20)); operator = random_choice(['+', '-', '*']); end = random_choice(range(0, 20)); return start + operator + end; } function single_digit(expr) { return eval(expr) <= 9 && eval(expr) >= 1 } function gen_single_digit_expression() { expr = gen_math_expression(); while (!single_digit(expr)) { expr = gen_math_expression(); } return expr; } function number_from_keycode(keycode) { return keycode.which - 48; } function draw_welcome_and_score() { write_at(0, 0, "Single Digit Math Quiz"); write_at(600, 0, points); } function lose_sound() { var snd = new Audio("http://www.soundjay.com/misc/sounds/fail-buzzer-02.mp3"); snd.play(); } function win_sound() { var snd = new Audio("http://www.soundjay.com/misc/bell-ringing-05.wav"mp3"); snd.play(); } function main() { canvas = document.getElementById("canvas") ctx = canvas.getContext('2d'); points = 0 draw_welcome_and_score() write_at(0, 100, "Press the result of the operation on your keyboard.", 0, "20px Arial"); expr = gen_single_digit_expression() write_at_random(expr); function check_expr_and_go_next(e) { if (number_from_keycode(e) == eval(expr)) { points++; color = '#7CFC00'; // light green win_sound() } else { points--; color = 'red'; lose_sound() } ctx.clearRect(0, 0, canvas.width, canvas.height) canvas.style.background = color; draw_welcome_and_score() expr = gen_single_digit_expression() write_at_random(expr); } window.addEventListener("keydown", check_expr_and_go_next, true); } main()
<html> <canvas id="canvas" width="800" height="600" style="border:1px solid #000000;"> </canvas> </html>