12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220 |
- const squareOne = {
- control: undefined,
- default: undefined,
- ui: undefined,
- animation: undefined,
- tractor: undefined,
- stack: undefined,
- floor: undefined,
-
- create: function () {
- const truckWidth = 201;
- const divisor = gameDifficulty == 3 ? 4 : gameDifficulty;
- let lineColor = undefined;
- let fillColor = undefined;
- if (gameOperation === 'minus') {
- lineColor = colors.red;
- fillColor = colors.redLight;
- } else {
- lineColor = colors.green;
- fillColor = colors.greenLight;
- }
- this.ui = {
- arrow: undefined,
- help: undefined,
- message: undefined,
- continue: {
-
- button: undefined,
- text: undefined,
- },
- };
- this.control = {
- direc: gameOperation == 'minus' ? -1 : 1,
- divisorsList: '',
- lineWidth: 3,
- hasClicked: false,
- checkAnswer: false,
- isCorrect: false,
- count: 0,
- };
- this.animation = {
- animateTractor: false,
- animateEnding: false,
- speed: 2 * this.control.direc,
- };
- this.default = {
- width: 172,
- height: 70,
- x0:
- gameOperation == 'minus'
- ? context.canvas.width - truckWidth
- : truckWidth,
- y0: context.canvas.height - game.image['floor_grass'].width * 1.5,
- };
- this.default.arrowX0 =
- self.default.x0 + self.default.width * self.control.direc;
- this.default.arrowXEnd =
- self.default.arrowX0 + self.default.width * self.control.direc * 8;
- renderBackground();
-
- if (moodle) {
- navigation.add.right(['audio']);
- } else {
- navigation.add.left(['back', 'menu', 'show_answer'], 'customMenu');
- navigation.add.right(['audio']);
- }
- this.stack = {
- list: [],
-
- selectedIndex: undefined,
-
- correctIndex: undefined,
-
- curIndex: 0,
-
- curBlockEndX: undefined,
- };
- this.floor = {
- list: [],
-
- selectedIndex: undefined,
-
- correctIndex: undefined,
-
- curIndex: -1,
-
- correctX: undefined,
- };
- let [restart, correctXA] = this.utils.renderStackedBlocks(
- this.control.direc,
- lineColor,
- fillColor,
- this.control.lineWidth,
- divisor
- );
- this.utils.renderFloorBlocks(
- this.control.direc,
- lineColor,
- this.control.lineWidth,
- divisor,
- correctXA
- );
- this.utils.renderCharacters();
- this.utils.renderMainUI();
- this.restart = restart;
- if (!this.restart) {
- game.timer.start();
- game.event.add('click', this.events.onInputDown);
- game.event.add('mousemove', this.events.onInputOver);
- }
- },
-
- update: function () {
-
- if (self.animation.animateTractor) {
- self.utils.animateTractorHandler();
- }
-
- if (self.control.checkAnswer) {
- self.utils.checkAnswerHandler();
- }
-
- if (self.animation.animateEnding) {
- self.utils.animateEndingHandler();
- }
- game.render.all();
- },
- utils: {
-
-
- renderStackedBlocks: (direc, lineColor, fillColor, lineWidth, divisor) => {
- let restart = false;
- let hasBaseDifficulty = false;
- const max = gameMode == 'b' ? 10 : curMapPosition + 4;
- const total = game.math.randomInRange(curMapPosition + 2, max);
- const renderLabels = (curDivisor, x, y, i, curBlock) => {
- let font, curFractionItems;
- const fractionPartsList = [];
- if (curDivisor === 1) {
- font = textStyles.h2_;
- curFractionItems = [
- {
- x: x,
- y: self.default.y0 - i * y - 20,
- text: '1',
- },
- {
- x: x - 25,
- y: self.default.y0 - i * y - 27,
- text: gameOperation === 'minus' ? '-' : '',
- },
- null,
- ];
- } else {
- font = textStyles.p_;
- curFractionItems = [
- {
- x: x,
- y: self.default.y0 - i * y - 40,
- text: '1\n' + curDivisor,
- },
- {
- x: x - 25,
- y: self.default.y0 - i * y - 27,
- text: gameOperation === 'minus' ? '-' : '',
- },
- {
- x0: x,
- y: self.default.y0 - i * y - 35,
- x1: x + 25,
- lineWidth: 2,
- color: lineColor,
- },
- ];
- }
- font = { ...font, font: 'bold ' + font.font, fill: lineColor };
- for (let i = 0; i < 2; i++) {
- const item = game.add.text(
- curFractionItems[i].x,
- curFractionItems[i].y,
- curFractionItems[i].text,
- font
- );
- item.lineHeight = 30;
- fractionPartsList.push(item);
- }
- if (curFractionItems[2]) {
- const line = game.add.geom.line(
- curFractionItems[2].x0,
- curFractionItems[2].y,
- curFractionItems[2].x1,
- curFractionItems[2].y,
- curFractionItems[2].lineWidth,
- curFractionItems[2].color
- );
- line.anchor(0.5, 0);
- fractionPartsList.push(line);
- } else {
- fractionPartsList.push(null);
- }
- curBlock.fraction = {
- labels: fractionPartsList,
- nominator: direc,
- denominator: curDivisor,
- };
- if (!showFractions) {
- curBlock.fraction.labels.forEach((label) => {
- if (label) label.alpha = 0;
- });
- }
- };
- const shouldRestart = (hasBaseDifficulty, correctXA) => {
- if (
- !hasBaseDifficulty ||
- (gameOperation == 'plus' &&
- (correctXA < self.default.x0 + self.default.width ||
- correctXA > self.default.x0 + 8 * self.default.width)) ||
- (gameOperation == 'minus' &&
- (correctXA < self.default.x0 - 8 * self.default.width ||
- correctXA > self.default.x0 - self.default.width))
- )
- return true;
- return false;
- };
- let correctXA = self.default.x0 + self.default.width * direc;
-
- for (let i = 0; i < total; i++) {
- let curDivisor = game.math.randomInRange(1, gameDifficulty);
- if (curDivisor === gameDifficulty) hasBaseDifficulty = true;
- if (curDivisor === 3) curDivisor = 4;
- const curBlockWidth = self.default.width / curDivisor;
- self.control.divisorsList += curDivisor + ',';
- correctXA += curBlockWidth * direc;
- const curBlock = game.add.geom.rect(
- self.default.x0,
- self.default.y0 - i * self.default.height - lineWidth,
- curBlockWidth,
- self.default.height,
- fillColor,
- 1,
- lineColor,
- lineWidth
- );
- curBlock.anchor(gameOperation === 'minus' ? 1 : 0, 1);
- curBlock.blockValue = divisor / curDivisor;
-
- if (gameMode === 'b') curBlock.blockIndex = i;
-
- self.stack.list.push(curBlock);
-
- const x = self.default.x0 + (curBlockWidth + 40) * direc;
- const y = self.default.height + 1;
- renderLabels(curDivisor, x, y, i, curBlock);
- }
-
- if (gameMode === 'a') self.stack.selectedIndex = total - 1;
-
-
- self.stack.curBlockEndX =
- self.default.x0 + self.stack.list[0].width * direc;
-
- restart = shouldRestart(hasBaseDifficulty, correctXA);
- if (isDebugMode) {
- console.log(
- `------------------------------
- \nGame Map Position: ${curMapPosition}
- \n------------------------ setup stack
- \nMin blocks (curMapPosition + 2): ${curMapPosition + 2}
- ${
- gameMode === 'a'
- ? `\nMax blocks (A mode) (curMapPosition + 4): ${
- curMapPosition + 4
- }`
- : '\nMax blocks (B mode): 10'
- }
- \nTotal blocks (random min..max): ${total}
- \nPossible divisors (random 1..gameDifficulty / if 3 then 4): 1..${
- gameDifficulty == 3 ? 4 : gameDifficulty
- }
- \n(Checks if has 1/diff or floor x is out of bounds)
- `
- );
- if (restart) console.log('Error during level setup. Retrying...');
- else console.log('Successfull level setup!');
- }
- return [restart, correctXA];
- },
- /**
- * Create floor blocks for the level in create()
- */
- renderFloorBlocks: (direc, lineColor, lineWidth, divisor, correctXA) => {
- let correctXB = 0;
- let total = 8 * divisor; // Number of floor blocks
- const blockWidth = self.default.width / divisor; // Width of each floor block
- const renderLabels = () => {
- for (let i = 0; i <= 8; i++) {
- const x = self.default.x0 + (i + 1) * self.default.width * direc;
- const y = self.default.y0 + self.default.height + 45 - 65;
- let numberX = x;
- let numberText = i;
- let numberCircleSize = 45;
- let numberFont = {
- ...textStyles.h3_,
- fill: lineColor,
- font: 'bold ' + textStyles.h3_.font,
- };
- if (gameOperation === 'minus') {
- numberX = i !== 0 ? x - 2 : x;
- numberText = -i;
- numberCircleSize = 45;
- numberFont.font = 'bold ' + textStyles.h4_.font;
- }
- game.add.geom
- .circle(x, y, numberCircleSize, undefined, 0, colors.white, 1)
- .anchor(0, 0.25);
- game.add.text(numberX, y + 2, numberText, numberFont);
- }
- };
- // If game is type (b), select a random floor x position
- if (gameMode === 'b') {
- self.stack.correctIndex = game.math.randomInRange(
- 0,
- self.stack.list.length - 1
- ); // Correct stacked index
- correctXB = self.default.x0 + self.default.width * direc;
- for (let i = 0; i <= self.stack.correctIndex; i++) {
- correctXB += self.stack.list[i].width * direc; // Equivalent x position on the floor
- }
- }
- // Render floor blocks
- for (let i = 0, shouldUpdateIndex = true; i < total; i++) {
- const curX =
- self.default.x0 + (self.default.width + i * blockWidth) * direc;
- // If game is type (a), iterate until find equivalent floor index
- if (gameMode === 'a' && shouldUpdateIndex) {
- if (
- (gameOperation == 'plus' && curX >= correctXA) ||
- (gameOperation == 'minus' && curX <= correctXA)
- ) {
- self.floor.correctIndex = i - 1; // Set index of correct floor block
- shouldUpdateIndex = false;
- }
- }
- // If game is type (b), stop iterating after find equivalent floor block
- if (gameMode === 'b') {
- if (
- (gameOperation == 'plus' && curX >= correctXB) ||
- (gameOperation == 'minus' && curX <= correctXB)
- ) {
- total = i;
- break;
- }
- }
- // Render floor block
- const curBlock = game.add.geom.rect(
- curX,
- self.default.y0,
- blockWidth,
- self.default.height + 10,
- colors.blueBgInsideLevel,
- 1,
- colors.gray,
- lineWidth
- );
- const anchor = gameOperation == 'minus' ? 1 : 0;
- curBlock.anchor(anchor, 0);
- curBlock.blockValue = 1;
- // If game is type (a), add events to floor blocks
- if (gameMode === 'a') {
- curBlock.fillColor = 'transparent';
- curBlock.blockIndex = i;
- }
- // Add current block to list
- self.floor.list.push(curBlock);
- }
- if (gameMode === 'b') {
- self.floor.selectedIndex = total - 1; // Computer generated correct floor index
- self.floor.correctX = correctXB;
- } else {
- self.floor.correctX = correctXA;
- }
- // Creates labels on the floor to display the numbers
- renderLabels();
- if (isDebugMode) {
- console.log(
- `------------------------ setup floor
- \nDivisor (gameDifficulty / if 3 then 4): ${divisor}
- ${
- gameMode === 'a'
- ? `\nTotal blocks (A) (divisor * 8): ${divisor} * 8 = ${
- divisor * 8
- }`
- : `\nTotal blocks (B) (((equiv. to stack))): ${self.floor.list.length}`
- }
- ${
- gameMode === 'a'
- ? `\nCorrect index (A) (((equival. to stack))): ${self.floor.correctIndex}`
- : ''
- }
- `
- );
- }
- },
- renderCharacters: () => {
- self.tractor = game.add.sprite(
- self.default.x0,
- self.default.y0,
- 'tractor',
- 0,
- 1
- );
- if (gameOperation == 'plus') {
- self.tractor.anchor(1, 1);
- self.tractor.animation = ['move', [0, 1, 2, 3, 4], 4];
- } else {
- self.tractor.anchor(0, 1);
- self.tractor.animation = ['move', [5, 6, 7, 8, 9], 4];
- self.tractor.curFrame = 5;
- }
- },
- renderMainUI: () => {
- // Help pointer
- self.ui.help = game.add.image(0, 0, 'pointer', 1.7, 0);
- if (gameMode === 'b') self.ui.help.anchor(0.25, 0.7);
- else self.ui.help.anchor(0.2, 0);
- // Selection Arrow
- if (gameMode === 'a') {
- self.ui.arrow = game.add.image(
- self.default.arrowX0,
- self.default.y0,
- 'arrow_down',
- 1.5
- );
- self.ui.arrow.anchor(0.5, 1);
- self.ui.arrow.alpha = 0.5;
- }
- // Intro text
- const correctMessage =
- gameMode === 'a'
- ? game.lang.squareOne_intro_a
- : game.lang.squareOne_intro_b;
- const treatedMessage = correctMessage.split('\\n');
- const font = textStyles.h1_;
- self.ui.message = [];
- self.ui.message.push(
- game.add.text(
- context.canvas.width / 2,
- 170,
- treatedMessage[0] + '\n' + treatedMessage[1],
- font
- )
- );
- },
- renderOperationUI: () => {
- /**
- *
- * if game mode A:
- * - left: (1) selected floor position (user selection)
- * - right: (2) expected floor position equivalent to the stack of blocks (pre-set)
- *
- * if game mode B:
- * - left: (3) floor position equivalent to the stack of blocks (user selection)
- * - right: (4) generated floor position (pre-set)
- */
- const divisor = gameDifficulty == 3 ? 4 : gameDifficulty;
- const renderFloorFractions = (lastIndex, divisor) => {
- const operator = gameOperation === 'minus' ? '-' : '+';
- const index = lastIndex;
- const blocks = index + 1;
- const valueReal = blocks / divisor;
- const valueFloor = Math.floor(valueReal);
- const valueRest = valueReal - valueFloor;
- let fracNomin = (fracDenomin = fracLine = '');
- // adds sign on the left of the equation
- if (gameOperation === 'minus') {
- fracNomin += ' ';
- fracDenomin += ' ';
- fracLine += operator;
- }
- // 1 _ _
- if (valueFloor) {
- fracNomin += ' ';
- fracDenomin += ' ';
- fracLine += valueFloor;
- }
- // _ + _
- if (valueFloor && valueRest) {
- fracNomin += ' ';
- fracDenomin += ' ';
- fracLine += operator;
- }
- // _ _ 1/5
- if (valueRest) {
- fracNomin += `${valueRest * divisor}`;
- fracDenomin += `${divisor}`;
- fracLine += '-';
- }
- return [fracNomin, fracDenomin, fracLine, valueReal];
- };
- const renderStackFractions = (lastIndex) => {
- const operator = gameOperation === 'minus' ? '-' : '+';
- const index = lastIndex;
- const blocks = index + 1;
- const nominators = [];
- const denominators = [];
- const values = [];
- let valueReal = 0;
- let fracNomin = (fracDenomin = fracLine = '');
- for (let i = 0; i < blocks; i++) {
- const m = self.stack.list[i].fraction.denominator || 1;
- const temp = self.stack.list[i].fraction.nominator || 0;
- const n = gameOperation === 'minus' ? -temp : +temp;
- const nm = n / m;
- nominators[i] = n + 0;
- denominators[i] = m + 0;
- values[i] = nm;
- valueReal += nm;
- }
- for (let i = 0; i < blocks; i++) {
- const valueReal = values[i];
- const valueFloor = Math.floor(valueReal);
- const valueRest = valueReal - valueFloor;
- if (i > 0 || gameOperation === 'minus') {
- fracNomin += ' ';
- fracDenomin += ' ';
- fracLine += operator;
- }
- if (valueFloor && !valueRest) {
- fracNomin += ' ';
- fracDenomin += ' ';
- fracLine += valueFloor;
- }
- if (valueRest) {
- fracNomin += `${nominators[i]}`;
- fracDenomin += `${denominators[i]}`;
- fracLine += '-';
- }
- }
- return [fracNomin, fracDenomin, fracLine, valueReal];
- };
- // Initial setup
- const font = textStyles.fraction;
- font.fill = colors.black;
- const padding = 100;
- const offsetX = 100;
- const widthOfChar = 35;
- const x0 = padding;
- const y0 = context.canvas.height / 3;
- let nextX = x0;
- const cardHeight = 400;
- const cardX = x0 - padding;
- const cardY = y0;
- const renderList = [];
- // Render Card
- const card = game.add.geom.rect(
- cardX,
- cardY,
- 0,
- cardHeight,
- colors.blueLight,
- 0.5,
- colors.blueDark,
- 8
- );
- card.id = 'card';
- card.anchor(0, 0.5);
- renderList.push(card);
- // Fraction setup
- console.clear();
- const [floorNominators, floorDenominators, floorLines, floorValue] =
- renderFloorFractions(
- self.floor.selectedIndex,
- divisor
- // 'LEFT SIDE - a fração escolhida no chão é...\n\n'
- );
- renderFloorFractions(
- self.floor.correctIndex,
- divisor
- // '\n\nRIGHT SIDE 1 - a fração CORRETA no chão é...\n\n'
- );
- const [stackNominators, stackDenominators, stackLines, stackValue] =
- renderStackFractions(
- self.stack.selectedIndex
- // '\n\nRIGHT SIDE 2 - a fração CORRETA na stack é...\n\n'
- );
- const renderFloorOperationLine = (x) => {
- font.fill = colors.black;
- const floorNom = game.add.text(
- x + offsetX / 2,
- y0,
- floorNominators,
- font,
- 60
- );
- const floorDenom = game.add.text(
- x + offsetX / 2,
- y0 + 70,
- floorDenominators,
- font,
- 60
- );
- const floorLin = game.add.text(
- x + offsetX / 2,
- y0 + 35,
- floorLines,
- font,
- 60
- );
- renderList.push(floorNom);
- renderList.push(floorDenom);
- renderList.push(floorLin);
- };
- const renderStackOperationLine = (x) => {
- font.fill = colors.black;
- const stackNom = game.add.text(
- x + offsetX / 2,
- y0,
- stackNominators,
- font,
- 60
- );
- const stackDenom = game.add.text(
- x + offsetX / 2,
- y0 + 70,
- stackDenominators,
- font,
- 60
- );
- const stackLin = game.add.text(
- x + offsetX / 2,
- y0 + 35,
- stackLines,
- font,
- 60
- );
- renderList.push(stackNom);
- renderList.push(stackDenom);
- renderList.push(stackLin);
- };
- // Render LEFT part of the operation
- if (gameMode === 'a') renderFloorOperationLine(x0);
- else renderStackOperationLine(x0);
- let curNominators = gameMode === 'a' ? floorNominators : stackNominators;
- nextX = x0 + (curNominators.length + 2) * widthOfChar;
- // Render middle sign - equal by default
- font.fill = colors.green;
- let comparisonSign = '=';
- // Render middle sign - if not equal
- if (floorValue != stackValue) {
- font.fill = colors.red;
- let leftSideIsLarger = floorValue > stackValue;
- if (gameMode === 'b') leftSideIsLarger = !leftSideIsLarger;
- if (gameOperation === 'minus') leftSideIsLarger = !leftSideIsLarger;
- comparisonSign = leftSideIsLarger ? '>' : '<';
- }
- renderList.push(game.add.text(nextX, y0 + 35, comparisonSign, font));
- // Render RIGHT part of the operation
- if (gameMode === 'a') renderStackOperationLine(nextX);
- else renderFloorOperationLine(nextX);
- curNominators = gameMode === 'a' ? stackNominators : floorNominators;
- const resultWidth = (curNominators.length + 2) * widthOfChar;
- const cardWidth = nextX - x0 + resultWidth + padding * 2;
- card.width = cardWidth;
- const endSignX = (context.canvas.width - cardWidth) / 2 + cardWidth;
- // Center Card
- moveList(renderList, (context.canvas.width - cardWidth) / 2, 0);
- self.fractionOperationUI = renderList;
- return endSignX;
- },
- renderEndUI: () => {
- let btnColor = colors.green;
- let btnText = game.lang.continue;
- if (!self.control.isCorrect) {
- btnColor = colors.red;
- btnText = game.lang.retry;
- }
- // continue button
- self.ui.continue.button = game.add.geom.rect(
- context.canvas.width / 2,
- context.canvas.height / 2 + 100,
- 450,
- 100,
- btnColor
- );
- self.ui.continue.button.anchor(0.5, 0.5);
- self.ui.continue.text = game.add.text(
- context.canvas.width / 2,
- context.canvas.height / 2 + 16 + 100,
- btnText,
- textStyles.btn
- );
- },
- // UPDATE HANDLERS
- animateTractorHandler: () => {
- // Move
- self.tractor.x += self.animation.speed;
- self.stack.list.forEach((block) => (block.x += self.animation.speed));
- // If the current block is 1/n (not 1/1) we need to consider the
- // extra space the truck needs to pass after the blocks falls but
- // before reaching the next block
- const curBlockExtra =
- (self.default.width - self.stack.list[self.stack.curIndex].width) *
- self.control.direc;
- const canLowerBlocks =
- (gameOperation == 'plus' &&
- self.stack.list[0].x >= self.stack.curBlockEndX + curBlockExtra) ||
- (gameOperation == 'minus' &&
- self.stack.list[0].x <= self.stack.curBlockEndX + curBlockExtra);
- if (canLowerBlocks) {
- const endAnimation = self.utils.lowerBlocksHandler();
- if (!endAnimation) {
- self.animation.animateTractor = false;
- self.control.checkAnswer = true;
- }
- }
- },
- lowerBlocksHandler: () => {
- self.floor.curIndex += self.stack.list[self.stack.curIndex].blockValue;
- const tooManyStackBlocks = self.floor.curIndex > self.floor.selectedIndex;
- if (tooManyStackBlocks) return false;
- // fill floor
- for (let i = 0; i <= self.floor.curIndex; i++) {
- self.floor.list[i].fillColor = 'transparent';
- }
- // lower blocks
- self.stack.list.forEach((block) => {
- block.y += self.default.height;
- });
- // hide current block
- self.stack.list[self.stack.curIndex].alpha = 0;
- const isLastFloorBlock = self.floor.curIndex === self.floor.selectedIndex;
- const notEnoughStackBlocks =
- self.stack.curIndex === self.stack.list.length - 1;
- if (isLastFloorBlock || notEnoughStackBlocks) return false;
- // update stack blocks
- self.stack.curIndex++;
- self.stack.curBlockEndX +=
- self.stack.list[self.stack.curIndex].width * self.control.direc;
- return true;
- },
- checkAnswerHandler: () => {
- game.timer.stop();
- game.animation.stop(self.tractor.animation[0]);
- if (gameMode === 'a') self.ui.arrow.alpha = 0;
- self.control.isCorrect =
- gameMode === 'a'
- ? self.floor.selectedIndex === self.floor.correctIndex
- : self.stack.selectedIndex === self.stack.correctIndex;
- const x = self.utils.renderOperationUI();
- // Give feedback to player and turns on sprite animation
- if (self.control.isCorrect) {
- completedLevels++; // Increases number os finished levels
- if (audioStatus) game.audio.okSound.play();
- game.animation.play(self.tractor.animation[0]);
- game.add
- .image(x + 50, context.canvas.height / 3, 'answer_correct')
- .anchor(0.5, 0.5);
- if (isDebugMode) console.log('Completed Levels: ' + completedLevels);
- } else {
- if (audioStatus) game.audio.errorSound.play();
- game.add
- .image(x, context.canvas.height / 3, 'answer_wrong')
- .anchor(0.5, 0.5);
- }
- self.fetch.postScore();
- self.control.checkAnswer = false;
- self.animation.animateEnding = true;
- },
- animateEndingHandler: () => {
- // ANIMATE ENDING
- self.control.count++;
- // If CORRECT ANSWER runs final tractor animation (else tractor desn't move, just wait)
- if (self.control.isCorrect) self.tractor.x += self.animation.speed;
- if (self.control.count === 100) {
- self.utils.renderEndUI();
- self.control.showEndInfo = true;
- if (self.control.isCorrect) canGoToNextMapPosition = true;
- else canGoToNextMapPosition = false;
- }
- },
- endLevel: () => {
- game.state.start('map');
- },
- // INFORMATION
- /**
- * Display correct answer
- */
- showAnswer: () => {
- if (!self.control.hasClicked) {
- // On gameMode (a)
- if (gameMode === 'a') {
- const aux = self.floor.list[0];
- self.ui.help.x =
- self.floor.correctX - (aux.width / 2) * self.control.direc;
- self.ui.help.y = self.default.y0;
- // On gameMode (b)
- } else {
- const aux = self.stack.list[self.stack.correctIndex];
- self.ui.help.x = aux.x + (aux.width / 2) * self.control.direc;
- self.ui.help.y = aux.y;
- }
- self.ui.help.alpha = 0.7;
- }
- },
- // EVENT HANDLERS
- /**
- * Function called by self.events.onInputDown() when player clicks on a valid rectangle.
- */
- clickHandler: (clickedIndex, curSet) => {
- if (!self.control.hasClicked && !self.animation.animateEnding) {
- document.body.style.cursor = 'auto';
- // Play beep sound
- if (audioStatus) game.audio.popSound.play();
- // Disable show answer nav icon
- navigation.disableIcon(navigation.showAnswerIcon);
- // Hide intro message
- self.ui.message[0].alpha = 0;
- // Hide labels
- if (showFractions) {
- self.stack.list.forEach((block) => {
- block.fraction.labels.forEach((lbl) => {
- if (lbl) lbl.alpha = 0;
- });
- });
- }
- // Hide solution pointer
- if (self.ui.help != undefined) self.ui.help.alpha = 0;
- // Hide unselected blocks
- for (let i = curSet.list.length - 1; i > clickedIndex; i--) {
- curSet.list[i].alpha = 0;
- }
- // Save selected index
- curSet.selectedIndex = clickedIndex;
- if (gameMode === 'a') {
- self.ui.arrow.alpha = 0;
- } else {
- // update list size
- self.stack.list.length = curSet.selectedIndex + 1;
- }
- // Turn tractor animation on
- game.animation.play(self.tractor.animation[0]);
- self.animation.animateTractor = true;
- self.control.hasClicked = true;
- }
- },
- /**
- * Function called by self.events.onInputOver() when cursor is over a valid rectangle
- *
- * @param {object} cur rectangle the cursor is over
- */
- overHandler: (cur) => {
- if (!self.control.hasClicked) {
- document.body.style.cursor = 'pointer';
- if (gameMode === 'a') {
- for (let i in self.floor.list) {
- self.floor.list[i].fillColor =
- i <= cur.blockIndex ? colors.blueBgInsideLevel : 'transparent';
- }
- self.floor.selectedIndex = cur.blockIndex;
- } else {
- for (let i in self.stack.list) {
- const alpha = i <= cur.blockIndex ? 1 : 0.4;
- self.stack.list[i].alpha = alpha;
- if (showFractions) {
- self.stack.list[i].fraction.labels.forEach((lbl) => {
- if (lbl) lbl.alpha = alpha;
- });
- }
- }
- self.stack.selectedIndex = cur.blockIndex;
- }
- }
- },
- /**
- * Function called by self.events.onInputOver() when cursos is out of a valid rectangle
- */
- outHandler: () => {
- if (!self.control.hasClicked) {
- document.body.style.cursor = 'auto';
- if (gameMode === 'a') {
- for (let i in self.floor.list) {
- self.floor.list[i].fillColor = 'transparent';
- }
- self.floor.selectedIndex = undefined;
- } else {
- for (let i in self.stack.list) {
- self.stack.list[i].alpha = 1;
- if (showFractions) {
- self.stack.list[i].fraction.labels.forEach((lbl) => {
- if (lbl) lbl.alpha = 1;
- });
- }
- }
- self.stack.selectedIndex = undefined;
- }
- }
- },
- },
- events: {
- /**
- * Called by mouse click event
- *
- * @param {object} mouseEvent contains the mouse click coordinates
- */
- onInputDown: (mouseEvent) => {
- const x = game.math.getMouse(mouseEvent).x;
- const y = game.math.getMouse(mouseEvent).y;
- // click blocks
- const curSet = gameMode == 'a' ? self.floor : self.stack;
- for (let i in curSet.list) {
- if (game.math.isOverIcon(x, y, curSet.list[i])) {
- self.utils.clickHandler(+i, curSet);
- break;
- }
- }
- // Continue button
- if (self.control.showEndInfo) {
- if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
- if (audioStatus) game.audio.popSound.play();
- self.utils.endLevel();
- }
- }
- navigation.onInputDown(x, y);
- game.render.all();
- },
- /**
- * Called by mouse move event
- *
- * @param {object} mouseEvent contains the mouse move coordinates
- */
- onInputOver: (mouseEvent) => {
- const x = game.math.getMouse(mouseEvent).x;
- const y = game.math.getMouse(mouseEvent).y;
- let isOverFloor = false;
- let isOverStack = false;
- if (gameMode === 'a') {
- self.floor.list.forEach((cur) => {
- // hover floor blocks
- if (game.math.isOverIcon(x, y, cur)) {
- isOverFloor = true;
- self.utils.overHandler(cur);
- }
- // move arrow
- if (
- !self.control.hasClicked &&
- !self.animation.animateEnding &&
- game.math.isOverIcon(x, self.default.y0, cur)
- ) {
- self.ui.arrow.x = x;
- }
- });
- if (!isOverFloor) self.utils.outHandler('a');
- }
- if (gameMode === 'b') {
- // hover stack blocks
- self.stack.list.forEach((cur) => {
- if (game.math.isOverIcon(x, y, cur)) {
- isOverStack = true;
- self.utils.overHandler(cur);
- }
- });
- if (!isOverStack) self.utils.outHandler('b');
- }
- // Continue button
- if (self.control.showEndInfo) {
- if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
- // If pointer is over icon
- document.body.style.cursor = 'pointer';
- self.ui.continue.button.scale =
- self.ui.continue.button.initialScale * 1.1;
- self.ui.continue.text.style = textStyles.btnLg;
- } else {
- // If pointer is not over icon
- document.body.style.cursor = 'auto';
- self.ui.continue.button.scale =
- self.ui.continue.button.initialScale * 1;
- self.ui.continue.text.style = textStyles.btn;
- }
- }
- navigation.onInputOver(x, y);
- game.render.all();
- },
- },
- fetch: {
- /**
- * Saves players data after level ends - to be sent to database <br>
- *
- * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
- *
- * @see /php/save.php
- */
- postScore: () => {
- // Creates string that is going to be sent to db
- const data =
- '&line_game=' +
- gameShape +
- '&line_mode=' +
- gameMode +
- '&line_oper=' +
- gameOperation +
- '&line_leve=' +
- gameDifficulty +
- '&line_posi=' +
- curMapPosition +
- '&line_resu=' +
- self.control.isCorrect +
- '&line_time=' +
- game.timer.elapsed +
- '&line_deta=' +
- 'numBlocks:' +
- self.stack.list.length +
- ', valBlocks: ' +
- self.control.divisorsList + // Ends in ','
- ' blockIndex: ' +
- self.stack.selectedIndex +
- ', floorIndex: ' +
- self.floor.selectedIndex;
- // FOR MOODLE
- sendToDatabase(data);
- },
- },
- };
|