<commit_before>/*

humusCode.js - generate code from Humus tokens

The MIT License (MIT)

Copyright (c) 2016 Dale Schumacher

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
"use strict";

var gen = module.exports;

//var log = console.log;
var log = function () {};

gen._code = (function () {
    var the_case_end = { beh: 'case_end' };
    var the_self_expr = { beh: 'self_expr' };
    var the_any_ptrn = { beh: 'any_ptrn' };
    var the_self_ptrn = { beh: 'self_ptrn' };

    return {
        pair_expr: function pair_expr(head, tail) {
            return { beh: 'pair_expr', head: head, tail: tail };
        },
        let_expr: function let_expr(eqtn, expr) {
            return { beh: 'let_expr', eqtn: eqtn, expr: expr };
        },
        if_expr: function if_expr(eqtn, expr, next) {
            return { beh: 'if_expr', eqtn: eqtn, expr: expr, next: next };
        },
        case_expr: function case_expr(expr, next) {
            return { beh: 'case_expr', expr: expr, next: next };
        },
        case_choice: function case_choice(ptrn, expr, next) {
            return { beh: 'case_choice', ptrn: ptrn, expr: expr, next: next };
        },
        case_end: function case_end() {
            return the_case_end;
        },
        new_expr: function new_expr(expr) {
            return { beh: 'new_expr', expr: expr };
        },
        app_expr: function app_expr(abs, arg) {
            return { beh: 'app_expr', abs: abs, arg: arg };
        },
        ident_expr: function ident_expr(name) {
            return { beh: 'ident_expr', ident: name };
        },
        self_expr: function self_expr() {
            return the_self_expr;
        },
        abs_expr: function abs_expr(ptrn, body) {
            return { beh: 'abs_expr', ptrn: ptrn, body: body };
        },
        const_expr: function const_expr(value) {
            return { beh: 'const_expr', value: value };
        },
        literal_expr: function literal_expr(value) {
            return { beh: 'literal_expr', value: value };
        },
        eqtn: function eqtn(left, right) {
            return { beh: 'eqtn', left: left, right: right };
        },
        any_ptrn: function any_ptrn() {
            return the_any_ptrn;
        },
        pair_ptrn: function pair_ptrn(head, tail) {
            return { beh: 'pair_ptrn', head: head, tail: tail };
        },
        ident_ptrn: function ident_ptrn(name) {
            return { beh: 'ident_ptrn', ident: name };
        },
        self_ptrn: function self_ptrn() {
            return the_self_ptrn;
        },
        value_ptrn: function value_ptrn(expr) {
            return { beh: 'value_ptrn', expr: expr };
        },
        const_ptrn: function const_ptrn(value) {
            return { beh: 'const_ptrn', value: value };
        },
        literal_ptrn: function literal_ptrn(value) {
            return { beh: 'literal_ptrn', value: value };
        }
    };
})();

gen.humus = function genHumus(ast) {
    log('genHumus:', ast);
    var result = gen.block(ast);  // { value: [stmt, ...], ... }
    log('Humus:', result);
    return result;
};

gen.block = function genBlock(ast) {
    log('genBlock:', ast);
    var final = { beh: 'empty_stmt' };
    var result = {
        tail: final  // placeholder for initial statement
    };
    var scope = [];
    var current = result;
    ast.value.forEach(function (stmt) {  // { value: [stmt, ...], ... }
        current.tail = {
            beh: 'stmt_pair',
            head: gen.stmt(stmt, scope),
            tail: final
        };
        current = current.tail;
    });
    result = {
        beh: 'block_beh',
        vars: [],
        stmt: result.tail
    };
    log('Block:', result);
    return result;
};

gen.stmt = function genStmt(ast, scope) {
    log('genStmt:', ast, scope);
    var result = ast;
    if (ast.type === 'expr') {  // { type: 'expr', expr: value }
        result = {
            beh: 'expr_stmt',
            expr: gen.expr(ast.expr)
        };
    } else if (ast.type === 'let') {  // { type: 'let', eqtn: equation }
        result = {
            beh: 'let_stmt',
            eqtn: gen.eqtn(ast.eqtn, scope)
        };
    } else if (ast.type === 'send') {  // { type: 'send', msg: message, to: target }
        result = {
            beh: 'send_stmt',
            msg: gen.expr(ast.msg),
            to: gen.expr(ast.to)
        };
    } else if (ast.type === 'after_send') {  // { type: 'after_send', dt: delay, msg: message, to: target }
        result = {
            beh: 'after_send_stmt',
            msg: gen.expr(ast.msg),
            to: gen.expr(ast.to),
            dt: gen.expr(ast.dt)
        };
    } else if (ast.type === 'create') {  // { type: 'create', ident: identifier, expr: behavior }
        var name = ast.ident.value;  // extract actual identifier name
        if (scope) {
            scope[scope.length] = name;  // FIXME: check for duplicates?
        }
        result = {
            beh: 'create_stmt',
            ident: name,
            expr: gen.expr(ast.expr)
        };
    } else if (ast.type === 'become') {  // { type: 'become', expr: behavior }
        result = {
            beh: 'become_stmt',
            expr: gen.expr(ast.expr)
        };
    } else if (ast.type === 'throw') {  // { type: 'throw', expr: exception }
        result = {
            beh: 'throw_stmt',
            expr: gen.expr(ast.expr)
        };
    }
    log('Stmt:', result);
    return result;
};

gen.expr = function genExpr(ast) {
    log('genExpr:', ast);
    var result = ast;
    if (ast.type === 'pair') {  // { type: 'pair', head: term, tail: more }
        result = gen._code.pair_expr(
            gen.expr(ast.head),
            gen.expr(ast.tail)
        );
    } else if (ast.type === 'let_in') {  // { type: 'let_in', eqtn: equation, expr: expression }
        result = gen._code.let_expr(
            gen.eqtn(ast.eqtn),  // FIXME: track declared variables ??
            gen.expr(ast.expr)
        );
    } else if (ast.type === 'if') {  // { type: 'if', eqtn: eqtn, expr: cnsq, next: altn }
        result = gen._code.if_expr(
            gen.eqtn(ast.eqtn),  // FIXME: track declared variables ??
            gen.expr(ast.expr),
            gen.expr(ast.next)
        );
    } else if (ast.type === 'case') {  // { type: 'case', expr: value, next: ... }
        result = gen._code.case_expr(
            gen.expr(ast.expr),
            gen.case(ast.next)
        );
    } else if (ast.type === 'new') {  // { type: 'new', expr: term }
        result = gen._code.new_expr(gen.expr(ast.expr));
    } else if (ast.type === 'app') {  // { type: 'app', abs: fn, arg: expr }
        result = gen._code.app_expr(
            gen.expr(ast.abs),
            gen.expr(ast.arg)
        );
    } else if (ast.type === 'ident') {  // { type: 'ident', value: name }
        result = gen._code.ident_expr(ast.value);
    } else if (ast.type === 'block') {  // { type: 'block', value: [stmt, ...] }
        result = gen.block(ast);
    } else if (ast.type === 'self') {  // { type: 'self' }
        result = gen._code.self_expr();
    } else if (ast.type === 'abs') {  // { type: 'abs', ptrn: ptrn, body: expr }
        result = gen._code.abs_expr(
            gen.ptrn(ast.ptrn),  // FIXME: track declared variables ??
            gen.expr(ast.body)
        );
    } else if (ast.type === 'const') {  // { type: 'const', value: ... }
        result = gen._code.const_expr(ast.value);
    } else if (ast.type === 'literal') {  // { type: 'literal', value: ... }
        result = gen._code.literal_expr(ast.value);
    }
    log('Expr:', result);
    return result;
};

gen.case = function genCase(ast) {
    log('genCase:', ast);
    var result = ast;
    if (ast.type === 'choice') {  // { type: 'choice', ptrn: cond, expr: body, next: ... }
        result = gen._code.case_choice(
            gen.ptrn(ast.ptrn),  // FIXME: track declared variables ??
            gen.expr(ast.expr),
            gen.case(ast.next)
        );
    } else if (ast.type === 'end') {  // { type: 'end' }
        result = gen._code.case_end();
    }
    log('Case:', result);
    return result;
};

gen.eqtn = function genEqtn(ast, scope) {
    log('genEqtn:', ast, scope);
    var result = ast;
    if (ast.type === 'eqtn') {  // { type: 'eqtn', left: lhs, right: rhs }
        result = gen._code.eqtn(
            gen.ptrn(ast.left, scope),
            gen.ptrn(ast.right, scope)
        );
    }
    log('Eqtn:', result);
    return result;
};

gen.ptrn = function genPtrn(ast, scope) {
    log('genPtrn:', ast, scope);
    var result = ast;
    if (ast.type === 'pair') {  // { type: 'pair', head: pterm, tail: more }
        result = gen._code.pair_ptrn(
            gen.ptrn(ast.head, scope),
            gen.ptrn(ast.tail, scope)
        );
    } else if (ast.type === 'any') {  // { type: 'any' }
        result = gen._code.any_ptrn();
    } else if (ast.type === 'value') {  // { type: 'value', expr: term }
        result = gen._code.value_ptrn(gen.expr(ast));
    } else if (ast.type === 'ident') {  // { type: 'ident', value: name }
        var name = ast.value;
        if (scope) {
            scope[scope.length] = name;  // FIXME: check for duplicates?
        }
        result = gen._code.ident_ptrn(name);
    } else if (ast.type === 'self') {  // { type: 'self' }
        result = gen._code.self_ptrn();
    } else if ((ast.type === 'block')   // { type: 'block', value: [stmt, ...] }
            || (ast.type === 'abs')) {  // { type: 'abs', ptrn: ptrn, body: expr }
        result = gen._code.value_ptrn(gen.expr(ast));
    } else if (ast.type === 'const') {  // { type: 'const', value: ... }
        result = gen._code.const_ptrn(ast.value);
    } else if (ast.type === 'literal') {  // { type: 'literal', value: ... }
        result = gen._code.literal_ptrn(ast.value);
    }
    log('Ptrn:', result);
    return result;
};
<commit_msg>Add object encoding for statements<commit_after>/*

humusCode.js - generate code from Humus tokens

The MIT License (MIT)

Copyright (c) 2016 Dale Schumacher

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
"use strict";

var gen = module.exports;

//var log = console.log;
var log = function () {};

gen._code = (function () {
    var the_case_end = { beh: 'case_end' };
    var the_self_expr = { beh: 'self_expr' };
    var the_any_ptrn = { beh: 'any_ptrn' };
    var the_self_ptrn = { beh: 'self_ptrn' };

    return {
        expr_stmt: function expr_stmt(expr) {
            return { beh: 'expr_stmt', expr: expr };
        },
        let_stmt: function let_stmt(eqtn) {
            return { beh: 'let_stmt', eqtn: eqtn };
        },
        send_stmt: function send_stmt(msg, to) {
            return { beh: 'send_stmt', msg: msg, to: to };
        },
        after_send_stmt: function after_send_stmt(msg, to, dt) {
            return { beh: 'after_send_stmt', msg: msg, to: to, dt: dt };
        },
        create_stmt: function create_stmt(name, expr) {
            return { beh: 'create_stmt', ident: name, expr: expr };
        },
        become_stmt: function become_stmt(expr) {
            return { beh: 'become_stmt', expr: expr };
        },
        throw_stmt: function throw_stmt(expr) {
            return { beh: 'throw_stmt', expr: expr };
        },
        pair_expr: function pair_expr(head, tail) {
            return { beh: 'pair_expr', head: head, tail: tail };
        },
        let_expr: function let_expr(eqtn, expr) {
            return { beh: 'let_expr', eqtn: eqtn, expr: expr };
        },
        if_expr: function if_expr(eqtn, expr, next) {
            return { beh: 'if_expr', eqtn: eqtn, expr: expr, next: next };
        },
        case_expr: function case_expr(expr, next) {
            return { beh: 'case_expr', expr: expr, next: next };
        },
        case_choice: function case_choice(ptrn, expr, next) {
            return { beh: 'case_choice', ptrn: ptrn, expr: expr, next: next };
        },
        case_end: function case_end() {
            return the_case_end;
        },
        new_expr: function new_expr(expr) {
            return { beh: 'new_expr', expr: expr };
        },
        app_expr: function app_expr(abs, arg) {
            return { beh: 'app_expr', abs: abs, arg: arg };
        },
        ident_expr: function ident_expr(name) {
            return { beh: 'ident_expr', ident: name };
        },
        self_expr: function self_expr() {
            return the_self_expr;
        },
        abs_expr: function abs_expr(ptrn, body) {
            return { beh: 'abs_expr', ptrn: ptrn, body: body };
        },
        const_expr: function const_expr(value) {
            return { beh: 'const_expr', value: value };
        },
        literal_expr: function literal_expr(value) {
            return { beh: 'literal_expr', value: value };
        },
        eqtn: function eqtn(left, right) {
            return { beh: 'eqtn', left: left, right: right };
        },
        any_ptrn: function any_ptrn() {
            return the_any_ptrn;
        },
        pair_ptrn: function pair_ptrn(head, tail) {
            return { beh: 'pair_ptrn', head: head, tail: tail };
        },
        ident_ptrn: function ident_ptrn(name) {
            return { beh: 'ident_ptrn', ident: name };
        },
        self_ptrn: function self_ptrn() {
            return the_self_ptrn;
        },
        value_ptrn: function value_ptrn(expr) {
            return { beh: 'value_ptrn', expr: expr };
        },
        const_ptrn: function const_ptrn(value) {
            return { beh: 'const_ptrn', value: value };
        },
        literal_ptrn: function literal_ptrn(value) {
            return { beh: 'literal_ptrn', value: value };
        }
    };
})();

gen.humus = function genHumus(ast) {
    log('genHumus:', ast);
    var result = gen.block(ast);  // { value: [stmt, ...], ... }
    log('Humus:', result);
    return result;
};

gen.block = function genBlock(ast) {
    log('genBlock:', ast);
    var final = { beh: 'empty_stmt' };
    var result = {
        tail: final  // placeholder for initial statement
    };
    var scope = [];
    var current = result;
    ast.value.forEach(function (stmt) {  // { value: [stmt, ...], ... }
        current.tail = {
            beh: 'stmt_pair',
            head: gen.stmt(stmt, scope),
            tail: final
        };
        current = current.tail;
    });
    result = {
        beh: 'block_beh',
        vars: [],
        stmt: result.tail
    };
    log('Block:', result);
    return result;
};

gen.stmt = function genStmt(ast, scope) {
    log('genStmt:', ast, scope);
    var result = ast;
    if (ast.type === 'expr') {  // { type: 'expr', expr: value }
        result = gen._code.expr_stmt(gen.expr(ast.expr));
    } else if (ast.type === 'let') {  // { type: 'let', eqtn: equation }
        result = gen._code.let_stmt(gen.eqtn(ast.eqtn, scope));
    } else if (ast.type === 'send') {  // { type: 'send', msg: message, to: target }
        result = gen._code.send_stmt(
            gen.expr(ast.msg),
            gen.expr(ast.to)
        );
    } else if (ast.type === 'after_send') {  // { type: 'after_send', dt: delay, msg: message, to: target }
        result = gen._code.after_send_stmt(
            gen.expr(ast.msg),
            gen.expr(ast.to),
            gen.expr(ast.dt)
        );
    } else if (ast.type === 'create') {  // { type: 'create', ident: identifier, expr: behavior }
        var name = ast.ident.value;  // extract actual identifier name
        if (scope) {
            scope.push(name);  // FIXME: check for duplicates?
        }
        result = gen._code.create_stmt(name, gen.expr(ast.expr));
    } else if (ast.type === 'become') {  // { type: 'become', expr: behavior }
        result = gen._code.become_stmt(gen.expr(ast.expr));
    } else if (ast.type === 'throw') {  // { type: 'throw', expr: exception }
        result = gen._code.throw_stmt(gen.expr(ast.expr));
    }
    log('Stmt:', result);
    return result;
};

gen.expr = function genExpr(ast) {
    log('genExpr:', ast);
    var result = ast;
    if (ast.type === 'pair') {  // { type: 'pair', head: term, tail: more }
        result = gen._code.pair_expr(
            gen.expr(ast.head),
            gen.expr(ast.tail)
        );
    } else if (ast.type === 'let_in') {  // { type: 'let_in', eqtn: equation, expr: expression }
        result = gen._code.let_expr(
            gen.eqtn(ast.eqtn),  // FIXME: track declared variables ??
            gen.expr(ast.expr)
        );
    } else if (ast.type === 'if') {  // { type: 'if', eqtn: eqtn, expr: cnsq, next: altn }
        result = gen._code.if_expr(
            gen.eqtn(ast.eqtn),  // FIXME: track declared variables ??
            gen.expr(ast.expr),
            gen.expr(ast.next)
        );
    } else if (ast.type === 'case') {  // { type: 'case', expr: value, next: ... }
        result = gen._code.case_expr(
            gen.expr(ast.expr),
            gen.case(ast.next)
        );
    } else if (ast.type === 'new') {  // { type: 'new', expr: term }
        result = gen._code.new_expr(gen.expr(ast.expr));
    } else if (ast.type === 'app') {  // { type: 'app', abs: fn, arg: expr }
        result = gen._code.app_expr(
            gen.expr(ast.abs),
            gen.expr(ast.arg)
        );
    } else if (ast.type === 'ident') {  // { type: 'ident', value: name }
        result = gen._code.ident_expr(ast.value);
    } else if (ast.type === 'block') {  // { type: 'block', value: [stmt, ...] }
        result = gen.block(ast);
    } else if (ast.type === 'self') {  // { type: 'self' }
        result = gen._code.self_expr();
    } else if (ast.type === 'abs') {  // { type: 'abs', ptrn: ptrn, body: expr }
        result = gen._code.abs_expr(
            gen.ptrn(ast.ptrn),  // FIXME: track declared variables ??
            gen.expr(ast.body)
        );
    } else if (ast.type === 'const') {  // { type: 'const', value: ... }
        result = gen._code.const_expr(ast.value);
    } else if (ast.type === 'literal') {  // { type: 'literal', value: ... }
        result = gen._code.literal_expr(ast.value);
    }
    log('Expr:', result);
    return result;
};

gen.case = function genCase(ast) {
    log('genCase:', ast);
    var result = ast;
    if (ast.type === 'choice') {  // { type: 'choice', ptrn: cond, expr: body, next: ... }
        result = gen._code.case_choice(
            gen.ptrn(ast.ptrn),  // FIXME: track declared variables ??
            gen.expr(ast.expr),
            gen.case(ast.next)
        );
    } else if (ast.type === 'end') {  // { type: 'end' }
        result = gen._code.case_end();
    }
    log('Case:', result);
    return result;
};

gen.eqtn = function genEqtn(ast, scope) {
    log('genEqtn:', ast, scope);
    var result = ast;
    if (ast.type === 'eqtn') {  // { type: 'eqtn', left: lhs, right: rhs }
        result = gen._code.eqtn(
            gen.ptrn(ast.left, scope),
            gen.ptrn(ast.right, scope)
        );
    }
    log('Eqtn:', result);
    return result;
};

gen.ptrn = function genPtrn(ast, scope) {
    log('genPtrn:', ast, scope);
    var result = ast;
    if (ast.type === 'pair') {  // { type: 'pair', head: pterm, tail: more }
        result = gen._code.pair_ptrn(
            gen.ptrn(ast.head, scope),
            gen.ptrn(ast.tail, scope)
        );
    } else if (ast.type === 'any') {  // { type: 'any' }
        result = gen._code.any_ptrn();
    } else if (ast.type === 'value') {  // { type: 'value', expr: term }
        result = gen._code.value_ptrn(gen.expr(ast));
    } else if (ast.type === 'ident') {  // { type: 'ident', value: name }
        var name = ast.value;
        if (scope) {
            scope.push(name);  // FIXME: check for duplicates?
        }
        result = gen._code.ident_ptrn(name);
    } else if (ast.type === 'self') {  // { type: 'self' }
        result = gen._code.self_ptrn();
    } else if ((ast.type === 'block')   // { type: 'block', value: [stmt, ...] }
            || (ast.type === 'abs')) {  // { type: 'abs', ptrn: ptrn, body: expr }
        result = gen._code.value_ptrn(gen.expr(ast));
    } else if (ast.type === 'const') {  // { type: 'const', value: ... }
        result = gen._code.const_ptrn(ast.value);
    } else if (ast.type === 'literal') {  // { type: 'literal', value: ... }
        result = gen._code.literal_ptrn(ast.value);
    }
    log('Ptrn:', result);
    return result;
};
<|endoftext|>


<commit_before>/*
This is a game by:
Markus "TiByte" Becker   - Lead Developer
Lucas "LFalch"           - Programmer
Aileen                   - Graphic Designer
Kilian "Malloth Rha"     - Musician
Micha                    - Junior Programmer
Using Libraries: Pixi.js and Howler.js
date: 16.04.2016 for LD35
theme: Shapeshift
*/

