How to use saveState method in Cypress

Best JavaScript code snippet using cypress

index.js

Source:index.js Github

copy

Full Screen

1//import functions from animations.js2import { sitAnimationRock } from './animations.js';3import { sitAnimationShroom } from './animations.js';4import { sitAnimationDino } from './animations.js';5import { eggGreenAnimation1 } from './animations.js';6import { eggGreenAnimation2 } from './animations.js';7import { eggGreenAnimation3 } from './animations.js';8import { eggGreenAnimation4 } from './animations.js';9import { eggOrangeAnimation1 } from './animations.js';10import { eggOrangeAnimation2 } from './animations.js';11import { eggOrangeAnimation3 } from './animations.js';12import { eggOrangeAnimation4 } from './animations.js';13import { eggPurpleAnimation1 } from './animations.js';14import { eggPurpleAnimation2 } from './animations.js';15import { eggPurpleAnimation3 } from './animations.js';16import { eggPurpleAnimation4 } from './animations.js';17import { deadAnimation } from './animations.js';18//Fitbit imports19import document from "document";20import * as fs from "fs";21import clock from "clock";22import { me as appbit } from "appbit";23import { today } from "user-activity";24//bind UI elements25let list = document.getElementById("myList");26let storeList = document.getElementById("storeList");27let storeItems = storeList.getElementsByClassName("list-item");28let items = list.getElementsByClassName("list-item");29let image = document.getElementById('image');30let background = document.getElementById('background');31let hungerLabel = document.getElementById('hunger');32let healthLabel = document.getElementById('health');33let walletLabel = document.getElementById('wallet');34let stepsLabel = document.getElementById('steps');35stepsLabel.style.display = 'none';36let cookieLabel = document.getElementById('cookies');37let feedPetButton = document.getElementById('button-4');38let devButton = document.getElementById('button-5');39let devButton2 = document.getElementById('button-6');40let devButton3 = document.getElementById('button-7');41let menuButton = document.getElementById('menuBtn');42let healthBar = document.getElementById('healthBar');43let hungerBar = document.getElementById('hungerBar');44let borderBarHealth = document.getElementById('borderBarHealth');45let borderBarHunger = document.getElementById('borderBarHunger');46let backButton = document.getElementById('backBtn');47healthBar.style.display = 'none';48hungerBar.style.display = 'none';49borderBarHealth.style.display = 'none';50borderBarHunger.style.display = 'none';51let healthCircle = document.getElementById('arc');52let storePage = document.getElementById('page3');53let mainPage = document.getElementById('page2');54let startPage = document.getElementById('page1');55let menuPage = document.getElementById('menuPage');56let statsPage = document.getElementById('statsPage');57let mainMenu = document.getElementById('mainMenu');58let menuBtn1 = document.getElementById('feedPetBtn');59let menuBtn2 = document.getElementById('storeBtn');60let menuBtn3 = document.getElementById('btn2');61let menuBtn4 = document.getElementById('btn3');62let menuBtn5 = document.getElementById('btn4');63let menuBtn6 = document.getElementById('btn5');64//page2.style.display = 'none';65//initialize UI elements and fitbit components66storePage.style.display = 'none';67statsPage.style.display = 'none';68devButton3.style.display = 'none';69clock.granularity = "seconds"; // seconds, minutes, hours70//uncomment to hide dev buttons.71//devButton.style.display ='none'; 72//devButton2.style.display ='none';73//declare variables74var lastSaveTime;75var hungerTime;76var dieTime;77var animationSpeed = 150;78var animationFrame = 1;79var eggStage0 = 10;80var eggStage1 = 20;81var eggStage2 = 30;82var eggStage3 = 40;83var menuOpen = false;84//initial game start data.85var saveState = {86 "data": {87 "hunger": 0,88 "wallet": 0,89 "steps": 0,90 "health": 100,91 "saveTimer": new Date(),92 "hungerTimer": new Date(),93 "fullTimer": null,94 "dieLoop": new Date(),95 "cookies": 1000,96 "pet": null,97 "egg": -1,98 "backgroundTask": false,99 "currentAnimation": null100 }101};102//event handler for the egg listbox selection.103items.forEach((element, index) => {104 let touch = element.getElementById("touch");105 touch.addEventListener("click", (evt) => {106 console.log(`touched: ${index}`);107 if (index > 0) {108 list.style.display = 'none';109 saveState.data.egg = index - 1;110 //initialize the offset for starting the tracking of step count.111 saveState.data.steps = today.adjusted.steps;112 }113 else {114 return;115 }116 });117});118//event handler for the store listbox selection.119storeItems.forEach((element, index) => {120 let touch = element.getElementById("touch");121 touch.addEventListener("click", (evt) => {122 console.log(`touched: ${index}`);123 });124});125//check if there is saved data.126if (fs.existsSync("/private/data/save.txt")) {127 //load any saved data to variables.128 saveState = fs.readFileSync("save.txt", "json");129 console.log("time since last save " + checkDate(new Date(saveState.data.saveTimer)) * -1 + " Min");130}131//if there is no saved data. We must start a new game.132else {133 console.log("no saved data found. creating new game.")134 fs.writeFileSync("save.txt", saveState, "json");135}136// Disable app timeout137if (appbit.appTimeoutEnabled) {138 console.log("Timeout is enabled");139}140appbit.appTimeoutEnabled = false; // Disable timeout141//animate the pet.142setInterval(swapImageAnimator, animationSpeed);143//event listeners144//open and close the storePage145menuButton.addEventListener("click", (evt) => {146 menuButton.style.display = 'none';147 menuOpen = true;148 //background.style.display = 'none';149 mainPage.style.display = 'none';150 menuPage.style.display = 'inline';151})152//back button inside the menu page.153backButton.addEventListener("click", (evt) => {154 if (mainMenu.style.display == 'inline') {155 menuOpen = false;156 menuPage.style.display = 'none';157 //background.style.display = 'inline';158 mainPage.style.display = 'inline';159 menuButton.style.display = 'inline';160 }161 162 else {163 164 }165})166//button event.167feedPetButton.addEventListener("click", (evt) => {168 console.log("Feed Pet.");169 if (saveState.data.cookies > 0 && saveState.data.hunger > 0) {170 saveState.data.cookies -= 1;171 saveState.data.hunger -= 10;172 if (saveState.data.hunger < 0) {173 saveState.data.hunger = 0;174 }175 }176 else {177 console.log("out of cookies...")178 }179})180devButton.addEventListener("click", (evt) => {181 saveState.data.hunger = 100;182 //saveState.data.health = 0;183})184//create new Game.185devButton3.addEventListener("click", (evt) => {186 saveState = {187 "data": {188 "hunger": 0,189 "wallet": 0,190 "steps": 0,191 "health": 100,192 "saveTimer": new Date(),193 "hungerTimer": new Date(),194 "fullTimer": null,195 "dieLoop": new Date(),196 "cookies": 1000,197 "pet": null,198 "egg": -1,199 "backgroundTask": false,200 "currentAnimation": null201 }202 };203 console.log("creating new game.")204 fs.writeFileSync("save.txt", saveState, "json");205 list.style.display = 'inline';206 image.style.display = 'none';207 devButton3.style.display = 'none';208})209devButton2.addEventListener("click", (evt) => {210 saveState.data.cookies += 100;211 saveState.data.hunger = 0;212 saveState.data.health = 100;213})214//happens when the clock ticks every second.215clock.addEventListener("tick", (evt) => {216 console.log("steps: " + saveState.data.steps);217 console.log("wallet: " + saveState.data.wallet);218 // TODO: COMPARTMENTALIZE THE GAME LOGIC219 // check if user has not selected an egg.220 if (saveState.data.egg == -1) {221 mainPage.style.display = 'none';222 startPage.style.display = 'inline';223 storePage.style.display = 'none';224 menuButton.style.display = 'none';225 return;226 }227 //if the pet is dead display dead animation.228 if (saveState.data.health <= 0) {229 animationFrame = 1;230 saveState.data.currentAnimation = 'dead';231 feedPetButton.style.display = "none";232 healthLabel.style.display = 'none';233 cookieLabel.style.display = 'none';234 hungerLabel.style.display = 'none';235 walletLabel.style.display = 'none';236 devButton3.style.display = 'inline';237 return;238 }239 //if we reach this point the game is in progress as either an egg or creature.240 if (!menuOpen) {241 //hide the start page and show the main Page.242 mainPage.style.display = 'inline';243 startPage.style.display = 'none';244 }245 //EGG LOGIC ---------------------------------------------------246 if (saveState.data.egg == 0) {247 background.style.display = 'inline';248 feedPetButton.style.display = 'none';249 walletLabel.style.display = 'inline';250 saveState.data.currentAnimation = 'egg0';251 if (saveState.data.wallet >= eggStage0)252 saveState.data.egg = 0.1;253 }254 else if (saveState.data.egg == 1) {255 background.style.display = 'inline';256 feedPetButton.style.display = 'none';257 walletLabel.style.display = 'inline';258 saveState.data.currentAnimation = 'egg1';259 if (saveState.data.wallet >= eggStage0)260 saveState.data.egg = 1.1;261 }262 else if (saveState.data.egg == 2) {263 background.style.display = 'inline';264 feedPetButton.style.display = 'none';265 walletLabel.style.display = 'inline';266 saveState.data.currentAnimation = 'egg2';267 if (saveState.data.wallet >= eggStage0)268 saveState.data.egg = 2.1;269 }270 else if (saveState.data.egg == 0.1) {271 saveState.data.currentAnimation = 'egg0.1';272 if (saveState.data.wallet >= eggStage1)273 saveState.data.egg = 0.2;274 }275 else if (saveState.data.egg == 1.1) {276 saveState.data.currentAnimation = 'egg1.1';277 if (saveState.data.wallet >= eggStage1)278 saveState.data.egg = 1.2;279 }280 else if (saveState.data.egg == 2.1) {281 saveState.data.currentAnimation = 'egg2.1';282 if (saveState.data.wallet >= eggStage1)283 saveState.data.egg = 2.2;284 }285 else if (saveState.data.egg == 0.2) {286 saveState.data.currentAnimation = 'egg0.2';287 if (saveState.data.wallet >= eggStage2)288 saveState.data.egg = 0.3;289 }290 else if (saveState.data.egg == 1.2) {291 saveState.data.currentAnimation = 'egg1.2';292 if (saveState.data.wallet >= eggStage2)293 saveState.data.egg = 1.3;294 }295 else if (saveState.data.egg == 2.2) {296 saveState.data.currentAnimation = 'egg2.2';297 if (saveState.data.wallet >= eggStage2)298 saveState.data.egg = 2.3;299 }300 else if (saveState.data.egg == 0.3) {301 saveState.data.currentAnimation = 'egg0.3';302 if (saveState.data.wallet >= eggStage3) {303 saveState.data.egg = null;304 saveState.data.currentAnimation = 'sit';305 saveState.data.wallet = 0;306 saveState.data.currentPet = 'dino';307 }308 }309 else if (saveState.data.egg == 1.3) {310 saveState.data.currentAnimation = 'egg1.3';311 if (saveState.data.wallet >= eggStage3) {312 saveState.data.egg = null;313 saveState.data.currentAnimation = 'sit';314 saveState.data.currentPet = 'rock';315 saveState.data.wallet = 0;316 }317 }318 else if (saveState.data.egg == 2.3) {319 saveState.data.currentAnimation = 'egg2.3';320 if (saveState.data.wallet >= eggStage3) {321 saveState.data.egg = null;322 saveState.data.currentAnimation = 'sit';323 saveState.data.currentPet = 'shroom';324 saveState.data.wallet = 0;325 }326 }327 //EGG LOGIC END ---------------------------------------------------328 else {329 if (!menuOpen) {330 menuButton.style.display = 'inline';331 healthBar.style.display = 'inline';332 hungerBar.style.display = 'inline';333 borderBarHealth.style.display = 'inline';334 borderBarHunger.style.display = 'inline';335 cookieLabel.style.display = 'block';336 feedPetButton.style.display = 'inline';337 hungerLabel.text = "Hunger:";338 healthLabel.text = "Health:";339 walletLabel.text = "Wallet:" + saveState.data.wallet;340 cookieLabel.text = "Cookies:" + saveState.data.cookies;341 }342 // represents how many minutes have passed since the last save.343 lastSaveTime = checkDate(new Date(saveState.data.saveTimer)) * -1;344 hungerTime = checkDate(new Date(saveState.data.hungerTimer)) * -1;345 dieTime = checkDate(new Date(saveState.data.dieLoop)) * -1;346 //if pet is not hungry rest dieLoop to zero.347 if (saveState.data.hunger > 0) {348 saveState.data.dieLoop = 0;349 }350 //hunger is 0, pet is full -> health goes up351 if (saveState.data.hunger == 0) {352 if (lastSaveTime >= 1 && saveState.data.health < 100) {353 saveState.data.health += 1;354 //update the current save state time.355 saveState.data.saveTimer = new Date();356 //update current save state.357 fs.writeFileSync("save.txt", saveState, "json");358 }359 }360 //hunger logic-----------------------------------------------361 if (hungerTime >= 100 && saveState.data.hunger < 100) {362 if (saveState.data.hunger > 100) {363 saveState.data.hunger = 100;364 } else {365 saveState.data.hunger += 100;366 }367 //update the current save state time.368 saveState.data.hungerTimer = new Date();369 }370 if (hungerTime >= 95 && saveState.data.hunger < 100) {371 if (saveState.data.hunger > 100) {372 saveState.data.hunger = 100;373 } else {374 saveState.data.hunger += 95;375 }376 //update the current save state time.377 saveState.data.hungerTimer = new Date();378 }379 if (hungerTime >= 90 && saveState.data.hunger < 100) {380 if (saveState.data.hunger > 100) {381 saveState.data.hunger = 100;382 } else {383 saveState.data.hunger += 90;384 }385 //update the current save state time.386 saveState.data.hungerTimer = new Date();387 }388 if (hungerTime >= 85 && saveState.data.hunger < 100) {389 if (saveState.data.hunger > 100) {390 saveState.data.hunger = 100;391 } else {392 saveState.data.hunger += 85;393 }394 //update the current save state time.395 saveState.data.hungerTimer = new Date();396 }397 if (hungerTime >= 80 && saveState.data.hunger < 100) {398 if (saveState.data.hunger > 100) {399 saveState.data.hunger = 100;400 } else {401 saveState.data.hunger += 80;402 }403 //update the current save state time.404 saveState.data.hungerTimer = new Date();405 }406 if (hungerTime >= 75 && saveState.data.hunger < 100) {407 if (saveState.data.hunger > 100) {408 saveState.data.hunger = 100;409 } else {410 saveState.data.hunger += 75;411 }412 //update the current save state time.413 saveState.data.hungerTimer = new Date();414 }415 if (hungerTime >= 70 && saveState.data.hunger < 100) {416 if (saveState.data.hunger > 100) {417 saveState.data.hunger = 100;418 } else {419 saveState.data.hunger += 70;420 }421 //update the current save state time.422 saveState.data.hungerTimer = new Date();423 }424 if (hungerTime >= 65 && saveState.data.hunger < 100) {425 if (saveState.data.hunger > 100) {426 saveState.data.hunger = 100;427 } else {428 saveState.data.hunger += 65;429 }430 //update the current save state time.431 saveState.data.hungerTimer = new Date();432 }433 if (hungerTime >= 60 && saveState.data.hunger < 100) {434 if (saveState.data.hunger > 100) {435 saveState.data.hunger = 100;436 } else {437 saveState.data.hunger += 60;438 }439 //update the current save state time.440 saveState.data.hungerTimer = new Date();441 }442 if (hungerTime >= 55 && saveState.data.hunger < 100) {443 if (saveState.data.hunger > 100) {444 saveState.data.hunger = 100;445 } else {446 saveState.data.hunger += 55;447 }448 //update the current save state time.449 saveState.data.hungerTimer = new Date();450 }451 if (hungerTime >= 50 && saveState.data.hunger < 100) {452 if (saveState.data.hunger > 100) {453 saveState.data.hunger = 100;454 } else {455 saveState.data.hunger += 50;456 }457 //update the current save state time.458 saveState.data.hungerTimer = new Date();459 }460 if (hungerTime >= 45 && saveState.data.hunger < 100) {461 if (saveState.data.hunger > 100) {462 saveState.data.hunger = 100;463 } else {464 saveState.data.hunger += 45;465 }466 //update the current save state time.467 saveState.data.hungerTimer = new Date();468 }469 if (hungerTime >= 40 && saveState.data.hunger < 100) {470 if (saveState.data.hunger > 100) {471 saveState.data.hunger = 100;472 } else {473 saveState.data.hunger += 40;474 }475 //update the current save state time.476 saveState.data.hungerTimer = new Date();477 }478 if (hungerTime >= 35 && saveState.data.hunger < 100) {479 if (saveState.data.hunger > 100) {480 saveState.data.hunger = 100;481 } else {482 saveState.data.hunger += 35;483 }484 //update the current save state time.485 saveState.data.hungerTimer = new Date();486 }487 if (hungerTime >= 30 && saveState.data.hunger < 100) {488 if (saveState.data.hunger > 100) {489 saveState.data.hunger = 100;490 } else {491 saveState.data.hunger += 30;492 }493 //update the current save state time.494 saveState.data.hungerTimer = new Date();495 }496 if (hungerTime >= 25 && saveState.data.hunger < 100) {497 if (saveState.data.hunger > 100) {498 saveState.data.hunger = 100;499 } else {500 saveState.data.hunger += 25;501 }502 //update the current save state time.503 saveState.data.hungerTimer = new Date();504 }505 if (hungerTime >= 20 && saveState.data.hunger < 100) {506 if (saveState.data.hunger > 100) {507 saveState.data.hunger = 100;508 } else {509 saveState.data.hunger += 20;510 }511 //update the current save state time.512 saveState.data.hungerTimer = new Date();513 }514 if (hungerTime >= 15 && saveState.data.hunger < 100) {515 if (saveState.data.hunger > 100) {516 saveState.data.hunger = 100;517 } else {518 saveState.data.hunger += 15;519 }520 //update the current save state time.521 saveState.data.hungerTimer = new Date();522 }523 if (hungerTime >= 10 && saveState.data.hunger < 100) {524 if (saveState.data.hunger > 100) {525 saveState.data.hunger = 100;526 } else {527 saveState.data.hunger += 10;528 }529 //update the current save state time.530 saveState.data.hungerTimer = new Date();531 }532 if (hungerTime >= 5 && saveState.data.hunger < 100) {533 if (saveState.data.hunger > 100) {534 saveState.data.hunger = 100;535 } else {536 saveState.data.hunger += 5;537 }538 //update the current save state time.539 saveState.data.hungerTimer = new Date();540 }541 //every 30 min the pet gains 1 hunger (becomes hungrier)542 if (hungerTime >= 1 && saveState.data.hunger < 100) {543 if (saveState.data.hunger > 100) {544 saveState.data.hunger = 100;545 } else {546 saveState.data.hunger += 1;547 }548 //update the current save state time.549 saveState.data.hungerTimer = new Date();550 }551 //if pet runs out of hunger health drops every min552 if (saveState.data.hunger == 100 && dieTime >= 1) {553 saveState.data.health -= 1;554 //update the current save state time.555 saveState.data.dieLoop = new Date();556 }557 }558 updateUI();559 //console.log("time since last hunger added " + hungerTime + " Min");560});561function updateUI() {562 healthBar.width = saveState.data.health;563 hungerBar.width = saveState.data.hunger;564 //healthCircle.groupTransform.angle += 0.28;565 checkSteps();566 walletLabel.text = "wallet: " + saveState.data.wallet;567 stepsLabel.text = "steps: " + saveState.data.steps;568}569//check how many steps the user has taken.570function checkSteps() {571 if (appbit.permissions.granted("access_activity")) {572 //update the user's wallet with steps.573 var stepDif = today.adjusted.steps - saveState.data.steps;574 saveState.data.wallet += stepDif;575 saveState.data.steps = today.adjusted.steps;576 }577}578function checkDate(date) {579 var today = new Date();580 var lastDate = date;581 var diffMs = (lastDate - today); // milliseconds between now & last date.582 var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes583 //var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours584 return diffMins;585}586function swapImageAnimator() {587 if (menuOpen) {588 return;589 }590 switch (saveState.data.currentAnimation) {591 case 'egg2':592 animationFrame = eggPurpleAnimation1(image, animationFrame);593 break;594 case 'egg2.1':595 animationFrame = eggPurpleAnimation2(image, animationFrame);596 break;597 case 'egg2.2':598 animationFrame = eggPurpleAnimation3(image, animationFrame);599 break;600 case 'egg2.3':601 animationFrame = eggPurpleAnimation4(image, animationFrame);602 break;603 case 'egg1':604 animationFrame = eggOrangeAnimation1(image, animationFrame);605 break;606 case 'egg1.1':607 animationFrame = eggOrangeAnimation2(image, animationFrame);608 break;609 case 'egg1.2':610 animationFrame = eggOrangeAnimation3(image, animationFrame);611 break;612 case 'egg1.3':613 animationFrame = eggOrangeAnimation4(image, animationFrame);614 break;615 case 'egg0':616 animationFrame = eggGreenAnimation1(image, animationFrame);617 break;618 case 'egg0.1':619 animationFrame = eggGreenAnimation2(image, animationFrame);620 break;621 case 'egg0.2':622 animationFrame = eggGreenAnimation3(image, animationFrame);623 break;624 case 'egg0.3':625 animationFrame = eggGreenAnimation4(image, animationFrame);626 break;627 case 'sit':628 if (saveState.data.currentPet == 'shroom')629 animationFrame = sitAnimationShroom(image, animationFrame);630 if (saveState.data.currentPet == 'rock')631 animationFrame = sitAnimationRock(image, animationFrame);632 if (saveState.data.currentPet == 'dino')633 animationFrame = sitAnimationDino(image, animationFrame);634 break;635 case 'sleep':636 //sleepAnimation();637 break;638 case 'eat':639 //eatAnimation();640 break;641 case 'dead':642 animationFrame = deadAnimation(image, animationFrame);643 break;644 }645}646//user is closing the app.647appbit.onunload = () => {648 console.log("App data is being saved");649 saveState.data.saveTimer = new Date();650 //update current save state.651 fs.writeFileSync("save.txt", saveState, "json");...

