Best JavaScript code snippet using cypress
trackswitcher.js
Source:trackswitcher.js
1"use strict";2class Shape {3 constructor(points, front, rear) {4 this.points = points;5 this.front = front || new Coords2D(1, 0);6 this.rear = rear || new Coords2D(-1, 0);7 }8 rotate(rad) {9 return new Shape(10 this.points.map(P => P.rotate(rad)),11 this.front.rotate(rad),12 this.rear.rotate(rad),13 );14 }15}16class EngineShape extends Shape {17 constructor(points) {18 super(points || [19 new Coords2D(-1, -0.4),20 new Coords2D(0.7, -0.4),21 new Coords2D(1.0, 0.0),22 new Coords2D(0.7, 0.4),23 new Coords2D(-1, 0.4),24 ]);25 }26}27class WagonShape extends Shape {28 constructor(points) {29 super(points || [30 new Coords2D(-1, -0.4),31 new Coords2D(1, -0.4),32 new Coords2D(1, 0.4),33 new Coords2D(-1, 0.4),34 ]);35 }36}37class BlockShape extends Shape {38 constructor(points) {39 super(points || [40 // Cross41 // new Coords2D(-0.8, -0.3),42 // new Coords2D(0.0, -0.1),43 // new Coords2D(0.8, -0.3),44 // new Coords2D(1.0, -0.2),45 // new Coords2D(0.1, 0.0),46 // new Coords2D(1.0, 0.2),47 // new Coords2D(0.8, 0.3),48 // new Coords2D(0.0, 0.1),49 // new Coords2D(-0.8, 0.3),50 // new Coords2D(-1.0, 0.2),51 // new Coords2D(-0.1, 0.0),52 // new Coords2D(-1.0, -0.2),53 // Bar54 new Coords2D(-0.8, -0.25),55 new Coords2D(0.8, -0.25),56 new Coords2D(0.8, 0.25),57 new Coords2D(-0.8, 0.25),58 ]);59 }60}61class Track {62 static SF = 0.85;63 constructor(name, x1, y1, x2, y2, angle) {64 this.name = name;65 this.from = new Coords2D(x1, y1);66 this.to = new Coords2D(x2, y2);67 if (x1 > x2 /*|| (x1 == x2 && y1 > y2)*/) {68 [this.from, this.to] = [this.to, this.from];69 }70 this.center = new Coords2D((this.from.x + this.to.x) / 2, (this.from.y + this.to.y) / 2);71 this.angle = angle;72 }73 get slope() {74 return Math.round((this.from.y - this.to.y) / (this.from.x - this.to.x) * 100) / 100;75 }76 getShape(model) {77 const angle = this.angle;78 return model.rotate(angle / 180 * Math.PI);79 }80 getEnds(game, model) {81 const center = game.scale(this.center);82 const shape = this.getShape(model);83 const front = center.add(shape.front.multiply(TrackSwitcher.SQUARE * Track.SF));84 const rear = center.add(shape.rear.multiply(TrackSwitcher.SQUARE * Track.SF));85 return [front, rear];86 }87 touchesTrack(other) {88 return other.touchesCoord(this.from) || other.touchesCoord(this.to);89 }90 touchesCoord(C) {91 return C.equal(this.from) || C.equal(this.to);92 }93 drawLine(game, color, width) {94 game.drawLine(game.scale(this.from), game.scale(this.to), {color, width});95 }96 drawTrainBacklight(game) {97 this.drawLine(game, TrackSwitcher.TRAIN_COLOR, TrackSwitcher.TRAIN_WIDTH);98 game.drawDot(game.scale(this.from), {99 color: TrackSwitcher.TRAIN_COLOR,100 radius: TrackSwitcher.TRAIN_WIDTH/2,101 });102 game.drawDot(game.scale(this.to), {103 color: TrackSwitcher.TRAIN_COLOR,104 radius: TrackSwitcher.TRAIN_WIDTH/2,105 });106 }107 drawRoute(game) {108 this.drawLine(game, TrackSwitcher.ROUTE_COLOR, TrackSwitcher.ROUTE_WIDTH);109 }110 drawTrackOuter(game) {111 this.drawLine(game, TrackSwitcher.TRACK_COLOR, TrackSwitcher.TRACK_WIDTH);112 }113 drawTrackInner(game) {114 this.drawLine(game, TrackSwitcher.BGCOLOR, TrackSwitcher.TRACK_INNER);115 }116 drawShape(game, model, color, reverse = false) {117 const center = game.scale(this.center);118 const angle = this.angle + (reverse ? 180 : 0);119 const shape = model.rotate(angle / 180 * Math.PI);120 game.ctx.fillStyle = color;121 game.ctx.beginPath();122 shape.points.forEach((point, i) => {123 const C = center.add(point.multiply(TrackSwitcher.SQUARE * Track.SF));124 game.ctx[i == 0 ? 'moveTo' : 'lineTo'](C.x, C.y);125 });126 game.ctx.closePath();127 game.ctx.fill();128 }129 drawEnds(game, model) {130 const [front, rear] = this.getEnds(game, model);131 game.drawDot(front, {radius: 3});132 game.drawDot(rear, {radius: 3});133 }134 drawEngine(game, car) {135 const color = car ? TrackSwitcher.CAR_COLORS[car.id] : TrackSwitcher.WAGON_COLOR;136 this.drawShape(game, TrackSwitcher.SHAPE_ENGINE, color, car ? car.direction == -1 : false);137 this.drawEnds(game, TrackSwitcher.SHAPE_ENGINE);138 }139 drawWagon(game, car) {140 const color = car ? TrackSwitcher.CAR_COLORS[car.id] : TrackSwitcher.WAGON_COLOR;141 this.drawShape(game, TrackSwitcher.SHAPE_WAGON, color);142 this.drawEnds(game, TrackSwitcher.SHAPE_WAGON);143 }144 drawBlock(game) {145 this.drawShape(game, TrackSwitcher.SHAPE_BLOCK, TrackSwitcher.BLOCK_COLOR);146 // const from = game.scale(this.from);147 // const to = game.scale(this.to);148 // game.drawLine(from, to, {color: TrackSwitcher.BLOCK_COLOR, width: TrackSwitcher.TRACK_WIDTH});149 }150}151class CircularTrack extends Track {152 constructor(name, x1, y1, x2, y2, angle, cx, cy, dcx, dcy, radius, startAngle, endAngle) {153 super(name, x1, y1, x2, y2, angle);154 this.center = new Coords2D(cx, cy);155 this.drawCenter = new Coords2D(dcx, dcy);156 this.radius = radius;157 this.startAngle = startAngle;158 this.endAngle = endAngle;159 }160 drawArc(game, color, width) {161 const C = game.scale(this.drawCenter);162 game.ctx.strokeStyle = color;163 game.ctx.lineWidth = width;164 game.ctx.beginPath();165 game.ctx.arc(C.x, C.y, this.radius * TrackSwitcher.SQUARE, this.startAngle, this.endAngle);166 game.ctx.stroke();167 }168 drawTrainBacklight(game) {169 this.drawArc(game, TrackSwitcher.TRAIN_COLOR, TrackSwitcher.TRAIN_WIDTH);170 game.drawDot(game.scale(this.from), {171 color: TrackSwitcher.TRAIN_COLOR,172 radius: TrackSwitcher.TRAIN_WIDTH/2,173 });174 game.drawDot(game.scale(this.to), {175 color: TrackSwitcher.TRAIN_COLOR,176 radius: TrackSwitcher.TRAIN_WIDTH/2,177 });178 }179 drawRoute(game) {180 this.drawArc(game, TrackSwitcher.ROUTE_COLOR, TrackSwitcher.ROUTE_WIDTH);181 }182 drawTrackOuter(game) {183 this.drawArc(game, TrackSwitcher.TRACK_COLOR, TrackSwitcher.TRACK_WIDTH);184 }185 drawTrackInner(game) {186 this.drawArc(game, TrackSwitcher.BGCOLOR, TrackSwitcher.TRACK_INNER);187 }188}189class TrackConn {190 constructor(from, to, x, y) {191 this.from = from;192 this.to = to;193 this.button = new Coords2D(x, y);194 }195}196class Route {197 constructor(game, start) {198 this.game = game;199 this.tracks = [start];200 }201 get length() {202 return this.tracks.length;203 }204 get first() {205 return this.tracks[0];206 }207 get last() {208 return this.tracks[this.tracks.length - 1];209 }210 get beforeLast() {211 return this.tracks[this.tracks.length - 2];212 }213 get head() {214 if (this.tracks.length < 2) return null;215 const last = this.last;216 const beforeLast = this.beforeLast;217 return last.from.equal(beforeLast.from) || last.from.equal(beforeLast.to) ? last.to : last.from;218 }219 connectsTo(track) {220 if (this.head) {221 return track.touchesCoord(this.head);222 }223 return track.touchesTrack(this.last);224 }225 includes(track) {226 return this.tracks.includes(track);227 }228 clone() {229 const route = new Route(this.game, null);230 route.tracks = [...this.tracks];231 return route;232 }233 reverse() {234 const route = this.clone();235 route.tracks.reverse();236 return route;237 }238 add(track) {239 this.tracks.push(track);240 }241 forward(track, train) {242 const fromTracks = this.tracks.slice(-train.length).map(T => T.name);243 this.tracks.push(track);244 this.moveCars(train, fromTracks);245 }246 backward(train) {247 const fromTracks = this.tracks.slice(-train.length).map(T => T.name);248 this.tracks.pop();249 this.moveCars(train, fromTracks);250 }251 moveCars(train, fromTracks) {252 const toTracks = this.tracks.slice(-train.length).map(T => T.name);253// console.log(fromTracks, toTracks);254 train.cars.forEach(car => {255 const i = fromTracks.indexOf(car.location);256 this.moveCar(car, car.location, toTracks[i]);257 });258 }259 moveCar(car, fromTrack, toTrack) {260 car.location = toTrack;261 if (TrackSwitcher.REVERSERS.includes(`${fromTrack}:${toTrack}`) || TrackSwitcher.REVERSERS.includes(`${toTrack}:${fromTrack}`)) {262 car.reverse();263 }264 }265}266class Train {267 constructor(route, car) {268 this.route = route;269 this.cars = [car];270 }271 get length() {272 return this.cars.length;273 }274 connectsTo(track) {275 return this.route.connectsTo(track);276 }277 add(car, track) {278 if (!this.cars.includes(car)) {279 this.cars.push(car);280 this.route.add(track);281 return true;282 }283 }284 canMove() {285 return this.cars.some(car => car instanceof Engine);286 }287}288class Problem {289 constructor(moves, froms, tos) {290 this.moves = moves;291 this.froms = froms;292 this.tos = tos;293 }294}295class Wagon {296 constructor(id, location) {297 this.id = id;298 this.location = location;299 }300 get model() {301 return TrackSwitcher.SHAPE_WAGON;302 }303 get movable() {304 return true;305 }306 draw(game) {307 const track = game.getTrack(this.location);308 track.drawWagon(game, this);309 }310 reverse() {311 }312 equal(car) {313 return this.constructor == car.constructor && car.id == this.id && car.location == this.location;314 }315 clone() {316 return new Wagon(this.id, this.location);317 }318}319class Engine extends Wagon {320 constructor(location, direction) {321 super(0, location);322 this.direction = direction;323 }324 get model() {325 return TrackSwitcher.SHAPE_ENGINE;326 }327 draw(game) {328 const track = game.getTrack(this.location);329 track.drawEngine(game, this);330 }331 reverse() {332 this.direction *= -1;333 }334 equal(car) {335 return super.equal(car) && car.direction == this.direction;336 }337 clone() {338 return new Engine(this.location, this.direction);339 }340}341class Block extends Wagon {342 constructor(location) {343 super(Math.random(), location);344 }345 get model() {346 return TrackSwitcher.SHAPE_BLOCK;347 }348 get movable() {349 return false;350 }351 draw(game) {352 const track = game.getTrack(this.location);353 track.drawBlock(game);354 }355 equal(car) {356 return this.constructor == car.constructor;357 }358 clone() {359 return new Block(this.location);360 }361}362class TrackSwitcher extends CanvasGame {363 static BEST_SCORES = {all: {}};364 static OFFSET = 1;365 static SQUARE = 40;366 static SQUARE = 40;367 static MARGIN = 0;368 static STOP_RADIUS = 12;369 static STOP_WIDTH = 3;370 static STOP_COLOR = '#aaa';371 static BLOCK_COLOR = '#000';372 static BGCOLOR = '';373 static BGCOLOR_DRAGGING = '';374 static TRACK_WIDTH = 14;375 static TRACK_INNER = 6;376 static TRACK_COLOR = '#aaa';377 static TRAIN_COLOR = '#fff';378 static TRAIN_WIDTH = 44;379 static ROUTE_COLOR = '#000';380 static ROUTE_WIDTH = 4;381 static CONNECTOR_RADIUS = 8;382 static WAGON_COLOR = 'red';383 static CAR_COLORS = ['red', 'green', 'blue', 'orange'];384 static WIDTH = 16;385 static HEIGHT = 10;386 static LEVEL_LABEL = new Coords2D(6.5, 5);387 static TRACKS = [388 new Track('1-1', 0, 1, 2, 1, 0), new Track('1-2', 2, 1, 4, 1, 0), new Track('1-3', 4, 1, 6, 1, 0), new Track('1-4', 6, 1, 8, 1, 0),389 new Track('1-5', 8, 1, 10, 1, 0), new Track('1-6', 10, 1, 12, 1, 0), new Track('1-7', 12, 1, 14, 1, 0), new Track('1-8', 14, 1, 16, 1, 0),390 new Track('2', 8, 1, 6, 3, -45),391 new Track('3-1', 6, 3, 8, 3, 0), new Track('3-2', 8, 3, 10, 3, 0),392 new Track('4-1', 6, 3, 4, 5, -45), new Track('4-2', 10, 3, 12, 5, 45),393 new CircularTrack('c', 8, 3, 8, 7, 90, 8.65, 5, 5.7, 5, 3, -Math.PI * .23, Math.PI * .23),394 new Track('5-1', 0, 5, 2, 5, 0), new Track('5-2', 2, 5, 4, 5, 0), new Track('5-3', 12, 5, 14, 5, 0), new Track('5-4', 14, 5, 16, 5, 0),395 new Track('6-1', 6, 7, 4, 5, 45), new Track('6-2', 10, 7, 12, 5, -45),396 new Track('7-1', 6, 7, 8, 7, 0), new Track('7-2', 8, 7, 10, 7, 0),397 new Track('lb-1', 6, 7, 4, 8, -30), new Track('lb-2', 4, 8, 3, 10, -60),398 new Track('rb-1', 8, 7, 10, 8.5, 36), new Track('rb-2', 10, 8.5, 12, 8.5, 0), new Track('rb-3', 12, 8.5, 14, 10, 36),399 ];400 // static TRACK_CONNECTORS = [401 // new TrackConn('1-1', '1-2', 2, 0.5), new TrackConn('1-2', '1-3', 4, 0.5), new TrackConn('1-3', '1-4', 6, 0.5), new TrackConn('1-4', '1-5', 8, 0.5),402 // new TrackConn('1-5', '1-6', 10, 0.5), new TrackConn('1-6', '1-7', 12, 0.5), new TrackConn('1-7', '1-8', 14, 0.5),403 // new TrackConn('1-5', '2', 8.3, 1.5),404 // new TrackConn('2', '4-1', 5.5, 2.7), new TrackConn('3-1', '4-1', 6.3, 3.5), new TrackConn('3-1', '3-2', 8, 2.5), new TrackConn('3-2', '4-2', 10.3, 2.5),405 // new TrackConn('5-1', '5-2', 2, 4.5), new TrackConn('4-1', '5-2', 3.8, 4.4), new TrackConn('5-2', '6-1', 3.8, 5.6),406 // new TrackConn('6-1', '7-1', 6.1, 6.3), new TrackConn('cb', '7-1', 7.7, 6.4), new TrackConn('6-2', '7-2', 9.8, 6.4),407 // new TrackConn('7-1', 'lb-1', 6.2, 7.5), new TrackConn('7-1', 'rb-1', 7.8, 7.5),408 // ];409 static UNBENDABLES = ['lb-1:6-1', '6-1:4-1', '3-1:2', '1-4:2', 'rb-1:7-2', 'rb-1:c', 'c:7-2', '4-2:6-2', '3-2:c'];410 static REVERSERS = ['c:7-1'];411 static SHAPE_ENGINE = new EngineShape();412 static SHAPE_WAGON = new WagonShape();413 static SHAPE_BLOCK = new BlockShape();414 static PROBLEMS = [];415 constructor(canvas, solutionCanvas) {416 super(canvas);417 this.solutionCanvas = solutionCanvas;418 this.solutionCtx = solutionCanvas.getContext('2d');419 }420 createGame() {421 super.createGame();422 // this.paintingTiming = true;423 this.$levels = $('#levels');424 this.$levelPrev = $('#prev');425 this.$levelNext = $('#next');426 this.$showNames = $('#show-names');427 // this.$showSolution = $('#show-solution');428 this.createLevelSelect();429 this.interTracks = this.createInterTracks();430 }431 createLevelSelect() {432 const L = TrackSwitcher.PROBLEMS.length;433 const html = TrackSwitcher.PROBLEMS.map((P, n) => !P ? '' : `<option value="${n}">${this.levelLabel(n)} / ${L}</option>`).join('');434 this.$levels.setHTML(html);435 }436 createInterTracks() {437 const coords = [];438 TrackSwitcher.TRACKS.forEach(T => {439 coords.find(C => C.equal(T.to)) || coords.push(T.to);440 coords.find(C => C.equal(T.from)) || coords.push(T.from);441 });442 return coords;443 }444 reset() {445 super.reset();446 this.drawingSolution = false;447 this.level = 0;448 this.cars = [];449 this.dragging = 0;450 // this.draggingFrom = null;451 this.draggingTrain = null;452 this.draggingRoute = null;453 this.connecteds = [];454 }455 drawContent() {456 this.drawFill(this.dragging ? TrackSwitcher.BGCOLOR_DRAGGING : TrackSwitcher.BGCOLOR);457 this.drawTrainBacklight();458 this.drawStops();459 this.drawTracks();460 // this.drawConnectors();461 this.drawDragging();462 this.drawCars();463 this.drawTrainLinks();464 this.drawLevelNumber();465 if (this.$showNames && this.$showNames.checked) {466 this.drawTrackNames();467 }468 }469 drawCars() {470 this.getCars().forEach(car => {471 car.draw(this);472 });473 }474 drawTrainBacklight() {475 if (this.draggingTrain) {476 this.draggingTrain.cars.forEach(car => this.getTrack(car).drawTrainBacklight(this));477 }478 }479 drawTrainLinks() {480 if (this.draggingTrain) {481 for (let i = 1; i < this.draggingTrain.cars.length; i++) {482 const fromCar = this.draggingTrain.cars[i - 1];483 const fromTrack = this.getTrack(fromCar.location);484 const toCar = this.draggingTrain.cars[i];485 const toTrack = this.getTrack(toCar.location);486 if (fromCar && toCar) {487 this.drawTrainLink(fromTrack, fromCar, toTrack, toCar);488 }489 }490 }491 }492 drawTrainLink(fromTrack, fromCar, toTrack, toCar) {493 const inter = this.scale(this.getInter(fromTrack, toTrack));494 const ends = [...fromTrack.getEnds(this, fromCar.model), ...toTrack.getEnds(this, toCar.model)];495 ends.sort((a, b) => a.distance(inter) < b.distance(inter) ? -1 : 1);496 this.drawLine(ends[0], ends[1], {width: 4});497 }498 drawDragging() {499 if (this.draggingRoute) {500 this.draggingRoute.tracks.forEach(track => track.drawRoute(this));501 }502 }503 drawStops() {504 TrackSwitcher.TRACKS.map(T => {505 const C = T.center;506 if (this.shouldDrawStop(T)) {507 this.drawCircle(this.scale(C), TrackSwitcher.STOP_RADIUS, {508 color: TrackSwitcher.STOP_COLOR,509 width: TrackSwitcher.STOP_WIDTH,510 });511 }512 // else {513 // this.drawLine(this.scale(C).add(new Coords2D(-7, -7)), this.scale(C).add(new Coords2D(7, 7)));514 // this.drawLine(this.scale(C).add(new Coords2D(-7, 7)), this.scale(C).add(new Coords2D(7, -7)));515 // }516 });517 }518 shouldDrawStop(track) {519 const car = this.getCar(track);520 return !car || car.movable;521 }522 drawTracks() {523 this.interTracks.forEach(C => this.drawDot(this.scale(C), {524 radius: TrackSwitcher.TRACK_WIDTH/2,525 color: TrackSwitcher.TRACK_COLOR,526 }));527 TrackSwitcher.TRACKS.map(track => track.drawTrackOuter(this));528 TrackSwitcher.TRACKS.map(track => track.drawTrackInner(this));529 }530 // drawConnectors() {531 // TrackSwitcher.TRACK_CONNECTORS.forEach(inter => {532 // // if (!this.getCar(this.getTrack(inter.from)) || !this.getCar(this.getTrack(inter.to))) return;533 // const C = this.scale(inter.button);534 // const enabled = this.connecteds.includes(inter);535 // this.drawDot(C, {536 // radius: TrackSwitcher.CONNECTOR_RADIUS,537 // color: enabled ? '#0c0' : '#f00',538 // });539 // this.drawCircle(C, TrackSwitcher.CONNECTOR_RADIUS, {540 // color: '#000',541 // width: 2,542 // });543 // });544 // }545 drawTrackNames() {546 TrackSwitcher.TRACKS.map(track => this.drawTrackName(track));547 }548 drawLevelNumber() {549 this.ctx.textAlign = 'center';550 this.ctx.textBaseline = 'middle';551 this.drawText(this.scale(TrackSwitcher.LEVEL_LABEL), this.levelLabel(this.level), {552 size: 50,553 style: 'bold',554 });555 }556 drawTrackName(track) {557 this.ctx.textAlign = 'left';558 this.ctx.textBaseline = 'bottom';559 this.drawText(this.scale(track.center), track.name, {color: 'green'});560 }561 getTrack(location) {562 if (location instanceof Wagon) {563 location = location.location;564 }565 return TrackSwitcher.TRACKS.find(T => T.name == location);566 }567 getCars(solution) {568 if (this.drawingSolution /*this.$showSolution.checked*/) {569 return [570 ...TrackSwitcher.PROBLEMS[this.level].tos.filter(car => car.movable),571 ...TrackSwitcher.PROBLEMS[this.level].froms.filter(car => !car.movable),572 ];573 }574 return this.cars;575 }576 getCar(track) {577 return this.getCars().find(car => car.location === track.name);578 }579 getEngine(track) {580 const car = this.getCar(track);581 return car instanceof Engine ? car : null;582 }583 getConnInter(conn) {584 return this.getInter(this.getTrack(conn.from), this.getTrack(conn.to));585 }586 getInter(track1, track2) {587 if (track1.from.equal(track2.from)) {588 return track1.from;589 }590 if (track1.to.equal(track2.to)) {591 return track1.to;592 }593 if (track1.from.equal(track2.to)) {594 return track1.from;595 }596 if (track1.to.equal(track2.from)) {597 return track1.to;598 }599 }600 startGame(level = 0) {601 this.reset();602 this.canvas.width = this.solutionCanvas.width = TrackSwitcher.OFFSET + TrackSwitcher.WIDTH * (TrackSwitcher.SQUARE + TrackSwitcher.MARGIN) - TrackSwitcher.MARGIN + TrackSwitcher.OFFSET;603 this.canvas.height = this.solutionCanvas.height = TrackSwitcher.OFFSET + TrackSwitcher.HEIGHT * (TrackSwitcher.SQUARE + TrackSwitcher.MARGIN) - TrackSwitcher.MARGIN + TrackSwitcher.OFFSET;604 // this.$showSolution.checked = false;605 this.loadLevel(level);606 this.changed = true;607 this.drawOn(this.solutionCtx, () => {608 this.drawingSolution = true;609 this.drawStructure();610 this.drawContent();611 this.drawingSolution = false;612 });613 }614 levelLabel(n) {615 return String(n + 1);616 }617 loadLevel(n) {618 this.level = n;619 this.$levels.value = n;620 this.$levelPrev.disabled = n == 0;621 this.$levelNext.disabled = n == TrackSwitcher.PROBLEMS.length - 1;622 this.printBestScore(n + 1);623 this.cars = TrackSwitcher.PROBLEMS[this.level].froms.map(car => car.clone());624 }625 scale( source, square ) {626 if ( source instanceof Coords2D ) {627 return new Coords2D(this.scale(source.x, TrackSwitcher.SQUARE), this.scale(source.y, TrackSwitcher.SQUARE));628 }629 return TrackSwitcher.OFFSET + source * (square + TrackSwitcher.MARGIN);630 }631 // unscale( source, square ) {632 // if ( source instanceof Coords2D ) {633 // source = source.multiply(this.canvas.width / this.canvas.offsetWidth);634 // const C = new Coords2D(this.unscale(source.x, TrackSwitcher.SQUARE), this.unscale(source.y, TrackSwitcher.SQUARE));635 // return C;636 // }637 // return Math.round((source - TrackSwitcher.OFFSET - square/2) / (TrackSwitcher.MARGIN + square));638 // }639 findClosestTrack(C) {640 const dists = TrackSwitcher.TRACKS.map(T => this.scale(T.center).distance(C));641 const sorted = dists642 .map((d, i) => ([d, i]))643 .sort((a, b) => a[0] - b[0])644 .filter(([d, i]) => {645 return d < 20;646 });647 return sorted.length ? TrackSwitcher.TRACKS[sorted[0][1]] : null;648 }649 canBendTo(a, b) {650 return !TrackSwitcher.UNBENDABLES.includes(`${a.name}:${b.name}`) && !TrackSwitcher.UNBENDABLES.includes(`${b.name}:${a.name}`);651 }652 // disableConnections(conns) {653 // this.connecteds = this.connecteds.filter(conn => !conns.includes(conn));654 // }655 // enableConnection(conn) {656 // this.connecteds.push(conn);657 // const inter = this.getConnInter(conn);658 // const others = TrackSwitcher.TRACK_CONNECTORS.filter(conn2 => {659 // const inter2 = this.getConnInter(conn2);660 // return conn2 != conn && inter2.equal(inter);661 // });662 // if (others.length) {663 // this.disableConnections(others);664 // }665 // }666 haveWon() {667 const filter = car => car.movable;668 const sort = (a, b) => {669 var cmp = a.id - b.id;670 if (cmp != 0) return cmp;671 cmp = a.location < b.location ? -1 : 1;672 return cmp;673 };674 const goal = TrackSwitcher.PROBLEMS[this.level].tos.filter(filter).sort(sort);675 const real = this.cars.filter(filter).sort(sort);676 if (goal.length == real.length) {677 return real.every((car, i) => {678 return car.equal(goal[i]);679 });680 }681 }682 getScore() {683 const lvl = this.level + 1;684 const best = this.getBestScore(lvl);685 if (this.m_iMoves && (!best || this.m_iMoves < best)) {686 TrackSwitcher.BEST_SCORES.all[lvl] = this.m_iMoves;687 this.printBestScore(lvl);688 }689 return {690 ...super.getScore(),691 level: lvl,692 };693 }694 getBestScore(lvl) {695 return TrackSwitcher.BEST_SCORES.all[lvl] || 0;696 }697 printBestScore(lvl) {698 $('#best-moves').setText(this.getBestScore(lvl) || '?');699 }700 getObjectAt(C) {701 return this.findClosestTrack(C);702 }703 handleClick(C) {704 if (this.m_bGameOver) return;705 const track = this.findClosestTrack(C);706 if (track) return;707 if (this.draggingTrain) {708 this.draggingTrain = null;709 }710 this.changed = true;711 // const R = TrackSwitcher.CONNECTOR_RADIUS * 1.5;712 // const conn = TrackSwitcher.TRACK_CONNECTORS.find(conn => this.scale(conn.button).distance(C) < R);713 // if (conn) {714 // if (this.connecteds.includes(conn)) {715 // this.disableConnections([conn]);716 // }717 // else {718 // this.enableConnection(conn);719 // }720 // this.changed = true;721 // }722 }723 handleDragStartObject(track) {724 if (this.m_bGameOver) return;725 clearTimeout(this.checker);726 this.startTime();727 const car = this.getCar(track);728 if (!car || !car.movable) return;729 if (!this.draggingTrain) {730 this.draggingTrain = new Train(new Route(this, track), car);731 }732 else {733 const route = this.draggingTrain.route;734 if (track == route.first) {735 this.draggingRoute = route.reverse();736 }737 else if (track == route.last) {738 this.draggingRoute = route.clone();739 }740 else {741 return;742 }743 }744 this.changed = true;745 return true;746 }747 handleDragMoveObject(track) {748 if (this.m_bGameOver) return;749 const car = this.getCar(track);750 if (!this.draggingRoute) {751 if (!car && this.draggingTrain.length == 1 && this.draggingTrain.canMove()) {752 this.draggingRoute = this.draggingTrain.route;753 this.moveTrain(track, car);754 return;755 }756 if (car && car.movable) {757 this.extendTrain(track, car);758 }759 return;760 }761 if (this.draggingRoute.beforeLast === track) {762 this.reverseTrain(track, car);763 return;764 }765 this.moveTrain(track, car);766 }767 extendTrain(track, car) {768 if (this.draggingTrain.connectsTo(track)) {769 if (this.canBendTo(this.draggingTrain.route.last, track)) {770 if (this.draggingTrain.add(car, track)) {771 this.changed = true;772 }773 }774 }775 }776 moveTrain(track, car) {777 if (this.draggingRoute.last != track) {778 if (this.draggingRoute.connectsTo(track) && !this.getCar(track)) {779 if (this.canBendTo(this.draggingRoute.last, track)) {780 this.draggingRoute.forward(track, this.draggingTrain);781 this.changed = true;782 return;783 }784 }785 }786 }787 reverseTrain(track, car) {788 if (this.draggingRoute.length > this.draggingTrain.length) {789 this.draggingRoute.backward(this.draggingTrain);790 this.changed = true;791 }792 }793 handleDragEnd() {794 if (this.m_bGameOver) return;795 if (!this.draggingTrain && !this.draggingRoute) return;796 if (!this.draggingRoute) {797 if (!this.draggingTrain.canMove()) {798 this.draggingTrain = null;799 }800 this.changed = true;801 return;802 }803 if (this.draggingRoute.length > this.draggingTrain.length) {804 this.setMoves(this.m_iMoves + 1);805 }806 if (this.draggingRoute) {807 this.draggingTrain = null;808 }809 this.draggingRoute = null;810 this.changed = true;811 this.startWinCheck();812 }813 listenControls() {814 this.listenDragAndClick();815 this.$levels.on('change', e => {816 this.startGame(parseInt(e.target.value));817 });818 this.$levelPrev.on('click', e => {819 this.startGame(parseInt(this.$levels.selectedOptions[0].previousElementSibling.value));820 });821 this.$levelNext.on('click', e => {822 this.startGame(parseInt(this.$levels.selectedOptions[0].nextElementSibling.value));823 });824 $('#restart').on('click', e => {825 this.startGame(this.level);826 });827 this.$showNames && this.$showNames.on('change', e => {828 this.changed = true;829 });830 // this.$showSolution.on('change', e => {831 // this.changed = true;832 // });833 }...
listener.js
Source:listener.js
...45 log.error('inbound connection failed', err)46 return attemptClose(maConn)47 }48 log('inbound connection %s upgraded', maConn.remoteAddr)49 trackConn(server, maConn)50 if(handler) handler(conn)51 listener.emit('connection', conn)52 })53 server54 .on('listening', () => listener.emit('listening'))55 .on('error', err => listener.emit('error', err))56 .on('close', () => listener.emit('close'))57 // Keep track of open connections to destroy in case of timeout58 server.__connections = []59 listener.close = () => {60 if(!server.listening) return61 return new Promise((resolve, reject) => {62 server.__connections.forEach(maConn => attemptClose(maConn))63 server.close(err => err ? reject(err) : resolve())64 })65 }66 let peerId, listeningAddr67 listener.listen = ma => {68 listeningAddr = ma69 peerId = ma.getPeerId()70 if(peerId) {71 listeningAddr = ma.decapsulateCode(CODE_P2P)72 }73 return new Promise((resolve, reject) => {74 const options = multiaddrToNetConfig(listeningAddr)75 server.listen(options, err => {76 if(err) return reject(err)77 log('Listening on %s', server.address())78 resolve()79 })80 })81 }82 listener.getAddrs = () => {83 const multiaddrs = []84 const address = server.address()85 if(!address) {86 throw new Error('Listener is not ready yet')87 }88 const ipfsId = listeningAddr.getPeerId()89 // Because TCP will only return the IPv6 version90 // we need to capture from the passed multiaddr91 if(listeningAddr.toString().indexOf('ip4') !== -1) {92 let m = listeningAddr.decapsulate('tcp')93 m = m.encapsulate('/tcp/' + address.port + '/tls')94 if(listeningAddr.getPeerId()) {95 m = m.encapsulate('/p2p/' + ipfsId)96 }97 if(m.toString().indexOf('0.0.0.0') !== -1) {98 const netInterfaces = os.networkInterfaces()99 Object.keys(netInterfaces).forEach((niKey) => {100 netInterfaces[niKey].forEach((ni) => {101 if(ni.family === 'IPv4') {102 multiaddrs.push(multiaddr(m.toString().replace('0.0.0.0', ni.address)))103 }104 })105 })106 } else {107 multiaddrs.push(m)108 }109 }110 return multiaddrs111 }112 return listener113}114function trackConn(server, maConn) {115 server.__connections.push(maConn)116 const untrackConn = () => {117 server.__connections = server.__connections.filter(c => c !== maConn)118 }119 maConn.conn.once('close', untrackConn)...
allow-destroy.js
Source:allow-destroy.js
...8 * `secureConnection` events.9 */10function allowDestroy(server) {11 var connections = [];12 function trackConn(conn) {13 connections.push(conn);14 conn.on('close', function () {15 connections = connections.filter(function (connection) { return connection !== conn; });16 });17 }18 server.on('connection', trackConn);19 server.on('secureConnection', trackConn);20 // @ts-ignore Property 'destroy' does not exist on type 'Server'.21 server.destroy = function (cb) {22 server.close(cb);23 connections.map(function (connection) { return connection.destroy(); });24 };25 return server;26}...
Using AI Code Generation
1Cypress.on('uncaught:exception', (err, runnable) => {2})3Cypress.on('uncaught:exception', (err, runnable) => {4})5Cypress.on('uncaught:exception', (err, runnable) => {6})7Cypress.on('uncaught:exception', (err, runnable) => {8})9Cypress.on('uncaught:exception', (err, runnable) => {10})11Cypress.on('uncaught:exception', (err, runnable) => {12})13Cypress.on('uncaught:exception', (err, runnable) => {14})15Cypress.on('uncaught:exception', (err, runnable) => {16})17Cypress.on('uncaught:exception', (err, runnable) => {18})19Cypress.on('uncaught:exception', (err, runnable) => {20})21Cypress.on('uncaught:exception', (err, runnable) => {22})
Using AI Code Generation
1describe('test', () => {2 it('test', () => {3 cy.get('button').click();4 cy.wait('@get');5 });6});7Cypress.Commands.add('trackConn', url => {8 cy.server();9 cy.route('GET', url).as('get');10});11module.exports = (on, config) => {12 on('task', {13 log(message) {14 console.log(message);15 return null;16 },17 });18};19Cypress.Commands.add('log', message => {20 cy.task('log', message);21});22Cypress.Commands.add('log', message => {23 cy.task('log', message);24});25module.exports = (on, config) => {26 on('task', {27 log(message) {28 console.log(message);29 return null;30 },31 });32};33Cypress.Commands.add('log', message => {34 cy.task('log', message);35});36Cypress.Commands.add('log', message => {37 cy.task('log', message);38});39module.exports = (on, config) => {40 on('task', {41 log(message) {42 console.log(message);43 return null;44 },45 });46};47Cypress.Commands.add('log', message => {48 cy.task('log', message);49});50Cypress.Commands.add('log', message => {51 cy.task('log', message);52});
Using AI Code Generation
1require('cypress-xpath')2require('cypress-plugin-retries')3require('cypress-plugin-tab')4describe('Test case for login', function () {5 it('Login to the application', function () {6 cy.get('input[title="Search"]').type('Cypress')7 })8})
Using AI Code Generation
1describe('Cypress test', function() {2 it('should connect to the server', function() {3 onConnect: () => {4 },5 onDisconnect: () => {6 },7 });8 });9});
Using AI Code Generation
1cy.trackConn('test').then(() => {2 cy.wait(1000);3 cy.wait(1000);4});5cy.trackConn('test').then(() => {6 cy.wait(1000);7 cy.wait(1000);8});9cy.trackConn('test').then(() => {10 cy.wait(1000);11 cy.wait(1000);12});13cy.trackConn('test').then(() => {14 cy.wait(1000);15 cy.wait(1000);16});17cy.trackConn('test').then(() => {18 cy.wait(1000);19 cy.wait(1000);20});21cy.trackConn('test').then(() => {22 cy.wait(1000);23 cy.wait(1000);24});25cy.trackConn('test').then(() => {26 cy.wait(1000);27 cy.wait(1000);28});29cy.trackConn('test').then(() => {30 cy.wait(1000);31 cy.wait(1000);32});33cy.trackConn('test').then(() => {34 cy.wait(1000);35 cy.wait(1000);36});37cy.trackConn('test').then(() => {38 cy.wait(1000
Using AI Code Generation
1describe('Test', () => {2 it('test', () => {3 cy.trackConn()4 cy.get('input').type('cypress{enter}')5 cy.wait(2000)6 cy.getConn().then((connections) => {7 cy.log(connections)8 })9 })10})11Cypress.Commands.add('trackConn', () => {12 cy.window().then((win) => {13 win.XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {14 this.addEventListener('load', function () {15 if (this._url !== undefined) {16 cy.task('addConn', this._url)17 }18 })19 this._open(method, url, async, user, pass)20 }21 })22})23Cypress.Commands.add('getConn', () => {24 return cy.task('getConn')25})26module.exports = (on, config) => {27 on('task', {28 addConn(url) {29 connections.push(url)30 },31 getConn() {32 },33 })34}35{36}37"dependencies": {38}39import './commands'40module.exports = (on, config) => {41 on('task', {42 addConn(url) {43 connections.push(url)44 },45 getConn() {46 },47 })48}
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.
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.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!