/*

STRING OF EVENTS:
1. Intro Comic (3 Pictures)
    - socks come to life when unattended
2. Under the bed
    2.1. game
        - avoid hands
    2.2. more story
        - grey sock tells hero to fight sewer monster
3. Sewerfall
    3.1. game
        - falling in the sewer
        - avoid dirt
    3.2. reward (grow arms)
        - if not too dirty
4. Snake game
    4.1. game
        - eat fluff
    4.2. reward (grow bigger)
        - if player ate more than 20 fluff in 30 sec.
5. Plumbing game
    5.1. game
        - turn tiles to connect pipes
    5.2. reward (grow hair)
        - did it in 15 seconds
### Optional ###
0. Platforming game
    0.1. game
    0.2. reward (grow wings)
################
6. Doodle Jump
    6.1. game
        - collect something to gain height
    6.2. more story
        - if won grabbed by sock-hand
        - else falling = losing health
7. Boss fight
    - attack in turns
*/

// Cheat Sheet: https://github.com/mtib/ludum34/blob/master/game.js

// Canvas Size
const WIDTH = 1280;
const HEIGHT = 720;

// Current version
const version = "0.01d"

// Initialize Renderer
var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, {antialiasing: true, transparent: false, resolution: 1});
renderer.backgroundColor = 0x6ec2cb;
document.getElementById("gamediv").appendChild(renderer.view);