Full Screen

Full Screen

player.js

Source:player.js Github

copy

Full Screen

1import Data from './data.js';2import Game from './game.js';3import SaveState from './save-state.js';4import Menu from './menu.js';5import CombatMenu from './menus/Combat.js';6import StatusMenu from './menus/Status.js';7import TextDisplayMenu from './menus/TextDisplay.js';8import combat from './combat.js';9import config from './config.js';10import map from './map.js';11import script from './script.js';12const stairTiles = [13 Data.mapTiles.STAIRS_UP,14 Data.mapTiles.STAIRS_DOWN,15 Data.mapTiles.STAIRS_DOWN_GRASS,16];17export default {18 isMoving: false,19 // Map collision tiles20 collisionTiles: [1, 2, 5, 9, 10, 11, 17, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],21 // Last direction the character was facing22 facingDirection: '',23 // Screen position24 x: 0,25 y: 0,26 // Tile number at player's location - see map.js for tile definitions27 currentTile: 0,28 // movement speed - frames per step (60 / movement = number of tiles moved per second)29 steps: 0,30 visibility: 0,31 radiant_in_effect: false,32 radiant_step_counter: 0,33 status: '',34 spell_blocked: false,35 render() {36 switch (this.facingDirection) {37 case "left":38 if (SaveState.carryingPrincess) {39 this.animatePlayer(66, 67);40 } else if (!this.hasWeapon() && !this.hasShield()) {41 this.animatePlayer(2, 3);42 } else if (this.hasWeapon() && !this.hasShield()) {43 this.animatePlayer(18, 19);44 } else if (!this.hasWeapon() && this.hasShield()) {45 this.animatePlayer(34, 35);46 } else {47 this.animatePlayer(50, 51);48 }49 break;50 case "right":51 if (SaveState.carryingPrincess) {52 this.animatePlayer(70, 71);53 } else if (!this.hasWeapon() && !this.hasShield()) {54 this.animatePlayer(6, 7);55 } else if (SaveState.player.weapon !== "none" && !this.hasShield()) {56 this.animatePlayer(22, 23);57 } else if (!this.hasWeapon() && this.hasShield()) {58 this.animatePlayer(38, 39);59 } else {60 this.animatePlayer(54, 55);61 }62 break;63 case "up":64 if (SaveState.carryingPrincess) {65 this.animatePlayer(68, 69);66 } else if (!this.hasWeapon() && !this.hasShield()) {67 this.animatePlayer(4, 5);68 } else if (SaveState.player.weapon !== "none" && !this.hasShield()) {69 this.animatePlayer(20, 21);70 } else if (!this.hasWeapon() && this.hasShield()) {71 this.animatePlayer(36, 37);72 } else {73 this.animatePlayer(52, 53);74 }75 break;76 case "down":77 default:78 if (SaveState.carryingPrincess) {79 this.animatePlayer(64, 65);80 } else if (!this.hasWeapon() && !this.hasShield()) {81 this.animatePlayer(0, 1);82 } else if (SaveState.player.weapon !== "none" && !this.hasShield()) {83 this.animatePlayer(16, 17);84 } else if (!this.hasWeapon() && this.hasShield()) {85 this.animatePlayer(32, 33);86 } else {87 this.animatePlayer(48, 49);88 }89 break;90 }91 },92 hasWeapon() {93 return SaveState.player.weapon !== 'none';94 },95 hasShield() {96 return SaveState.player.shield !== 'none';97 },98 animatePlayer(frame1, frame2) {99 const drawFrame = (Game.frameInRange(0, 14) || Game.frameInRange(30, 44)) ? frame1 : frame2;100 Game.drawCharacter(drawFrame, config.offsetX * config.tileWidth, config.offsetY * config.tileHeight);101 },102 // Map positioning103 // -------------------------------------------------------------------104 setPosition(map_name) {105 var map = Data.maps[map_name];106 this.steps = 0;107 this.setXY(map.player_start[0], map.player_start[1]);108 },109 setXY(x, y) {110 this.x = x;111 this.y = y;112 },113 // Movement and collision114 // -------------------------------------------------------------------115 move(direction) {116 let x = this.x;117 let y = this.y;118 let prev_steps = this.steps;119 this.setCurrentTile();120 map.setZone();121 this.facingDirection = direction;122 this.render();123 if (this.canMove()) {124 switch (direction) {125 case 'left':126 if (!this.willCollide(x - 1, y)) {127 this.x--;128 this.steps++;129 }130 break;131 case 'right':132 if (!this.willCollide(x + 1, y)) {133 this.x++;134 this.steps++;135 }136 break;137 case 'up':138 if (!this.willCollide(x, y - 1)) {139 this.y--;140 this.steps++;141 }142 break;143 case 'down':144 if (!this.willCollide(x, y + 1)) {145 this.y++;146 this.steps++;147 }148 break;149 }150 }151 if (this.steps > prev_steps && combat.triggerRandomEncounter()) {152 Game.states.push(new CombatMenu());153 Game.resetKeys();154 }155 },156 canMove() {157 return Game.frameNumber % config.movementSpeed == 0;158 },159 setCurrentTile() {160 this.currentTile = map.map_ptr.layout[this.x + (this.y * map.map_ptr.width)] - 1;161 },162 willCollide(x, y) {163 var next_tile = this.tileIndex(x, y);164 if (this.collisionTiles.indexOf(next_tile) > -1 || map.getNpcAt(x, y) !== null) {165 return true;166 }167 return false;168 },169 tileIndex(x, y) {170 return map.map_ptr.layout[x + (y * map.map_ptr.width)] - 1;171 },172 // Set stats173 // -------------------------------------------------------------------174 load_player: function() {175 this.set_level();176 this.set_max_hp();177 this.set_max_mp();178 this.set_strength();179 this.set_agility();180 this.set_attack_power();181 this.set_defense_power();182 this.set_spells();183 },184 set_level: function() {185 let i;186 for (i = 0; i < Data.levels.length; i++) {187 let level = Data.levels[i];188 if (SaveState.player.experience < level.required_exp) {189 break;190 }191 if (level.spells_learned) {192 level.spells_learned.forEach(spellId => {193 SaveState.player.spells[spellId] = Data.spells[spellId];194 });195 }196 }197 SaveState.player.level = i;198 },199 set_max_hp: function() {200 SaveState.player.maxHp = Data.levels[SaveState.player.level - 1].max_hp;201 },202 set_max_mp: function() {203 SaveState.player.maxMp = Data.levels[SaveState.player.level - 1].max_mp;204 },205 set_strength: function() {206 SaveState.player.strength = Data.levels[SaveState.player.level - 1].strength;207 },208 set_agility: function() {209 SaveState.player.agility = Data.levels[SaveState.player.level - 1].agility;210 },211 set_attack_power: function() {212 SaveState.player.attackPower = SaveState.player.strength + Data.weapons[SaveState.player.weapon].attack;213 },214 set_defense_power: function() {215 SaveState.player.defensePower = Math.floor(SaveState.player.agility / 2) +216 Data.armors[SaveState.player.armor].defense +217 Data.shields[SaveState.player.shield].defense;218 },219 set_spells: function() {220 var self = this;221 Object.keys(SaveState.player.spells).forEach(function (spellId) {222 let spell = SaveState.player.spells[spellId];223 });224 },225 // Item management226 // -------------------------------------------------------------------227 door() {228 let door = null;229 switch (this.facingDirection) {230 case 'left': door = map.getDoorAt(this.x - 1, this.y); break;231 case 'right': door = map.getDoorAt(this.x + 1, this.y); break;232 case 'up': door = map.getDoorAt(this.x, this.y - 1); break;233 case 'down': door = map.getDoorAt(this.x, this.y + 1); break;234 }235 if (door !== null) {236 //TODO: check for (and use) keys!237 SaveState.doorsOpened.push(door.id);238 map.refreshMap();239 }240 },241 stairs() {242 if (stairTiles.includes(this.currentTile)) {243 }244 },245 talk() {246 const x = this.x;247 const y = this.y;248 let character = null;249 let offsetX = 0;250 let offsetY = 0;251 switch (this.facingDirection) {252 case 'left': offsetX = -1; if (this.tileIndex(x - 1, y) == 2) { offsetX = -2; } break;253 case 'right': offsetX = 1; if (this.tileIndex(x + 1, y) == 2) { offsetX = 2; } break;254 case 'up': offsetY = -1; if (this.tileIndex(x, y - 1) == 2) { offsetY = -2; } break;255 case 'down': offsetY = 1; if (this.tileIndex(x, y + 1) == 2) { offsetY = 2; } break;256 }257 character = map.getNpcAt(x + offsetX, y + offsetY);258 Game.states.pop();259 Game.states.push(new TextDisplayMenu());260 if (character && typeof character.talk === 'function') {261 character.talk(script);262 } else {263 Game.displayText(Data.text.menu.talk_none);264 }265 },266 displayStatusMenu() {267 Game.states.push(new StatusMenu());268 },269 displayFieldSpells() {270 Menu.open('spells', this);271 },272 displayItemsMenu() {273 },274 search() {275 },276 take() {277 },278 add_item: function(item) {279 SaveState.player.inventory.push(item);280 },281 remove_item: function(item) {282 },283 // Non-static stat changes (combat or shop related)284 // -------------------------------------------------------------------285 gain_hp: function(amount) {286 SaveState.player.currentHp += amount;287 if (SaveState.player.currentHp > SaveState.player.maxHp) {288 SaveState.player.currentHp = SaveState.player.maxHp;289 }290 },291 lose_hp: function(amount) {292 SaveState.player.currentHp -= amount;293 if (SaveState.player.currentHp < 0) {294 SaveState.player.currentHp = 0;295 }296 },297 gain_mp: function(amount) {298 SaveState.player.currentMp += amount;299 if (SaveState.player.currentMp > SaveState.player.maxMp) {300 SaveState.player.currentMp = SaveState.player.maxMp;301 }302 },303 lose_mp: function(amount) {304 SaveState.player.currentMp -= amount;305 if ( SaveState.player.currentMp < 0) {306 SaveState.player.currentMp = 0;307 }308 },309 add_experience: function(amount) {310 SaveState.player.experience += amount;311 if (SaveState.player.experience >= 65535) {312 SaveState.player.experience = 65535;313 }314 },315 add_gold: function(amount) {316 SaveState.player.gold += amount;317 if (SaveState.player.gold > 99999) {318 SaveState.player.gold = 99999;319 }320 },321 remove_gold: function(amount) {322 SaveState.player.gold -= amount;323 if (SaveState.player.gold < 0) {324 SaveState.player.gold = 0;325 }326 },327 castSpell(spell) {328 // TODO - handle not enough MP329 if (SaveState.player.currentMp >= spell.cost) {330 spell.effect();331 }332 },...

Full Screen

Full Screen

monster.js

Source:monster.js Github

copy

Full Screen

1// Mandatory arguments2// id3// name4// abilities5//6// Form of stats in saveState: {bond: value, resilience: value, intellect: value, power: value}7var Monster = function(saveState){8 this.name = saveState.name;9 this.primaryTemplateId = saveState.primaryTemplateId;10 this.primaryTemplate = monsterTemplates[this.primaryTemplateId];11 this.secondaryTemplateId = eqOr(saveState.secondaryTemplateId, null);12 if(this.secondaryTemplateId){13 this.secondaryTemplate = monsterTemplates[this.secondaryTemplateId];14 }else{15 this.secondaryTemplate = null;16 }17 // Status18 this.destroyed = eqOr(saveState.destroyed, false);19 20 // Actions21 this.actionRunningDuration = (saveState.actionRunningDuration !== undefined) ? saveState.actionRunningDuration : 0;22 this.actionRunning = (saveState.actionRunning !== undefined) ? saveState.actionRunning : null;23 this.id = saveState.id;24 this.actionsElementId = this.id + '-action-family';25 this.profileElementId = this.id + '-monster-profile';26 this.actionsAreBusy = (saveState.actionsAreBusy !== undefined) ? saveState.actionsAreBusy : false;27 this.unlockedActions = eqOr(saveState.unlockedActions, this.primaryTemplate.actions);28 this.lockedActions = (saveState.lockedActions !== undefined) ? saveState.lockedActions : [];29 30 // Abilities31 this.abilitiesAreUnlocked = (saveState.abilitiesAreUnlocked !== undefined) ? saveState.abilitiesAreUnlocked : false;32 this.abilitiesAreTraining = (saveState.abilitiesAreTraining !== undefined) ? saveState.abilitiesAreTraining : false;33 this.abilityTraining = (saveState.abilityTraining !== undefined) ? saveState.abilityTraining : null;34 this.abilityTrainingDuration = (saveState.abilityTrainingDuration !== undefined) ? saveState.abilityTrainingDuration : 0;35 this.unlockedAbilities = (saveState.unlockedAbilities !== undefined) ? saveState.unlockedAbilities : [];36 this.lockedAbilities = eqOr(saveState.lockedAbilities, this.primaryTemplate.abilities);37 this.activeAbilities = (saveState.activeAbilities !== undefined) ? saveState.activeAbilities : [];38 this.trainedAbilities = (saveState.trainedAbilities !== undefined) ? saveState.trainedAbilities : [];39 40 // Stats41 this.unlockedStats = (saveState.unlockedStats !== undefined) ? saveState.unlockedStats : [42 'bond'43 ];44 this.lockedStats = (saveState.lockedStats !== undefined) ? saveState.lockedStats : [45 'resilience',46 'intellect',47 'power'48 ];49 if(saveState.stats){50 this.stats = {51 bond: new BondStat(this, saveState.stats.bond),52 resilience: new ResilienceStat(this, saveState.stats.resilience),53 intellect: new IntellectStat(this, saveState.stats.intellect),54 power: new PowerStat(this, saveState.stats.power),55 };56 }else{57 this.stats = {58 bond: new BondStat(this, 0),59 resilience: new ResilienceStat(this, 1),60 intellect: new IntellectStat(this, 1),61 power: new PowerStat(this, 1),62 };63 }64};65Monster.prototype.toSaveState = function(){66 var thing = {67 name: this.name,68 id: this.id,69 destroyed: this.destroyed,70 primaryTemplateId: this.primaryTemplateId, 71 secondaryTemplateId: this.secondaryTemplateId,72 73 // Actions74 actionRunningDuration: this.actionRunningDuration,75 actionRunning: this.actionRunning,76 profileElementId: this.profileElementId,77 actionsAreBusy: this.actionsAreBusy,78 unlockedActions: this.unlockedActions,79 lockedActions: this.lockedActions,80 81 // Abilities82 abilitiesAreUnlocked: this.abilitiesAreUnlocked,83 abilitiesAreTraining: this.abilitiesAreTraining,84 abilityTraining: this.abilityTraining,85 abilityTrainingDuration: this.abilityTrainingDuration,86 unlockedAbilities: this.unlockedAbilities,87 lockedAbilities: this.lockedAbilities,88 activeAbilities: this.activeAbilities,89 trainedAbilities: this.trainedAbilities,90 91 // Stats92 unlockedStats: this.unlockedStats,93 lockedStats: this.lockedStats,94 stats: {95 bond: this.stats.bond.level,96 resilience: this.stats.resilience.level,97 intellect: this.stats.intellect.level,98 power: this.stats.power.level99 }100 }101 return thing;102}103Monster.prototype.isAlive = function(){104 return !this.destroyed;105};106Monster.prototype.maxActiveAbilities = function(){107 return this.stats.intellect.level;108};109Monster.prototype.totalLevels = function(){110 var total = 0;111 $.each(this.stats, function(key, monsterStat){112 total += monsterStat.level;113 });114 return total;115}116Monster.prototype.setup = function(){117 var that = this;118 var actionsElement = $("#action-family-template").clone();119 actionsElement.attr('id', this.actionsElementId);120 actionsElement.find('.monster-name').text(this.name);121 $("#action-view").append(actionsElement);122 123 var profileElement = $("#monster-profile-template").clone();124 profileElement.attr('id', this.profileElementId);125 profileElement.find('.monster-name').text(this.name);126 $("#monster-view").append(profileElement);127 128 // Setup stats129 this.unlockedStats.forEach(function(id){130 that.stats[id].setup()131 });132 133 // Setup abilities134 this.unlockedAbilities.forEach(function(id){135 abilities[id].setup(that);136 });137 138 if(this.abilitiesAreUnlocked){139 $("#abilities").show();140 }else{141 $("#abilities").hide();142 }143 144 this.unlockedActions.forEach(function(id){145 var action = actions[id];146 action.setup(that);147 });148}149Monster.prototype.updateAbilities = function(){150 var that = this;151 $('#'+this.profileElementId+' .currently-active-abilities').text(this.activeAbilities.length);152 $('#'+this.profileElementId+' .max-active-abilities').text(this.maxActiveAbilities());153 this.lockedAbilities.forEach(function(id){154 var ability = abilities[id];155 if(ability.unlockedConditionsMet(that)){156 ability.unlock(that);157 }158 });159 this.unlockedAbilities.forEach(function(id){160 var ability = abilities[id];161 ability.update(that);162 });163}164Monster.prototype.update = function(){165 if(!this.abilitiesAreUnlocked){166 if(this.unlockedAbilities.length > 0){167 this.abilitiesAreUnlocked = true;168 $("#abilities").show();169 }170 }171 this.updateAbilities();172 173 var displayName = this.name;174 if(this.destroyed){175 var displayName = this.name + " (Destroyed)";176 }177 var actionsNameElement = $("#"+this.actionsElementId+" .monster-name");178 if(actionsNameElement.text() != displayName){179 actionsNameElement .text(displayName);180 }181 var profileNameElement = $("#"+this.profileElementId+" .monster-name");182 if(profileNameElement.text() != displayName){183 profileNameElement.text(displayName);184 }185 186 var displayType = this.primaryTemplate.name+'(' +this.primaryTemplate.type+')';187 if(this.secondaryTemplate){188 displayType += "/"+this.secondaryTemplate.name+'(' +this.secondaryTemplate.type+')';189 }190 var profileTypeElement = $("#"+this.profileElementId+" .monster-type");191 if(profileTypeElement.text() != displayType){192 profileTypeElement.text(displayType);193 }194}195Monster.prototype.kill = function(){196 this.destroyed = true;197 addLog('red', this.name + ' was destroyed!');198 if(null != this.abilityTraining){199 abilities[this.abilityTraining].cancelTraining(this);200 }201 if(null != this.actionRunning){202 actions[this.actionRunning].cancel(this);203 };204}205Monster.prototype.consume = function(enemy){206 var that = this;207 if('minion' == enemy.type){208 this.gainSpirit(40, 10);209 }else if('boss' == enemy.type){210 this.gainSpirit(100, 20);211 // Do nothing more if we already have a secondary template, or the new one is the same as our primary template212 if(this.secondaryTemplate){return;}213 if(this.primaryTemplateId == enemy.monsterTemplateId){return;}214 // Otherwise, gain a secondary template215 this.secondaryTemplateId = enemy.monsterTemplateId;216 this.secondaryTemplate = monsterTemplates[this.secondaryTemplateId];217 this.secondaryTemplate.abilities.forEach(function(ability){218 if(!that.lockedAbilities.includes(ability) && !that.unlockedAbilities.includes(ability)){219 that.lockedAbilities.push(ability);220 }221 });222 addLog("green", this.name+" gained additional monster type "+this.secondaryTemplate.name);223 }224}225Monster.prototype.gainSpirit = function(value, special_value=0){226 if(abilities.sharedHealing.isActive(this) && state.character.diminished > 0){227 var amountToSiphon = this.stats.power.level;228 if(amountToSiphon > value){229 amountToSiphon = value;230 }231 if(amountToSiphon > state.character.diminished){232 amountToSiphon = state.character.diminished;233 }234 state.character.diminished -= amountToSiphon;235 addLog('red', "Orphan healed "+amountToSiphon+" points of damage.");236 if(state.character.diminished <= 0){237 addLog('red', "Orphan fully healed.");238 }239 value = value - amountToSiphon;240 }241 state.resources.spirit.change(value);242 specialResourceId = state.getCurrentRegion().specialResourceId243 if(null != specialResourceId){244 state.resources[specialResourceId].change(special_value);245 }...

Full Screen

Full Screen

state.js

Source:state.js Github

copy

Full Screen

1var state = {}23var State = function(saveState){4 var that = this;5 this.currentTime = (saveState.currentTime !== undefined) ? saveState.currentTime : null;6 this.lastTime = (saveState.lastTime !== undefined) ? saveState.lastTime : null;7 this.timeSinceLastUpdate = (saveState.timeSinceLastUpdate !== undefined) ? saveState.timeSinceLastUpdate : null;8 this.ambushClock = eqOr(saveState.ambushClock, getAmbushClock());9 this.selectedTab = (saveState.selectedTab !== undefined) ? saveState.selectedTab : 'action';10 this.mode = eqOr(saveState.mode, 'standard'); // Valid: 'standard', 'battle' 11 12 // Simple Trackers13 this.log = (saveState.log !== undefined) ? saveState.log : [];14 this.unlockedResources = (saveState.unlockedResources !== undefined) ? saveState.unlockedResources : [];15 this.currentRegion = (saveState.currentRegion !== undefined) ? saveState.currentRegion : null;16 this.unlockedRegions = (saveState.unlockedRegions !== undefined) ? saveState.unlockedRegions : [];17 this.lockedRegions = (saveState.lockedRegions !== undefined) ? saveState.lockedRegions : [];18 19 // Game Progress20 this.tabsAreUnlocked = (saveState.tabsAreUnlocked !== undefined) ? saveState.tabsAreUnlocked : false;21 this.orphanIsUnlocked = (saveState.orphanIsUnlocked !== undefined) ? saveState.orphanIsUnlocked : false;22 this.regionsAreUnlocked = (saveState.regionsAreUnlocked !== undefined) ? saveState.regionsAreUnlocked : false;23 24 // Complex Trackers25 26 this.monsters = [];27 saveState.monsters.forEach(function(monsterState){28 that.monsters.push(new Monster(monsterState));29 });30 31 this.regions = {};32 regionDefinitions.forEach(function(definition){33 that.regions[definition.id] = new Region(definition);34 });35 if(saveState.regions){36 saveState.regions.forEach(function(regionState){37 that.regions[regionState.id].awareness = regionState.awareness;38 that.regions[regionState.id].traveling = regionState.traveling;39 that.regions[regionState.id].bossId = regionState.bossId;40 that.regions[regionState.id].minionId = regionState.minionId;41 });42 }4344 this.resources = {};45 resourceDefinitions.forEach(function(definition){46 that.resources[definition.id] = new Resource(definition.id, definition.name);47 });48 if(saveState.resources){49 saveState.resources.forEach(function(resourceState){50 that.resources[resourceState.id].value = resourceState.value;51 });52 }53 54 this.character = new Character(saveState.character);55 56 57 if('battle' == this.mode){58 this.battle = new Battle(saveState.battle);59 }else{60 this.battle = null;61 }62};6364State.prototype.toSaveState = function(){65 var that = this;66 thing = {67 currentTime: this.currentTime,68 lastTime: this.lastTime,69 timeSinceLastUpdate: this.timeSinceLastUpdate,70 ambushClock: this.ambushClock,71 selectedTab: this.selectedTab,72 mode: this.mode,73 log: this.log,74 unlockedResources: this.unlockedResources,75 currentRegion: this.currentRegion,76 unlockedRegions: this.unlockedRegions,77 lockedRegions: this.lockedRegions,78 tabsAreUnlocked: this.tabsAreUnlocked,79 orphanIsUnlocked: this.orphanIsUnlocked,80 regionsAreUnlocked: this.regionsAreUnlocked81 }82 if('battle' == this.mode){83 thing.battle = this.battle.toSaveState();84 }85 86 thing.monsters = [];87 this.monsters.forEach(function(monster){88 thing.monsters.push(monster.toSaveState());89 });90 91 thing.regions = [];92 regionDefinitions.forEach(function(definition){93 region = that.regions[definition.id];94 thing.regions.push(region.toSaveState());95 });96 97 thing.resources = [];98 resourceDefinitions.forEach(function(resource){99 thing.resources.push({id: resource.id, value: that.resources[resource.id].value}); 100 });101 102 thing.character = state.character.toSaveState();103 return thing;104}105106State.prototype.getCurrentRegion = function(){107 return this.regions[this.currentRegion];108}109110State.prototype.getTeammate = function(id){111 if('character' == id){112 return this.character;113 }else{114 return this.monsters.find(function(monster){ return monster.id == id });115 }116}117118State.prototype.addTeammate = function(templateId){119 var monster = {};120 monster.id = 'monster-' + (this.monsters.length+1);121 monster.name = "Captured Monster";122 monster.primaryTemplateId = templateId;123 monster = new Monster(monster);124 this.monsters.push(monster);125 monster.setup();126}127128129var newGameState = function(){130 var lockedRegions = []131 regionDefinitions.forEach(function(regionDefinition){132 lockedRegions.push(regionDefinition.id);133 });134 var currentRegion = "blackenedWasteland";135 136 // Create all monsters137 var monsters = [138 {139 id: 'monster-1',140 name: "Monster One",141 primaryTemplateId: 'genericMonster'142 }143 ]144 145 var character = {146 name: "Wayward Orphan"147 }148 149 150 return new State({151 lockedRegions: lockedRegions,152 currentRegion: currentRegion,153 monsters: monsters,154 character: character155 }); ...

Full Screen

Full Screen

video_bumper_spec.js

Source:video_bumper_spec.js Github

copy

Full Screen

1(function (WAIT_TIMEOUT) {2 'use strict';3 describe('VideoBumper', function () {4 var state, oldOTBD, waitForPlaying;5 waitForPlaying = function (state) {6 waitsFor(function () {7 return state.el.hasClass('is-playing');8 }, 'Player is not playing.', WAIT_TIMEOUT);9 };10 beforeEach(function () {11 oldOTBD = window.onTouchBasedDevice;12 window.onTouchBasedDevice = jasmine13 .createSpy('onTouchBasedDevice').andReturn(null);14 state = jasmine.initializePlayer('video_with_bumper.html');15 $('.poster .btn-play').click();16 jasmine.Clock.useMock();17 });18 afterEach(function () {19 $('source').remove();20 state.storage.clear();21 if (state.bumperState && state.bumperState.videoPlayer) {22 state.bumperState.videoPlayer.destroy();23 }24 if (state.videoPlayer) {25 state.videoPlayer.destroy();26 }27 window.onTouchBasedDevice = oldOTBD;28 });29 it('can render the bumper video', function () {30 expect($('.is-bumper')).toExist();31 });32 it('can show the main video on error', function () {33 state.el.trigger('error');34 jasmine.Clock.tick(20);35 expect($('.is-bumper')).not.toExist();36 waitForPlaying(state);37 });38 it('can show the main video once bumper ends', function () {39 state.el.trigger('ended');40 jasmine.Clock.tick(20);41 expect($('.is-bumper')).not.toExist();42 waitForPlaying(state);43 });44 it('can show the main video on skip', function () {45 state.bumperState.videoBumper.skip();46 jasmine.Clock.tick(20);47 expect($('.is-bumper')).not.toExist();48 waitForPlaying(state);49 });50 it('can stop the bumper video playing if it is too long', function () {51 state.el.trigger('timeupdate', [state.bumperState.videoBumper.maxBumperDuration + 1]);52 jasmine.Clock.tick(20);53 expect($('.is-bumper')).not.toExist();54 waitForPlaying(state);55 });56 it('can save appropriate states correctly on ended', function () {57 var saveState = jasmine.createSpy('saveState');58 state.bumperState.videoSaveStatePlugin.saveState = saveState;59 state.el.trigger('ended');60 jasmine.Clock.tick(20);61 expect(saveState).toHaveBeenCalledWith(true, {62 bumper_last_view_date: true});63 });64 it('can save appropriate states correctly on skip', function () {65 var saveState = jasmine.createSpy('saveState');66 state.bumperState.videoSaveStatePlugin.saveState = saveState;67 state.bumperState.videoBumper.skip();68 expect(state.storage.getItem('isBumperShown')).toBeTruthy();69 jasmine.Clock.tick(20);70 expect(saveState).toHaveBeenCalledWith(true, {71 bumper_last_view_date: true});72 });73 it('can save appropriate states correctly on error', function () {74 var saveState = jasmine.createSpy('saveState');75 state.bumperState.videoSaveStatePlugin.saveState = saveState;76 state.el.trigger('error');77 expect(state.storage.getItem('isBumperShown')).toBeTruthy();78 jasmine.Clock.tick(20);79 expect(saveState).toHaveBeenCalledWith(true, {80 bumper_last_view_date: true});81 });82 it('can save appropriate states correctly on skip and do not show again', function () {83 var saveState = jasmine.createSpy('saveState');84 state.bumperState.videoSaveStatePlugin.saveState = saveState;85 state.bumperState.videoBumper.skipAndDoNotShowAgain();86 expect(state.storage.getItem('isBumperShown')).toBeTruthy();87 jasmine.Clock.tick(20);88 expect(saveState).toHaveBeenCalledWith(true, {89 bumper_last_view_date: true, bumper_do_not_show_again: true});90 });91 it('can destroy itself', function () {92 state.bumperState.videoBumper.destroy();93 expect(state.videoBumper).toBeUndefined();94 });95 });...

Full Screen

Full Screen

AppStateProvider.jsx

Source:AppStateProvider.jsx Github

copy

Full Screen

1import React, { createContext, useReducer } from 'react';2import doneeInfo from '../resources/DoneeData/donee-info';3export const AppContext = createContext();4const initialState = {5 isLoggedIn: false,6 userId: null,7 userEmail: null,8 Token: null,9 donees: doneeInfo,10 applicationForm: {11 dob: '',12 userId: '',13 firstName: '',14 lastName: '',15 homeAddress: '',16 country: '',17 itemNeeded: '',18 reasonForApplication: '',19 imageLink: '',20 letterOfRecommendationLink: '',21 nationalIdLink: '',22 orgName: '',23 orgWebsite: '',24 orgContact: '',25 signature: '',26 phoneNumber: '',27 gender: '',28 eduLevel: '',29 },30 completedTabs: [],31 userOTP: 0,32};33function reducer(state, action) {34 let saveState = { ...state };35 if (action.type === 'REGISTER') {36 saveState.isLoggedIn = false;37 saveState.userName = action.payload.username;38 saveState.userId = action.payload.userId;39 saveState.userEmail = action.payload.userEmail;40 saveState.userRole = action.payload.userRole;41 }42 if (action.type === 'SAVE_OTP') {43 saveState.userOTP = action.payload.userOTP;44 }45 if (action.type === 'SAVE_EMAIL') {46 saveState.userEmail = action.payload.userEmail;47 }48 if (action.type === 'LOGIN') {49 saveState.isLoggedIn = true;50 saveState.userId = action.payload.userId;51 saveState.userEmail = action.payload.userEmail;52 saveState.Token = action.payload.Token;53 }54 if (action.type === 'UPDATE_EMAIL') {55 saveState.userEmail = action.payload.userEmail;56 }57 if (action.type === 'LOGOUT') {58 saveState.isLoggedIn = false;59 saveState.userId = null;60 saveState.userEmail = null;61 saveState.token = null;62 }63 if (action.type === 'DONEE_APPLICATION') {64 saveState.isLoggedIn = true;65 saveState.donees = [...saveState.donees, action.payload.donee];66 }67 if (action.type === 'DONOR_APPLICATION') {68 saveState.isLoggedIn = true;69 saveState.donors = action.payload.donor;70 }71 if (action.type === 'SELECT_IMAGE') {72 saveState.imageSelectedPass = action.payload.imageSelectedPass;73 }74 if (action.type === 'SELECT_LETTER') {75 saveState.imageSelectedLetter = action.payload.imageSelectedLetter;76 }77 if (action.type === 'SELECT_ID') {78 saveState.imageSelectedID = action.payload.imageSelectedID;79 }80 if (action.type === 'SAVE_IMAGES') {81 saveState.imageUploadPass = action.payload.imageUploadedPass;82 saveState.imageUploadLetter = action.payload.imageUploadedLetter;83 saveState.imageUploadID = action.payload.imageUploadedID;84 }85 if (action.type === 'UPDATE_APPLICATION_FORM')86 saveState.applicationForm = { ...saveState.applicationForm, ...action.payload }87 if (action.type === 'SET_ACTIVE_TAB')88 saveState.setActiveTab = action.payload;89 if (action.type === 'ADD_COMPLETED_STEP')90 saveState.completedTabs = [...saveState.completedTabs, action.payload];91 // if (action.type === 'UPDATE_DONEELIST')92 // saveState.isLoggedIn = false;93 // saveState.donees = [action.payload, ...saveState.donees];94 return saveState;95}96function AppStateProvider({ children }) {97 const [appstate, dispatch] = useReducer(reducer, initialState);98 const contextObject = {99 state: appstate,100 dispatch: dispatch,101 };102 return (103 <AppContext.Provider value={contextObject}>104 {children}105 </AppContext.Provider>106 );107}...

Full Screen

Full Screen

AppStates.jsx

Source:AppStates.jsx Github

copy

Full Screen

1import { createContext,useReducer} from 'react';2export const AppContext = createContext();3const initialState = {4 isLoggedIn: false,5 userId: null,6 userEmail: null,7 userTasks:[],8 title:"",9 description:"",10 isEditing:false,11 currentlyEditing:"",12 13};14function reducer (state, action) {15 let saveState = {...state};16 // set the name on our state copy to action17 saveState.action = action;18 if (action.type === 'ADD_TASK') {19 if(saveState.isEditing){20 saveState.userTasks = saveState.userTasks.map(21 todo=> {22 if(todo.id === saveState.currentlyEditing){ 23 todo.title = saveState.title;24 todo.description = saveState.description;25 }26 return todo;27 }28 );29 }30 else {31 return {32 ...state,33 userTasks:[action.payload, ...state.userTasks],34 };35 //saveState.userTasks.push(action.payload);36 }37 38 // return {39 // ...state,40 // userTasks:[action.payload, ...state.userTasks],41 // };42 }43 if (action.type === 'SET_TASK') {44 //saveState.userTasks = action.payload;45 return {46 ...state,47 userTasks: action.payload,48 };49 }50 if (action.type === 'REGISTER') {51 52 saveState.isLoggedIn=false;53 saveState.userEmail=action.payload.userEmail;54 saveState.userId=action.payload.userId;55 // return {56 // ...state,57 // isLoggedIn:false,58 // ...action.payload,59 // };60 }61 if (action.type === 'LOGIN') {62 saveState.isLoggedIn=true;63 saveState.userEmail=action.payload.userEmail;64 saveState.userId=action.payload.userId;65 }66 // return {67 // ...state,68 // isLoggedIn:true,69 // ...action.payload,70 // };71 // }72 if (action.type === 'LOGOUT') {73 saveState.isLoggedIn = false;74 saveState.userEmail=null;75 saveState.userId=null;76 // return {77 // // // ...state,78 // // isLoggedIn: false,79 // // userEmail: null,80 // // userId: null,81 // };82 }83 if (action.type === 'DELETE') {84 saveState.userTasks = saveState.userTasks.filter(todo => todo.id!== action.payload.id);85 }86 87 if (action.type === 'EDIT') {88 saveState.title = action.payload.title;89 saveState.description = action.payload.description;90 saveState.isEditing = true;91 saveState.currentlyEditing =action.payload.id;92 }93 if (action.type === 'UPDATE_TITLE'){94 saveState.title = action.payload;95 }96 97 if (action.type === 'UPDATE_DESC'){98 saveState.description = action.payload;99 }100 101 if (action.type === 'RESET_INPUTS'){102 saveState.title="";103 saveState.description="";104 }105 106 return saveState;107 }108 109export default function AppStates({children }) {110 const [appstate, dispatch] = useReducer(reducer, initialState);111 112 const ContextObject ={113 state: appstate,114 dispatch: dispatch,115 };116 117 118 return (119 <AppContext.Provider value={ContextObject}>120 {children}121 </AppContext.Provider>122 );...

Full Screen

Full Screen

stateprovider.jsx

Source:stateprovider.jsx Github

copy

Full Screen

1import { useEffect } from 'react';2import { createContext, useReducer } from 'react';3import mentorData from '../store/mentor-data';4export const AppContext = createContext();5const initialState = {6 isLoggedIn: false,7 userId: null,8 userEmail: null,9 mentors: mentorData,10};11function reducer(state, action) {12 let saveState = { ...state };13 if (action.type === 'REGISTER') {14 saveState.isLoggedIn = false;15 saveState.userEmail = action.payload.userEmail;16 saveState.userId = action.payload.userId;17 }18 if (action.type === 'SELECT_IMAGE') {19 saveState.imageSelected = action.payload.imageSelected;20 }21 if (action.type === 'SAVE_IMAGE') {22 saveState.imageUploaded = action.payload.imageUploaded;23 }24 if (action.type === 'REGISTER_MENTOR') {25 saveState.isLoggedIn = false;26 saveState.mentors = [action.payload.mentorUser, ...saveState.mentors];27 //saveState.mentorUser = action.payload.mentorUser;28 //saveState.mentors.unshift(action.payload.mentorUser)29 }30 if (action.type === 'UPDATE_MENTORLIST') {31 saveState.isLoggedIn = false;32 saveState.mentors = [...action.payload, ...saveState.mentors];33 }34 if (action.type === 'LOGIN') {35 saveState.isLoggedIn = true;36 saveState.userEmail = action.payload.userEmail;37 saveState.userId = action.payload.userId;38 }39 if (action.type === 'LOGOUT') {40 saveState.isLoggedIn = false;41 saveState.userEmail = null;42 saveState.userId = null;43 }44 return saveState;45}46export default function AppStates({ children }) {47 const [appstate, dispatch] = useReducer(reducer, initialState);48 const ContextObject = {49 state: appstate,50 dispatch: dispatch,51 };52 useEffect(() => {53 let storage = localStorage.getItem('mentor-list');54 let mentorListInStorage = storage ? JSON.parse(storage) : [];55 dispatch({56 type: 'UPDATE_MENTORLIST',57 payload: mentorListInStorage58 })59 }, [])60 return (61 <AppContext.Provider value={ContextObject}>62 {children}63 </AppContext.Provider>64 );...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.saveState()2cy.restoreState()3cy.clearState()4cy.saveState()5cy.restoreState()6cy.clearState()7{8}9{10}11{12 "env": {13 }14}15{16 "env": {17 }18}

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('saveState', () => {2 cy.window().then((win) => {3 win.sessionStorage.clear();4 cy.log('Session storage cleared');5 });6 cy.window().then((win) => {7 win.localStorage.clear();8 cy.log('Local storage cleared');9 });10});11describe('Test', () => {12 beforeEach(() => {13 cy.saveState();14 });15 it('Test', () => {16 cy.log('Test');17 });18});19describe('Test', () => {20 beforeEach(() => {21 cy.saveState();22 });23 it('Test', () => {24 cy.log('Test');25 });26});27describe('Test', () => {28 beforeEach(() => {29 cy.saveState();30 });31 it('Test', () => {32 cy.log('Test');33 });34});35describe('Test', () => {36 beforeEach(() => {37 cy.saveState();38 });39 it('Test', () => {40 cy.log('Test');41 });42});43describe('Test', () => {44 beforeEach(() => {45 cy.saveState();46 });47 it('Test', () => {48 cy.log('Test');49 });50});51describe('Test', () => {52 beforeEach(() => {53 cy.saveState();54 });55 it('Test', () => {56 cy.log('Test');57 });58});59describe('Test', () => {60 beforeEach(() => {61 cy.saveState();62 });63 it('Test', () => {64 cy.log('Test');65 });66});67describe('Test', () => {68 beforeEach(() => {69 cy.saveState();70 });71 it('Test', () => {72 cy.log('Test');73 });74});75describe('Test', () => {76 beforeEach(() => {

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.saveState();2cy.loadState();3cy.clearState();4cy.saveStateSnapshot();5cy.loadStateSnapshot();6cy.clearStateSnapshot();7cy.saveStateSnapshot();8cy.loadStateSnapshot();9cy.clearStateSnapshot();10cy.saveStateSnapshot();11cy.loadStateSnapshot();12cy.clearStateSnapshot();13cy.saveStateSnapshot();14cy.loadStateSnapshot();15cy.clearStateSnapshot();16cy.saveStateSnapshot();17cy.loadStateSnapshot();18cy.clearStateSnapshot();19cy.saveStateSnapshot();20cy.loadStateSnapshot();21cy.clearStateSnapshot();22cy.saveStateSnapshot();23cy.loadStateSnapshot();24cy.clearStateSnapshot();25cy.saveStateSnapshot();26cy.loadStateSnapshot();27cy.clearStateSnapshot();28cy.saveStateSnapshot();29cy.loadStateSnapshot();30cy.clearStateSnapshot();31cy.saveStateSnapshot();32cy.loadStateSnapshot();

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.saveState();2cy.loadState();3cy.clearState();4cy.saveState('myState');5cy.loadState('myState');6cy.clearState('myState');7cy.saveState('myState', { foo: 'bar' });8cy.loadState('myState', { foo: 'bar' });9cy.clearState('myState', { foo: 'bar' });10cy.saveState();11cy.loadState();12cy.clearState();13cy.saveState('myState');14cy.loadState('myState');15cy.clearState('myState');16cy.saveState('myState', { foo: 'bar' });17cy.loadState('myState', { foo: 'bar' });18cy.clearState('myState', { foo: 'bar' });19cy.saveState();20cy.loadState();21cy.clearState();22cy.saveState('myState');23cy.loadState('myState');24cy.clearState('myState');25cy.saveState('myState', { foo: 'bar' });26cy.loadState('myState', { foo: 'bar' });27cy.clearState('myState', { foo

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.saveState();2cy.restoreState();3describe('My Test Suite', () => {4 before(() => {5 cy.saveState();6 });7 it('My Test Case', () => {8 });9 afterEach(() => {10 cy.restoreState();11 });12});13MIT © [prashant-andani](

Full Screen

Using AI Code Generation

copy

Full Screen

1beforeEach(() => {2 cy.saveState();3});4afterEach(() => {5 cy.restoreState();6});7beforeEach(() => {8 cy.saveState();9});10afterEach(() => {11 cy.restoreState();12});13beforeEach(() => {14 cy.saveState();15});16afterEach(() => {17 cy.restoreState();18});19beforeEach(() => {20 cy.saveState();21});22afterEach(() => {23 cy.restoreState();24});25beforeEach(() => {26 cy.saveState();27});28afterEach(() => {29 cy.restoreState();30});31beforeEach(() => {32 cy.saveState();33});34afterEach(() => {35 cy.restoreState();36});37beforeEach(() => {38 cy.saveState();39});40afterEach(() => {41 cy.restoreState();42});43beforeEach(() => {44 cy.saveState();

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2 it('Save state', function() {3 cy.saveState()4 })5})6Cypress.Commands.add('saveState', () => {7 cy.window().then(win => {8 cy.writeFile('cypress/fixtures/state.json', win.sessionStorage)9 })10})

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful