factorize event handling

This commit is contained in:
Gwenhael Le Moine 2011-07-14 12:47:10 +02:00
parent 257ff69520
commit 7d2bf35c5a

View file

@ -223,14 +223,12 @@ function initialize_a_star( dom_container ) {
)
{
state = set_cell( item_coord[ 0 ], item_coord[ 1 ], cell.VOID ); /* void the origin cell */
// voiding origin cell on canvas
draw_cell( assets.sprites.void, item_coord[ 0 ], item_coord[ 1 ] );
item_coord[ 0 ] += motion[ 0 ]; /* move coordinate */
item_coord[ 1 ] += motion[ 1 ]; /* to those of target cells */
state = set_cell( item_coord[ 0 ], item_coord[ 1 ], state.moving ); /* move actor into target cell */
// drawing target cell on canvas
draw_cell( ( state.moving == cell.BALL ) ? assets.sprites.ball_selected : assets.sprites.cube_selected, item_coord[ 0 ], item_coord[ 1 ] );
state.distance_travelled++; /* increment distance_travelled */
@ -239,12 +237,8 @@ function initialize_a_star( dom_container ) {
return state;
}
function start_loop( ) {
display_level( );
$(document).focus( );
$(document).click(
function( e ) {
function event_handler( e ) {
if ( e.type === "click" ) {
var movingpos = get_pos( state.moving );
var notmovingpos = get_pos( ( state.moving != cell.BALL ) ? cell.BALL : cell.CUBE );
var click = { };
@ -273,20 +267,8 @@ function initialize_a_star( dom_container ) {
state = make_a_move( direction.LEFT );
}
}
if ( won_or_not( ) ) {
if ( state.level < assets.levels.length - 1 ) {
state = load_level( state.level + 1 );
display_level( );
}
else {
alert( "You won!" );
}
}
}
});
$(document).keydown(
function( e ) {
} else if ( e.type === "keydown" ) {
switch( e.keyCode ) {
case 38: // UP
state = make_a_move( direction.UP );
@ -322,6 +304,7 @@ function initialize_a_star( dom_container ) {
default:
break;
}
}
if ( won_or_not( ) ) {
if ( state.level < assets.levels.length - 1 ) {
@ -332,7 +315,15 @@ function initialize_a_star( dom_container ) {
alert( "You won!" );
}
}
});
}
function start_loop( ) {
display_level( );
$(document).focus( );
$(document).click( event_handler );
$(document).keydown( event_handler );
}
////// MAIN (so to speak) //////