// Master Containter
var stage = new PIXI.Container();

// Layers
var cBack = new PIXI.Container();
var cMiddle = new PIXI.Container();
var cFront = new PIXI.Container();
var cGui = new PIXI.Container();

// Config goes here:
const fontConfig = {font: "30px 'Arial'", fill: "#000000", align: "left"};
const debugConfig = {font: "20px 'Fira Code',monospace,sans-serif", fill: "#FF0000", align: "left"};
const relcenter = {x:0.5,y:0.5};
const nKey = keyboard(78);
const enterKey = keyboard(13);

const leftArrow = keyboard(37);
const upArrow = keyboard(38);
const rightArrow = keyboard(39);
const downArrow = keyboard(40);

const aKey = keyboard(65);
const wKey = keyboard(87);
const dKey = keyboard(68);
const sKey = keyboard(83);

const s000bed1 = "./scenes/000/bed.pic1.jpg";
const s000bed2 = "./scenes/000/bed.pic2.jpg";
const s001bg = "./scenes/001/background.jpg"; // background for game #1
const ssock = "./scenes/001/sock.png"; // normal sock, for use in all? scenes
const s001armo = "./scenes/001/arm.open.png"; // o = open
const s001armg = "./scenes/001/arm.sock.png"; // g = grabbed

function Game1Sock() {
    self = this;
    size = 128 // Pixel
    speed = 3 // Pixel / Frame
    this.sprite = new PIXI.Sprite.fromImage(ssock);
    this.sprite.anchor = relcenter;
    this.sprite.width = size;
    this.sprite.height = size;
    this.sprite.position = {x: WIDTH*0.5, y: HEIGHT*0.5};
    this.die = function() {
        cMiddle.removeChild(this.sprite);
    }
    this.move = function() {
        delta = {x:0, y:0};
        did = false;
        if ((rightArrow.isDown || dKey.isDown) && this.sprite.position.x < WIDTH - 70) {
            delta.x += speed;
        }
        if ((leftArrow.isDown || aKey.isDown) && this.sprite.position.x > 70) {
            delta.x -= speed;
        }
        if ((upArrow.isDown || wKey.isDown) && this.sprite.position.y > 230) {
            delta.y -= speed;
        }
        if ((downArrow.isDown || sKey.isDown) && this.sprite.position.y < HEIGHT - 100) {
            delta.y += speed;
        }
        magsqr = Math.sqrt(Math.abs(delta.x) + Math.abs(delta.y))
        if (magsqr == 0) {
            return;
        }
        if (delta.x > 0 && this.sprite.scale.x > 0) {
            this.sprite.scale.x *= -1;
        } else if (delta.x < 0 && this.sprite.scale.x < 0) {
            this.sprite.scale.x *= -1;
        }
        delta.x /= magsqr;
        delta.y /= magsqr;
        this.sprite.position.x += delta.x;
        this.sprite.position.y += delta.y;
    }
    cMiddle.addChild(this.sprite);
    console.log("stuff should happen");
}

function State() {
    self = this;
    this.debugText = new PIXI.Text("Version: "+version+"\n<Debug Information>\nState: ",debugConfig);
    this.debugText.position = {x:5,y:5};
    this.debugStateText = new PIXI.Text("0", debugConfig);
    this.debugStateText.position = {x:89,y:45};

    this.doc = {}; // DestroyOnChange

    cGui.addChild(this.debugText);
    cGui.addChild(this.debugStateText);
    this.number = 0;
    this.run = function(){
        console.log("default state");
    }

    this.nextState = function(){
        for (var sprite in this.doc) {
            if (this.doc.hasOwnProperty(sprite)) {
                if (this.doc[sprite].die) {
                    this.doc[sprite].die();
                } else {
                    cBack.removeChild(this.doc[sprite]);
                }
            }
        }
        this.number += 1;
        this.switched = true;
        this.debugStateText.text = this.number;
        this.run = this.funcarray[this.number];
    }
    this.substate = 0;
    this.introfunc = function(){
        if (this.switched){
            this.substate = 1;
            this.doc["s000bed1"] = PIXI.Sprite.fromImage(s000bed1);
            this.doc["s000bed2"] = PIXI.Sprite.fromImage(s000bed2);

            this.doc["s000bed1"].width = WIDTH;
            this.doc["s000bed1"].height = HEIGHT;
            this.doc["s000bed2"].width = WIDTH;
            this.doc["s000bed2"].height = HEIGHT;

            cBack.addChild(this.doc["s000bed1"]);

            this.switched = false;
        }
    }
    nKey.press = function(){
        console.log(self.number, self.substate);
        if (self.number === 0){
            if (self.substate == 2){
                self.nextState();
            }else{
                cBack.removeChild(self.doc["s000bed"+self.substate++]);
                cBack.addChild(self.doc["s000bed"+self.substate]);
            }
        }
    }
    this.switched = true;
    this.underTheBed = function(){
        if (this.switched) {
            this.doc["s001bg"] = PIXI.Sprite.fromImage(s001bg);
            this.doc["s001armo"] = PIXI.Sprite.fromImage(s001armo);
            this.doc["s001armg"] = PIXI.Sprite.fromImage(s001armg);

            this.doc["s001bg"].width = WIDTH;
            this.doc["s001bg"].height = HEIGHT;
            cBack.addChild(this.doc["s001bg"]);
            this.doc["gamesock"] = new Game1Sock();

            this.switched = false;
        }
        this.doc["gamesock"].move();
    }
    this.funcarray = [this.introfunc, this.underTheBed];

    this.run = this.funcarray[this.number];
}

