/**
* @author Wolfgang Kowarschick <kowa@hs-augsburg.de>
* @copyright 2017 - 2018
* @license CC-BY-NC-SA-4.0
*/
/**
* @module logic/logic
*/
import {wait} from '/wk/util/wait';
/** @private */
let
v_game_loop, v_start_button, v_ball, v_paddles, v_scores, v_win_score, v_info;
/**
* @function initLogic
* @static
*
* @param {GameLoop} p_game_loop - the game loop
* @param {Object} p_models - the models of the game
* @param {ModelCircle} p_models.startButton - the startButton
* @param {ModelCircle} p_models.ball - the ball
* @param {Array.<ModelPaddle>} p_models.paddles - the two paddles
* @param {Array.<ModelScore>} p_models.scores - the two scores
* @param {ModelText} p_models.info - a text field to display info
* @param {Object} [p_config] - the configuration of the game logic
* @param {number} [p_config.winScore = 10] - the score of the winner
*/
function initLogic(p_game_loop,
{ startButton: p_start_button,
ball: p_ball,
paddles: p_paddles,
scores: p_scores,
info: p_info
},
{ winScore: p_win_score = 10
} = {}
)
{ v_game_loop = p_game_loop;
v_start_button = p_start_button;
v_ball = p_ball;
v_paddles = p_paddles;
v_scores = p_scores;
v_info = p_info;
v_win_score = p_win_score;
v_ball.moveTo(); // move the ball to its start point
v_ball.stop();
v_start_button.reset(); // make the start button visible
v_game_loop.start();
}
/**
* Starts the game.
* Should be called by a controller of a start button or the like.
*/
async function startGame()
{ v_scores[0].score = 0;
v_scores[1].score = 0;
v_start_button.x = -2*v_start_button.r; // move the start button outside
// the stage to make it invisible
await wait(1000);
v_ball.start(); // start the game
}
/**
* @param {string} p_player - the position of the player who lost the ball:
* <code>'left'</code> or <code>'right'</code>
*/
async function ballLoss(p_player)
{ // the score of the other player is raised
const c_player = p_player === 'left' ? 1 : 0;
v_scores[c_player].score++;
if (v_scores[c_player].score === v_win_score) // game over
{ v_ball.moveTo(); // Put the ball in the middle of the stage
v_ball.stop(); // so that no collision with the outside of
// the stage is detected.
v_info.text = v_paddles[c_player].player + ' hat gewonnen';
await wait(3000);
v_info.text = '';
v_start_button.reset(); // make the start button visible again
}
else // the next round starts
{ v_ball.reset(); }
}
export {initLogic, startGame, ballLoss};