var gamestate = new State();

/*
    stage
      |
      +-- cBack
      +-- cMiddle
      +-- cFront
      +-- cGui
Drawn from top to bottom
*/
stage.addChild(cBack);
stage.addChild(cMiddle);
stage.addChild(cFront);
stage.addChild(cGui);

PIXI.loader
    .add(s001bg)
    .add(s001armg)
    .add(s001armo)
    .add(ssock)
    .load(setup);

function setup(){
    // Do setup here
    // Easteregg: eyes!¬
    renderStage();
}

// Request Animation Frame
function renderStage(){
    requestAnimationFrame(renderStage);
    gameLoop();
    renderer.render(stage);
}

// Called before rendering
function gameLoop(){
    // after doing logic:
    gamestate.run()
}

// start game
setup();
<commit_msg>Add music to each scene<commit_after>/*
This is a game by:
Markus "TiByte" Becker   - Lead Developer
Lucas "LFalch"           - Programmer
Aileen                   - Graphic Designer
Kilian "Malloth Rha"     - Musician
Micha                    - Junior Programmer
Using Libraries: Pixi.js and Howler.js
date: 16.04.2016 for LD35
theme: Shapeshift
*/

/*

STRING OF EVENTS:
1. Intro Comic (3 Pictures)
    - socks come to life when unattended
2. Under the bed
    2.1. game
        - avoid hands
    2.2. more story
        - grey sock tells hero to fight sewer monster
3. Sewerfall
    3.1. game
        - falling in the sewer
        - avoid dirt
    3.2. reward (grow arms)
        - if not too dirty
4. Snake game
    4.1. game
        - eat fluff
    4.2. reward (grow bigger)
        - if player ate more than 20 fluff in 30 sec.
5. Plumbing game
    5.1. game
        - turn tiles to connect pipes
    5.2. reward (grow hair)
        - did it in 15 seconds
### Optional ###
0. Platforming game
    0.1. game
    0.2. reward (grow wings)
################
6. Doodle Jump
    6.1. game
        - collect something to gain height
    6.2. more story
        - if won grabbed by sock-hand
        - else falling = losing health
7. Boss fight
    - attack in turns
*/

// Cheat Sheet: https://github.com/mtib/ludum34/blob/master/game.js

// Canvas Size
const WIDTH = 1280;
const HEIGHT = 720;

// Current version
const version = "0.01d"

// Initialize Renderer
var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, {antialiasing: true, transparent: false, resolution: 1});
renderer.backgroundColor = 0x6ec2cb;
document.getElementById("gamediv").appendChild(renderer.view);

// Master Containter
var stage = new PIXI.Container();

// Layers
var cBack = new PIXI.Container();
var cMiddle = new PIXI.Container();
var cFront = new PIXI.Container();
var cGui = new PIXI.Container();

// Config goes here:
const fontConfig = {font: "30px 'Arial'", fill: "#000000", align: "left"};
const debugConfig = {font: "20px 'Fira Code',monospace,sans-serif", fill: "#FF0000", align: "left"};
const relcenter = {x:0.5,y:0.5};
const nKey = keyboard(78);
const enterKey = keyboard(13);

const leftArrow = keyboard(37);
const upArrow = keyboard(38);
const rightArrow = keyboard(39);
const downArrow = keyboard(40);

const aKey = keyboard(65);
const wKey = keyboard(87);
const dKey = keyboard(68);
const sKey = keyboard(83);

const s000bed1 = "./scenes/000/bed.pic1.jpg";
const s000bed2 = "./scenes/000/bed.pic2.jpg";
const s001bg = "./scenes/001/background.jpg"; // background for game #1
const ssock = "./scenes/001/sock.png"; // normal sock, for use in all? scenes
const s001armo = "./scenes/001/arm.open.png"; // o = open
const s001armg = "./scenes/001/arm.sock.png"; // g = grabbed

const sceneMusic = [
    new Howl({
        src: ['scenes/000/SockventureIntro.ogg'],
        loop: true,
        volume: 0.4,
    }),
    new Howl({
        src: ['scenes/001/SockventureHand.ogg'],
        loop: true,
        volume: 0.4,
    })
];

function Game1Sock() {
    self = this;
    size = 128 // Pixel
    speed = 3 // Pixel / Frame
    this.sprite = new PIXI.Sprite.fromImage(ssock);
    this.sprite.anchor = relcenter;
    this.sprite.width = size;
    this.sprite.height = size;
    this.sprite.position = {x: WIDTH*0.5, y: HEIGHT*0.5};
    this.die = function() {
        cMiddle.removeChild(this.sprite);
    }
    this.move = function() {
        delta = {x:0, y:0};
        did = false;
        if ((rightArrow.isDown || dKey.isDown) && this.sprite.position.x < WIDTH - 70) {
            delta.x += speed;
        }
        if ((leftArrow.isDown || aKey.isDown) && this.sprite.position.x > 70) {
            delta.x -= speed;
        }
        if ((upArrow.isDown || wKey.isDown) && this.sprite.position.y > 230) {
            delta.y -= speed;
        }
        if ((downArrow.isDown || sKey.isDown) && this.sprite.position.y < HEIGHT - 100) {
            delta.y += speed;
        }
        magsqr = Math.sqrt(Math.abs(delta.x) + Math.abs(delta.y))
        if (magsqr == 0) {
            return;
        }
        if (delta.x > 0 && this.sprite.scale.x > 0) {
            this.sprite.scale.x *= -1;
        } else if (delta.x < 0 && this.sprite.scale.x < 0) {
            this.sprite.scale.x *= -1;
        }
        delta.x /= magsqr;
        delta.y /= magsqr;
        this.sprite.position.x += delta.x;
        this.sprite.position.y += delta.y;
    }
    cMiddle.addChild(this.sprite);
    console.log("stuff should happen");
}

function State() {
    self = this;
    this.debugText = new PIXI.Text("Version: "+version+"\n<Debug Information>\nState: ",debugConfig);
    this.debugText.position = {x:5,y:5};
    this.debugStateText = new PIXI.Text("0", debugConfig);
    this.debugStateText.position = {x:89,y:45};

    this.doc = {}; // DestroyOnChange

    cGui.addChild(this.debugText);
    cGui.addChild(this.debugStateText);
    this.number = 0;
    sceneMusic[0].play();
    this.run = function(){
        console.log("default state");
    }

    this.nextState = function(){
        for (var sprite in this.doc) {
            if (this.doc.hasOwnProperty(sprite)) {
                if (this.doc[sprite].die) {
                    this.doc[sprite].die();
                } else {
                    cBack.removeChild(this.doc[sprite]);
                }
            }
        }
        sceneMusic[this.number++].stop();
        sceneMusic[this.number].play();
        this.switched = true;
        this.debugStateText.text = this.number;
        this.run = this.funcarray[this.number];
    }
    this.substate = 0;
    this.introfunc = function(){
        if (this.switched){
            this.substate = 1;
            this.doc["s000bed1"] = PIXI.Sprite.fromImage(s000bed1);
            this.doc["s000bed2"] = PIXI.Sprite.fromImage(s000bed2);

            this.doc["s000bed1"].width = WIDTH;
            this.doc["s000bed1"].height = HEIGHT;
            this.doc["s000bed2"].width = WIDTH;
            this.doc["s000bed2"].height = HEIGHT;

            cBack.addChild(this.doc["s000bed1"]);

            this.switched = false;
        }
    }
    nKey.press = function(){
        console.log(self.number, self.substate);
        if (self.number === 0){
            if (self.substate == 2){
                self.nextState();
            }else{
                cBack.removeChild(self.doc["s000bed"+self.substate++]);
                cBack.addChild(self.doc["s000bed"+self.substate]);
            }
        }
    }
    this.switched = true;
    this.underTheBed = function(){
        if (this.switched) {
            this.doc["s001bg"] = PIXI.Sprite.fromImage(s001bg);
            this.doc["s001armo"] = PIXI.Sprite.fromImage(s001armo);
            this.doc["s001armg"] = PIXI.Sprite.fromImage(s001armg);

            this.doc["s001bg"].width = WIDTH;
            this.doc["s001bg"].height = HEIGHT;
            cBack.addChild(this.doc["s001bg"]);
            this.doc["gamesock"] = new Game1Sock();

            this.switched = false;
        }
        this.doc["gamesock"].move();
    }
    this.funcarray = [this.introfunc, this.underTheBed];

    this.run = this.funcarray[this.number];
}

var gamestate = new State();

/*
    stage
      |
      +-- cBack
      +-- cMiddle
      +-- cFront
      +-- cGui
Drawn from top to bottom
*/
stage.addChild(cBack);
stage.addChild(cMiddle);
stage.addChild(cFront);
stage.addChild(cGui);

PIXI.loader
    .add(s001bg)
    .add(s001armg)
    .add(s001armo)
    .add(ssock)
    .load(setup);

function setup(){
    // Do setup here
    // Easteregg: eyes!¬
    renderStage();
}

// Request Animation Frame
function renderStage(){
    requestAnimationFrame(renderStage);
    gameLoop();
    renderer.render(stage);
}

// Called before rendering
function gameLoop(){
    // after doing logic:
    gamestate.run()
}

// start game
setup();
<|endoftext|>


<commit_before>/*
 1)      car   speedometer = 0;
 2)   Object    car  :
 setSpeedometer,    speedometer ()
 getSpeedometer,    speedometer ()
 clearSpeedometr,    speedometer
 3)    ,     :
 car.setSpeed(200).setSpeed(300).getSpeed().clearSpeed() //
 */

var car = {
 speedometer: 0
};

Object.defineProperties(car, {
 setSpeed: {
  set: function(value) {
   this.speedometer = value;
   console.log(this.speedometer);
   return this;
  }
 },

 getSpeed: {
  get: function() {
   console.log(this.speedometer);
   return this;
  }
 },

 clearSpeed: {
  set: function() {
   this.speedometer = 0;
   console.log(this.speedometer)
   return this;
  }
 }
});

//car.setSpeed(200).setSpeed(300).getSpeed().clearSpeed();
car.setSpeed(200);<commit_msg>Working version<commit_after>/*
 1)      car   speedometer = 0;
 2)   Object    car  :
 setSpeedometer,    speedometer ()
 getSpeedometer,    speedometer ()
 clearSpeedometr,    speedometer
 3)    ,     :
 car.setSpeed(200).setSpeed(300).getSpeed().clearSpeed() //
 */

var car = {
 speedometer: 0
};

Object.defineProperties(car, {
 setSpeed: {
  value: function(value) {
   this.speedometer = value;
   //console.log(this.speedometer);
   return this;
  },
  enumerable: true
 },

 getSpeed: {
  value: function() {
   console.log(this.speedometer);
   return this;
  },
  enumerable: true
 },

 clearSpeed: {
  value: function() {
   this.speedometer = 0;
   //console.log(this.speedometer)
   return this;
  },
  enumerable: true
 }
});

car.setSpeed(200).setSpeed(300).getSpeed().clearSpeed();
console.dir(car);<|endoftext|>


<commit_before>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.5 - Developed by d4rkd0s & d3mn5pwn ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.CANVAS, '', { preload: preload, create: create, update: update, render: render });
    function preload() {
        //setting up starting vars
        apple_count = 1;
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        horseHealth = 10;
        console.log("%c   horseHealth: 10   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        speed = 250;
        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('tree', 'assets/images/tree.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.audio('applesound', 'assets/sounds/apple.wav');
        game.load.audio('bobsound', 'assets/sounds/bob.wav')
        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects

        apple = game.add.sprite(100, 200, 'apple');

        // Stretch to fill
        game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT;

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        applesound = game.add.audio('applesound');
        applesound.allowMultiple = true;

        bobsound = game.add.audio('bobsound');
        bobsound.allowMultiple = true;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        tree = game.add.sprite(450, 30, 'tree');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //add player
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        horse.anchor.x = 0.5;
        horse.anchor.y = 0.5;

    game.scale.enterFullScreen.add(onEnterFullScreen, this);
    game.scale.leaveFullScreen.add(onLeaveFullScreen, this);

    game.input.onDown.add(gofull, this);

    //prime that apple
    apple.kill();
    }//create

    function onEnterFullScreen() {

        button.visible = true;

    }

    function onLeaveFullScreen() {

        button.visible = false;

    }

    function gofull() {

        game.scale.startFullScreen();

    }

    function update() {
        apple.bringToTop();
        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);
        game.physics.arcade.collide(ocean, apple);
        game.physics.arcade.collide(horse, ocean);
        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        //bob faster as he scores
        speed = 200+(10*score);

        //move mr.horse
        horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50+(score*5), 50+(score*5), 50+(score*5));

        if ( player.y < 250 ) {
            tree.bringToTop();
            apple.bringToTop();
        }
        else{
            player.bringToTop();
        }

        if ( apple.alive == true){
            if ( game.physics.arcade.overlap(apple, player) == true ){
                score = score + 1;
                bobsound.play();
                $( "#score" ).text("Score: " + score);
                apple.kill();
                console.log("Score: " + score);
            }
            if ( game.physics.arcade.collide(apple, horse) == true ){
                horseHealth = horseHealth - 1;
                if ( horseHealth == 1 ){
                    $( "#horseHealth" ).text(horseHealth + " apple until your horse dies!");
                }
                else{
                    $( "#horseHealth" ).text(horseHealth + " apples until your horse dies!");
                }
                applesound.play();
                apple.kill();
                if ( horseHealth == 0 ){
                    $( "#score" ).text("Final Score: " + score);
                    $( "#horseHealth" ).text("Your horse has died!");
                    game.debug.text('Retry? (Refresh the page)', (game.width/2)-140, game.height/2);
                    game.physics.destroy();
                }
                console.log("horseHealth: " + horseHealth);
            }
        }//apple alive
        else{
            if ( apple_count > 0 ){
                randX = Math.floor(Math.random()*(650-600+1)+600);
                randY = Math.floor(Math.random()*(190-90+1)+90);
                if ( game.physics.arcade.overlap(apple, horse) == true ){
                    console.log("Apple spawned on horse, regenerating randX and randY");
                    randX = Math.floor(Math.random()*(650-600+1)+600);
                    randY = Math.floor(Math.random()*(190-90+1)+90);
                    apple.kill();
                }
                else{
                    console.log("Apple is clear of horse, spawned apple.");
                    apple = game.add.sprite(randX, randY, 'apple');
                    game.physics.arcade.enable(apple);
                    game.physics.arcade.enableBody(apple);
                    apple.body.collideWorldBounds = true;
                    game.physics.arcade.collide(player, apple);
                    game.physics.arcade.collide(ocean, apple);
                }
            }//apple_count isnt 0
            else {
                console.log("apple count is now zero!");
                game.debug.text('Retry? (Refresh the page)', (game.width/2)-140, game.height/2);
                game.physics.destroy();
            }//apple count is 0
        }//dead apple

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -speed*2;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = speed*2;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -speed;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = speed;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

function render () {

    if (game.scale.isFullScreen)
    {
        game.debug.text('ESC to leave fullscreen', (game.width/2)-140, 60);
    }
    else
    {
        game.debug.text('Click / Tap to go fullscreen', (game.width/2)-140, 16);
    }

}
};
});<commit_msg>Leet Hacks<commit_after>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.5 - Developed by d4rkd0s & d3mn5pwn ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.CANVAS, '', { preload: preload, create: create, update: update, render: render });
    function preload() {
        //setting up starting vars
        apple_count = 1;
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        horseHealth = 10;
        console.log("%c   horseHealth: 10   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        speed = 250;
        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('tree', 'assets/images/tree.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.audio('applesound', 'assets/sounds/apple.wav');
        game.load.audio('bobsound', 'assets/sounds/bob.wav')
        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects

        apple = game.add.sprite(100, 200, 'apple');

        // Stretch to fill
        game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT;

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        applesound = game.add.audio('applesound');
        applesound.allowMultiple = true;

        bobsound = game.add.audio('bobsound');
        bobsound.allowMultiple = true;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        tree = game.add.sprite(450, 30, 'tree');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //add player
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        horse.anchor.x = 0.5;
        horse.anchor.y = 0.5;

    game.scale.enterFullScreen.add(onEnterFullScreen, this);
    game.scale.leaveFullScreen.add(onLeaveFullScreen, this);

    game.input.onDown.add(gofull, this);

    //prime that apple
    apple.kill();
    }//create

    function onEnterFullScreen() {

        button.visible = true;

    }

    function onLeaveFullScreen() {

        button.visible = false;

    }

    function gofull() {

        game.scale.startFullScreen();

    }

    function update() {
        apple.bringToTop();
        //ocean collision
        //game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);
        game.physics.arcade.collide(ocean, apple);
        game.physics.arcade.collide(horse, ocean);
        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        //bob faster as he scores
        speed = 200+(10*score);

        //move mr.horse
        horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50+(score*5), 50+(score*5), 50+(score*5));

        if ( player.y < 250 ) {
            tree.bringToTop();
            apple.bringToTop();
        }
        else{
            player.bringToTop();
        }

        if ( apple.alive == true){
            if ( game.physics.arcade.overlap(apple, player) == true ){
                score = score + 1;
                bobsound.play();
                $( "#score" ).text("Score: " + score);
                apple.kill();
                console.log("Score: " + score);
            }
            if ( game.physics.arcade.collide(apple, horse) == true ){
                horseHealth = horseHealth - 1;
                if ( horseHealth == 1 ){
                    $( "#horseHealth" ).text(horseHealth + " apple until your horse dies!");
                }
                else{
                    $( "#horseHealth" ).text(horseHealth + " apples until your horse dies!");
                }
                applesound.play();
                apple.kill();
                if ( horseHealth == 0 ){
                    $( "#score" ).text("Final Score: " + score);
                    $( "#horseHealth" ).text("Your horse has died!");
                    game.debug.text('Retry? (Refresh the page)', (game.width/2)-140, game.height/2);
                    game.physics.destroy();
                }
                console.log("horseHealth: " + horseHealth);
            }
        }//apple alive
        else{
            if ( apple_count > 0 ){
                randX = Math.floor(Math.random()*(650-600+1)+600);
                randY = Math.floor(Math.random()*(190-90+1)+90);

                console.log("Apple is clear of horse, spawned apple.");
                apple = game.add.sprite(randX, randY, 'apple');
                game.physics.arcade.enable(apple);
                game.physics.arcade.enableBody(apple);
                apple.body.collideWorldBounds = true;
                game.physics.arcade.collide(player, apple);
                game.physics.arcade.collide(ocean, apple);
            }//apple_count isnt 0
            else {
                console.log("apple count is now zero!");
                game.debug.text('Retry? (Refresh the page)', (game.width/2)-140, game.height/2);
                game.physics.destroy();
            }//apple count is 0
        }//dead apple

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -speed*2;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = speed*2;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -speed;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = speed;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

function render () {

    if (game.scale.isFullScreen)
    {
        game.debug.text('ESC to leave fullscreen', (game.width/2)-140, 60);
    }
    else
    {
        game.debug.text('Click / Tap to go fullscreen', (game.width/2)-140, 16);
    }

}
};
});<|endoftext|>


<commit_before>angular.module('redash', [
    'redash.directives',
    'redash.admin_controllers',
    'redash.controllers',
    'redash.filters',
    'redash.services',
    'redash.visualization',
    'plotly',
    'plotly-chart',
    'angular-growl',
    'angularMoment',
    'ui.bootstrap',
    'ui.sortable',
    'smartTable.table',
    'ngResource',
    'ngRoute',
    'ui.select',
    'naif.base64',
    'ui.bootstrap.showErrors',
    'ngSanitize'
  ]).config(['$routeProvider', '$locationProvider', '$compileProvider', 'growlProvider', 'uiSelectConfig',
    function ($routeProvider, $locationProvider, $compileProvider, growlProvider, uiSelectConfig) {
      function getQuery(Query, $route) {
        var query = Query.get({'id': $route.current.params.queryId });
        return query.$promise;
      };

      uiSelectConfig.theme = "bootstrap";

      $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|http|data):/);
      $locationProvider.html5Mode(true);
      growlProvider.globalTimeToLive(2000);

      $routeProvider.when('/embed/query/:queryId/visualization/:visualizationId', {
        templateUrl: '/views/visualization-embed.html',
        controller: 'EmbedCtrl',
        reloadOnSearch: false
      });
      $routeProvider.otherwise({
        redirectTo: '/embed'
      });

    }
  ])
   .controller('EmbedCtrl', ['$scope', function ($scope) {} ])
   .controller('EmbeddedVisualizationCtrl', ['$scope', 'Query', 'QueryResult',
    function ($scope, Query, QueryResult) {
       $scope.embed = true;
       $scope.visualization = visualization;
       $scope.query = visualization.query;
       query = new Query(visualization.query);
       $scope.queryResult = new QueryResult({query_result:query_result});
    } ])
   ;
<commit_msg>Fix: embeds got broken due to missing inject<commit_after>angular.module('redash', [
    'redash.directives',
    'redash.admin_controllers',
    'redash.controllers',
    'redash.filters',
    'redash.services',
    'redash.visualization',
    'plotly',
    'angular-growl',
    'angularMoment',
    'ui.bootstrap',
    'ui.sortable',
    'smartTable.table',
    'ngResource',
    'ngRoute',
    'ui.select',
    'naif.base64',
    'ui.bootstrap.showErrors',
    'ngSanitize'
  ]).config(['$routeProvider', '$locationProvider', '$compileProvider', 'growlProvider', 'uiSelectConfig',
    function ($routeProvider, $locationProvider, $compileProvider, growlProvider, uiSelectConfig) {
      function getQuery(Query, $route) {
        var query = Query.get({'id': $route.current.params.queryId });
        return query.$promise;
      };

      uiSelectConfig.theme = "bootstrap";

      $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|http|data):/);
      $locationProvider.html5Mode(true);
      growlProvider.globalTimeToLive(2000);

      $routeProvider.when('/embed/query/:queryId/visualization/:visualizationId', {
        templateUrl: '/views/visualization-embed.html',
        controller: 'EmbedCtrl',
        reloadOnSearch: false
      });
      $routeProvider.otherwise({
        redirectTo: '/embed'
      });

    }
  ])
   .controller('EmbedCtrl', ['$scope', function ($scope) {} ])
   .controller('EmbeddedVisualizationCtrl', ['$scope', 'Query', 'QueryResult',
    function ($scope, Query, QueryResult) {
       $scope.embed = true;
       $scope.visualization = visualization;
       $scope.query = visualization.query;
       query = new Query(visualization.query);
       $scope.queryResult = new QueryResult({query_result:query_result});
    } ])
   ;
<|endoftext|>


<commit_before>'use strict';

var charImgTopLeft = document.getElementById('char-img-top-left');
var charImgTopRight = document.getElementById('char-img-top-right');
var charImgBtmLeft = document.getElementById('char-img-btm-left');
var charImgBtmRight = document.getElementById('char-img-btm-right');
var gameboard = document.getElementById('gameboard');
var roundHeader = document.getElementById('round-header');
var clicksInRound = document.getElementById('clicks-in-round');
var nextRoundButton = document.getElementById('next-round-button');

var clickCount = 0;
var round = 1;
var positionArray = [];

function playRound(){
  roundHeader.textContent = 'Round ' + round;
  clicksInRound.textContent = 'Click Count: ' + clickCount + ' / ' + round;

  var randomPosition = getRandomPosition();
  if (randomPosition === 0){
    positionArray.push(charImgTopLeft);
  }
  if (randomPosition === 1){
    positionArray.push(charImgTopRight);
  }
  if (randomPosition === 2){
    positionArray.push(charImgBtmLeft);
  }
  if (randomPosition === 3){
    positionArray.push(charImgBtmRight);
  }
  renderPositionArray(positionArray, 250, 150);
  gameboard.addEventListener('click', handleUserClick);
  nextRoundButton.addEventListener('click', playRound);
}

function getRandomPosition() {
  var min = Math.ceil(0);
  var max = Math.floor(3);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function renderPosition(position, timeToShow, timeToHide) {
  window.setTimeout(function(){
    position.style.display = 'inline-block';
  }, timeToHide);
  window.setTimeout(function(){
    position.style.display = 'none';
  }, timeToShow);
}

function renderPositionArray(array, showTime, hideTime){
  for (var i = 0; i < array.length; i++){
    renderPosition(array[i], (showTime * (i + 1)) + (hideTime * i), (showTime + hideTime) * i);
  }
}

playRound();

function handleUserClick(event) {
  event.preventDefault();

  var userSelection;

  if (event.target.id === 'img-top-left') {
    userSelection = 'char-img-top-left';
  }
  if (event.target.id === 'img-top-right') {
    userSelection = 'char-img-top-right';
  }
  if (event.target.id === 'img-btm-left') {
    userSelection = 'char-img-btm-left';
  }
  if (event.target.id === 'img-btm-right') {
    userSelection = 'char-img-btm-right';
  }

  if (userSelection === positionArray[clickCount].id) {
    clickCount += 1;
    clicksInRound.textContent = 'Click Count: ' + clickCount + ' / ' + round;

  } else {
    console.log('user lose');
    //write userLose() function
    clickCount = 0;
  }

  if (clickCount === positionArray.length) {
    round += 1;
    console.log('round: ' + round);
    clickCount = 0;
    console.log('user win');
    // playRound();
    //write userWin() function
    // return userWin();
  }

  console.log(clickCount);
}
<commit_msg>implemented removed event listeners<commit_after>'use strict';

var charImgTopLeft = document.getElementById('char-img-top-left');
var charImgTopRight = document.getElementById('char-img-top-right');
var charImgBtmLeft = document.getElementById('char-img-btm-left');
var charImgBtmRight = document.getElementById('char-img-btm-right');
var gameboard = document.getElementById('gameboard');
var roundHeader = document.getElementById('round-header');
var clicksInRound = document.getElementById('clicks-in-round');
var nextRoundButton = document.getElementById('next-round-button');

var clickCount = 0;
var round = 1;
var positionArray = [];

function playRound(){
  roundHeader.textContent = 'Round ' + round;
  clicksInRound.textContent = 'Click Count: ' + clickCount + ' / ' + round;

  var randomPosition = getRandomPosition();
  if (randomPosition === 0){
    positionArray.push(charImgTopLeft);
  }
  if (randomPosition === 1){
    positionArray.push(charImgTopRight);
  }
  if (randomPosition === 2){
    positionArray.push(charImgBtmLeft);
  }
  if (randomPosition === 3){
    positionArray.push(charImgBtmRight);
  }
  renderPositionArray(positionArray, 250, 150);
  gameboard.addEventListener('click', handleUserClick);
  nextRoundButton.addEventListener('click', playRound);
}

function getRandomPosition() {
  var min = Math.ceil(0);
  var max = Math.floor(3);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function renderPosition(position, timeToShow, timeToHide) {
  window.setTimeout(function(){
    position.style.display = 'inline-block';
  }, timeToHide);
  window.setTimeout(function(){
    position.style.display = 'none';
  }, timeToShow);
}

function renderPositionArray(array, showTime, hideTime){
  for (var i = 0; i < array.length; i++){
    renderPosition(array[i], (showTime * (i + 1)) + (hideTime * i), (showTime + hideTime) * i);
  }
}

function handleUserClick(event) {
  event.preventDefault();

  var userSelection;

  if (event.target.id === 'img-top-left') {
    userSelection = 'char-img-top-left';
  }
  if (event.target.id === 'img-top-right') {
    userSelection = 'char-img-top-right';
  }
  if (event.target.id === 'img-btm-left') {
    userSelection = 'char-img-btm-left';
  }
  if (event.target.id === 'img-btm-right') {
    userSelection = 'char-img-btm-right';
  }

  if (userSelection === positionArray[clickCount].id) {
    clickCount += 1;
    clicksInRound.textContent = 'Click Count: ' + clickCount + ' / ' + round;

  } else {
    console.log('user lose');
    //write userLose() function
    nextRoundButton.removeEventListener('click', playRound);
    gameboard.removeEventListener('click', handleUserClick);
    return clickCount = 0;

  }

  if (clickCount === positionArray.length) {
    round += 1;
    console.log('round: ' + round);
    clickCount = 0;
    console.log('user win');
    gameboard.removeEventListener('click', handleUserClick);
    // playRound();
    //write userWin() function
    // return userWin();
  }

  console.log(clickCount);
}

//Function Calls
playRound();
<|endoftext|>


<commit_before>window.onload = function(){
    var canvas = document.getElementById('board');
    var context = canvas.getContext('2d');
    var brickWidth = 60;
    var brickMargin = 10;
    var objects;
    var ball;
    var player;

    canvas.width = 1024;
    canvas.height = 576;

    // Talking about closures, anything that was declared outside of a function is accessible by it.
    function resetContextStyle(){
      context.fillStyle = 'black';
      context.strokeStyle = 'black';
    }

    function createBall(){
      return {
        x: canvas.width / 2,
        y: canvas.height - 50,
        radius: 10,
        speedx: 0,
        speedy: 0,
        // Talking about attaching functions to objects and using "this"
        render: function(){
          context.beginPath();
          context.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
          context.fill();
        },
        checkWallCollision: function(axis, boundry){
          // Talking about objects as dictionaries
          if(this[axis] + this.radius >= boundry){
            this[axis] = boundry - this.radius;
            this['speed' + axis] = -this['speed' + axis];
          }
          else if(this[axis] - this.radius <= 0){
            this[axis] = this.radius;
            this['speed' + axis] = -this['speed' + axis];
          }
        },
        checkCollision: function(object){
          function between(center, range, min, max){
            return (center - range >= min && center - range <= max) ||
                   (center + range >= min && center + range <= max);
          }

          // Check that either the top or bottom part of the ball are between the top and bottom of the player.
          // And that the left and right of the ball are between the left and right of the player.
          if(between(this.y, this.radius, object.top(), object.bottom()) &&
             between(this.x, this.radius, object.left(), object.right())){
               var normalizedSpeedX = Math.floor((this.x - object.x) * 20 / (this.radius + object.width / 2));

               // Talking about calling functions on objects.
               this.setSpeed(normalizedSpeedX, -this.speedy);
               object.collidedWithBall();
          }
        },
        update: function(){
          this.x += this.speedx;
          this.y += this.speedy;
          this.checkWallCollision('x', canvas.width);
          this.checkWallCollision('y', canvas.height);

          // Talking about context, and what happens to callbacks and their context.
          var actualBall = this;

          objects.forEach(function(object){
            // Talking about the equality operator
            if(object !== actualBall){
              actualBall.checkCollision(object);
            }
          });
        },
        setSpeed: function(x, y){
          this.speedx = x;
          this.speedy = y;
        }
      };
    }

    function createPlayer() {
      return {
        x: canvas.width / 2,
        y: canvas.height - 40,
        width: 80,
        height: 10,
        speedX: 0,
        render: function(){
          context.fillRect(this.x - this.width / 2, this.y, this.width, this.height);
        },
        bottom: function(){
          return this.y + this.height;
        },
        top: function(){
          return this.y;
        },
        left: function(){
          return this.x - this.width / 2;
        },
        right: function(){
          return this.x + this.width / 2;
        },
        update: function(){
          this.x += this.speedX;

          if(this.x + this.width / 2 >= canvas.width){
            this.x = canvas.width - this.width / 2;
            this.setSpeed(0);
          }

          if(this.x - this.width / 2 <= 0){
            this.x = this.width / 2;
            this.setSpeed(0);
          }
        },
        setSpeed: function(x){
          this.speedX = x;
        },
        collidedWithBall: function(){ }
      };
    }

    function createBrick(x, y){
      return {
          R: Math.floor(Math.random() * 255),
          G: Math.floor(Math.random() * 255),
          B: Math.floor(Math.random() * 255),
          x: x,
          y: y,
          width: 60,
          height: 20,
          bottom: function(){
            return this.y + this.height;
          },
          top: function(){
            return this.y;
          },
          left: function(){
            return this.x - this.width / 2;
          },
          right: function(){
            return this.x + this.width / 2;
          },
          render: function(){
            var R = Math.floor(Math.random() * 255);
            var G = Math.floor(Math.random() * 255);
            var B = Math.floor(Math.random() * 255);
            var randomizeColor = false;

            if(randomizeColor){
              context.fillStyle = 'rgb(' + R + ',' + G + ',' + B + ')';
            }
            else {
              context.fillStyle = 'rgb(' + this.R + ',' + this.G + ',' + this.B + ')';
            }

            context.fillRect(this.x - this.width / 2, this.y, this.width, this.height);
            resetContextStyle();
          },
          collidedWithBall: function(){
            objects.splice(objects.indexOf(this), 1);
          },
          update: function(){}
      };
    }

    function clearCanvas(){
      context.fillStyle = 'white';
      context.fillRect(0, 0, canvas.width, canvas.height);
      resetContextStyle();
      context.strokeRect(0, 0, canvas.width, canvas.height);
    }

    function refresh(){
      clearCanvas();
      objects.forEach(function(object){
        object.render();
        object.update();
      });
    }

    var hasStarted = false;
    var frictionHandler;
    function clearFrictionHandler(){
      clearInterval(frictionHandler);
      frictionHandler = undefined;
    }

    // Talking about objects as dictionaries - continue.
    // Since it's a dictionary, a number is also acceptable.
    var actions = {
      // Left (37 - Right arrow)
      37: function(){
        if(hasStarted){
          player.setSpeed(player.speedX - 3);
          clearFrictionHandler();
        }
      },
      // Right (39 - Right arrow)
      39: function(){
        if(hasStarted){
          player.setSpeed(player.speedX + 3);
          clearFrictionHandler();
        }
      },
      // Start game (13 - Enter)
      13: function(){
        if(!hasStarted){
          ball.setSpeed(0, -10);
          hasStarted = true;
        }
      }
    };

    // 32 - Space
    actions[32] = actions[13];

    // Talking about event driven development
    window.addEventListener('keydown', function(event){
        // Talking about "truthy" and "falsy" values
        (actions[event.keyCode] || function(){})();
    });

    window.addEventListener('keyup', function(){
        if(!frictionHandler){
          frictionHandler = setInterval(function(){
            if(player.speedX === 0){
              clearFrictionHandler();
              return;
            }
            player.setSpeed(player.speedX > 0 ? player.speedX - 1 : player.speedX + 1);
          });
        }
    });

    var gameLoop;

    function init(){
      ball = createBall();
      player = createPlayer();
      objects = [ball, player];

      for(var brickIndex = 1; brickIndex < 104; brickIndex++){
        var x = -60 + (brickIndex * (brickWidth + brickMargin)) % canvas.width;
        if(x < brickWidth + brickMargin || canvas.width - x < brickWidth + brickMargin){
          continue;
        }
        var y = 30 + Math.floor((brickIndex * (brickWidth + brickMargin)) / canvas.width) * 30;
        objects.push(createBrick(x, y))
      }

      if (gameLoop){
        clearInterval(gameLoop);
      }

      // Talking about using functions as objects, it's basically a pointer object to a function.
      // Also talking about the event loop and one thread and a-synchronicity
      gameLoop = setInterval(refresh, 40);
    }

    init();
}
<commit_msg>Implement lives and game end<commit_after>window.onload = function(){
    var canvas = document.getElementById('board');
    var context = canvas.getContext('2d');
    var hasStarted = false;
    var brickWidth = 60;
    var brickMargin = 10;
    var playerBaseLine = 50;
    var ballRadius = 10;
    var lives = [];
    var bricks = [];
    var boardWidth;
    var boardHeight;
    var objects;
    var ball;
    var player;
    var frictionHandler;
    var gameLoopHandler;

    canvas.width = 1024;
    canvas.height = 576;

    boardHeight = canvas.height - 50;
    boardWidth = canvas.width;

    // Talking about closures, anything that was declared outside of a function is accessible by it.
    function resetContextStyle(){
      context.fillStyle = 'black';
      context.strokeStyle = 'black';
    }

    function removeFrom(array, index){
      objects.splice(objects.indexOf(array[index]), 1);
      array.splice(index, 1);
    }

    function createBall(){
      return {
        x: boardWidth / 2,
        y: boardHeight - playerBaseLine,
        radius: ballRadius,
        speedx: 0,
        speedy: 0,
        // Talking about attaching functions to objects and using "this"
        render: function(){
          context.beginPath();
          context.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
          context.fill();
        },
        checkWallCollision: function(axis, boundry){
          // Talking about objects as dictionaries
          if(this[axis] + this.radius >= boundry){
            this[axis] = boundry - this.radius;
            this['speed' + axis] = -this['speed' + axis];
          }
          else if(this[axis] - this.radius <= 0){
            this[axis] = this.radius;
            this['speed' + axis] = -this['speed' + axis];
          }
        },
        checkCollision: function(object){
          function between(center, range, min, max){
            return (center - range >= min && center - range <= max) ||
                   (center + range >= min && center + range <= max);
          }

          // Check that either the top or bottom part of the ball are between the top and bottom of the player.
          // And that the left and right of the ball are between the left and right of the player.
          if(between(this.y, this.radius, object.top(), object.bottom()) &&
             between(this.x, this.radius, object.left(), object.right())){
               var normalizedSpeedX = Math.floor((this.x - object.x) * 20 / (this.radius + object.width / 2));

               // Talking about calling functions on objects.
               this.setSpeed(normalizedSpeedX, -this.speedy);
               object.collidedWithBall();
          }
        },
        update: function(){
          if(!hasStarted)
            return;

          this.x += this.speedx;
          this.y += this.speedy;

          if(this.y - this.radius * 2 > boardHeight - playerBaseLine){
            removeFrom(lives, lives.length - 1);

            if(lives.length !== 0){
              resetPlayerAndBall(lives.length);
            }
            else{
              alert('Game Over');
              init();
            }
          }

          this.checkWallCollision('x', boardWidth);
          this.checkWallCollision('y', boardHeight);

          // Talking about context, and what happens to callbacks and their context.
          var actualBall = this;

          objects.forEach(function(object){
            // Talking about the equality operator
            if(object !== actualBall && object.isInBoard){
              actualBall.checkCollision(object);
            }
          });

          if(bricks.length === 0){
            alert('You won!');
          }
        },
        setSpeed: function(x, y){
          this.speedx = x;
          this.speedy = y;
        }
      };
    }

    function createPlayer() {
      return {
        x: boardWidth / 2,
        y: boardHeight - (playerBaseLine - ballRadius),
        width: 100,
        height: 10,
        speedX: 0,
        isInBoard: true,
        render: function(){
          context.fillRect(this.x - this.width / 2, this.y, this.width, this.height);
        },
        bottom: function(){
          return this.y + this.height;
        },
        top: function(){
          return this.y;
        },
        left: function(){
          return this.x - this.width / 2;
        },
        right: function(){
          return this.x + this.width / 2;
        },
        update: function(){
          this.x += this.speedX;

          if(this.x + this.width / 2 >= boardWidth){
            this.x = boardWidth - this.width / 2;
            this.setSpeed(0);
          }

          if(this.x - this.width / 2 <= 0){
            this.x = this.width / 2;
            this.setSpeed(0);
          }
        },
        setSpeed: function(x){
          if(x !== 0){
            var direction = Math.abs(x)/x;
            this.speedX = Math.floor(Math.min(Math.abs(x), 35)) * direction;
          }
          else{
            this.speedX = 0;
          }
        },
        collidedWithBall: function(){ }
      };
    }

    function createBrick(x, y){
      return {
          R: Math.floor(Math.random() * 255),
          G: Math.floor(Math.random() * 255),
          B: Math.floor(Math.random() * 255),
          x: x,
          y: y,
          width: 60,
          height: 20,
          isInBoard: true,
          bottom: function(){
            return this.y + this.height;
          },
          top: function(){
            return this.y;
          },
          left: function(){
            return this.x - this.width / 2;
          },
          right: function(){
            return this.x + this.width / 2;
          },
          render: function(){
            var R = Math.floor(Math.random() * 255);
            var G = Math.floor(Math.random() * 255);
            var B = Math.floor(Math.random() * 255);
            var randomizeColor = false;

            if(randomizeColor){
              context.fillStyle = 'rgb(' + R + ',' + G + ',' + B + ')';
            }
            else {
              context.fillStyle = 'rgb(' + this.R + ',' + this.G + ',' + this.B + ')';
            }

            context.fillRect(this.x - this.width / 2, this.y, this.width, this.height);
            resetContextStyle();
          },
          collidedWithBall: function(){
            removeFrom(bricks, bricks.indexOf(this));
          },
          update: function(){}
      };
    }

    function createHeart(x){
      return {
        x: x,
        y: boardHeight + 10,
        isInBoard: false,
        render: function(){
          // Talking about arrays and multi-dimensional arrays are just arrays within arrays.
          var pixels = [['white', 'black', 'black', 'white', 'white', 'white', 'black', 'black', 'white'],
                        ['black', 'red', 'red', 'black', 'white', 'black', 'red', 'red', 'black'],
                        ['black', 'red', 'red', 'red', 'black', 'red', 'red', 'red', 'black'],
                        ['black', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'black'],
                        ['white', 'black', 'red', 'red', 'red', 'red', 'red', 'black', 'white'],
                        ['white', 'white', 'black', 'red', 'red', 'red', 'black', 'white', 'white'],
                        ['white', 'white', 'white', 'black', 'red', 'black', 'white', 'white', 'white'],
                        ['white', 'white', 'white', 'white', 'black', 'white', 'white', 'white', 'white']];
          var heart = this;
          pixels.forEach(function(row, rowIndex){
            row.forEach(function(pixelColor, columnIndex){
              context.fillStyle = pixelColor;
              context.fillRect(heart.x + (columnIndex * 5), heart.y + (rowIndex * 5), 5, 5);
            });
          });

          resetContextStyle();
        },
        update: function(){}
      };
    }

    function clearCanvas(){
      context.fillStyle = 'white';
      context.fillRect(0, 0, canvas.width, canvas.height);
      resetContextStyle();
      context.strokeRect(0, 0, boardWidth, boardHeight);
    }

    function refresh(){
      clearCanvas();
      objects.forEach(function(object){
        object.render();
        object.update();
      });
    }

    function clearFrictionHandler(){
      clearInterval(frictionHandler);
      frictionHandler = undefined;
    }

    // Talking about objects as dictionaries - continue.
    // Since it's a dictionary, a number is also acceptable.
    var actions = {
      // Left (37 - Right arrow)
      37: function(){
        if(hasStarted){
          player.setSpeed(player.speedX - 8);
          clearFrictionHandler();
        }
      },
      // Right (39 - Right arrow)
      39: function(){
        if(hasStarted){
          player.setSpeed(player.speedX + 8);
          clearFrictionHandler();
        }
      },
      // Start game (13 - Enter)
      13: function(){
        if(!hasStarted){
          ball.setSpeed(0, -10);
          hasStarted = true;
        }
      }
    };

    // 32 - Space
    actions[32] = actions[13];

    // Talking about event driven development
    window.addEventListener('keydown', function(event){
        // Talking about "truthy" and "falsy" values and return value from logical operators
        (actions[event.keyCode] || function(){})();
    });

    window.addEventListener('keyup', function(){
        if(!frictionHandler){
          frictionHandler = setInterval(function(){
            if(player.speedX === 0){
              clearFrictionHandler();
              return;
            }
            player.setSpeed(player.speedX > 0 ? player.speedX - 1 : player.speedX + 1);
          }, 5);
        }
    });

    function addBricks(){
        for(var brickIndex = 1; brickIndex < 75; brickIndex++){
          var x = -60 + (brickIndex * (brickWidth + brickMargin)) % boardWidth;

          // Making sure that the brick doesn't exceed the board.
          if(x < brickWidth + brickMargin || boardWidth - x < brickWidth + brickMargin){
            continue;
          }

          var y = 60 + Math.floor((brickIndex * (brickWidth + brickMargin)) / boardWidth) * 30;

          // Talking about arrays, continue - they can act like queues with push/pop functions.
          bricks.push(createBrick(x, y));
          objects.push(bricks[bricks.length - 1]);
        }
    }

    // Talking about function parameters and overloading
    function resetPlayerAndBall(numberOfLives){
      hasStarted = false;
      numberOfLives = numberOfLives || 3;
      ball = createBall();
      player = createPlayer();

      // Talking about arrays, continue - the opposite of pop/push.
      objects.shift();
      objects.shift();
      objects.unshift(player);
      objects.unshift(ball);

      while(lives.length > 0){
        removeFrom(lives, 0);
      }

      for (var life = 0; life < numberOfLives; life++) {
        lives.push(createHeart(life * 50));
        objects.push(lives[lives.length - 1]);
      }
    }

    function init(){
      ball = createBall();
      player = createPlayer();

      // Placeholders for the player and ball.
      objects = [{}, {}];
      resetPlayerAndBall();
      addBricks();

      if (gameLoopHandler){
        clearInterval(gameLoopHandler);
      }

      // Talking about using functions as objects, it's basically a pointer object to a function.
      // Also talking about the event loop and one thread and a-synchronicity
      gameLoopHandler = setInterval(refresh, 40);
    }

    init();
}
<|endoftext|>