How to use viewport method in Puppeteer

Best JavaScript code snippet using puppeteer

viewports.js

Source:viewports.js Github

copy

Full Screen

1/**2 * # viewports.js3 * ### By [Diego Enrique Marquez](http://www.treintipollo.com)4 * ### [Find me on Github](https://github.com/diegomarquez)5 *6 * Inherits from:7 * [delegate](@@delegate@@)8 *9 * Depends of:10 * [viewport](@@viewport@@)11 * [error-printer](@@error-printer@@)12 * [util](@@util@@)13 *14 * A [requireJS](http://requirejs.org/) module. For use with [Game-Builder](http://diegomarquez.github.io/game-builder)15 *16 * This module serves as a container for all the [viewport](@@viewport@@) objects created.17 *18 * This module extends [delegate](@@delegate@@) so it provides a few events to hook into:19 *20 * ### **ADD**21 * When a [viewport](@@viewport@@) is added22 *23 * Registered callbacks get the [viewports](@@viewports@@) as argument24 * ``` javascript25 * gb.viewports.on(gb.viewports.ADD, function(viewports) {});26 * ```27 *28 * </br>29 *30 * ### **REMOVE**31 * When a [viewport](@@viewport@@) is removed32 *33 * Registered callbacks get the [viewport](@@viewport@@) as argument34 * ``` javascript35 * gb.viewports.on(gb.viewports.REMOVE, function(viewport) {});36 * ```37 *38 * </br>39 *40 * ### **CHANGE**41 * When a [viewport](@@viewport@@) changes position42 *43 * Registered callbacks get the [viewport](@@viewport@@) as argument44 * ``` javascript45 * gb.viewports.on(gb.viewports.CHANGE, function(viewport) {});46 * ```47 *48 * </br>49 *50 * ### **MOVE**51 * When all the [viewport](@@viewport@@) is moved52 *53 * ``` javascript54 * gb.viewports.on(gb.viewports.MOVE, function() {});55 * ```56 *57 * </br>58 *59 * <strong>Note: The snippet uses the reference to <a href=@@viewports@@>viewports</a>60 * found in the <a href=@@gb@@>gb</a> module.61 * The way you get a hold to a reference to <a href=@@viewports@@>viewports</a>62 * may vary.</strong>63 */64/**65 * Viewport management66 * --------------------------------67 */68/**69 * --------------------------------70 */71define(["delegate", "viewport", "error-printer", "util"], function(Delegate, Viewport, ErrorPrinter, Util) {72 var viewports = {};73 var viewportsArray = [];74 var ViewportContainer = Delegate.extend({75 init: function() {76 this._super();77 },78 /**79 * <p style='color:#AD071D'><strong>addViewport</strong></p>80 *81 * Creates a new [viewport](@@viewport@@) and adds it to the container.82 *83 * @param {String} name Id of the new [viewport](@@viewport@@)84 * @param {Number} width Width of the new [viewport](@@viewport@@)85 * @param {Number} height Height of the new [viewport](@@viewport@@)86 * @param {Number} [offsetX=0] X offset relative to the top corner of the screen87 * @param {Number} [offsetY=0] Y offset relative to the top corner of the screen88 * @param {Number} [scaleX=1] X scale of the [viewport](@@viewport@@)89 * @param {Number} [scaleY=1] Y scale of the [viewport](@@viewport@@)90 * @param {Array} [layers=null] Y An array of strings with the names of [layer](@@layer@@) objects to add on the created [viewport](@@viewport@@)91 * @param {Number} [strokeColor=null] Color of the stroke around the [viewports](@@viewports@@)92 * @param {Number} [strokeWidth=null] Width of the stroke around the [viewport](@@viewport@@)93 * @param {Boolean} [worldfit=false] Whether [viewport](@@viewport@@) should scale to fit the [world](@@world@@) size94 * @param {Boolean} [culling=true] Whether the viewport should perform culling when [game-objects](@@game-object@@) are drawn to it95 * @param {Boolean} [clipping=true] Whether the viewport should clip drawings that fall outside of it's viewing area96 *97 * @return {Object} The newly created [viewport](@@viewport@@). If it already exists, the existing one is returned98 */99 addViewport: function(name, width, height, offsetX, offsetY, scaleX, scaleY, layers, strokeColor, strokeWidth, worldFit, culling, clipping) {100 if (!viewports[name]) {101 var v = create.apply(this, arguments);102 viewports[name] = v;103 viewportsArray.push(v);104 this.execute(this.ADD, v);105 return v;106 }107 return viewports[name];108 },109 /**110 * --------------------------------111 */112 /**113 * <p style='color:#AD071D'><strong>addFromObject</strong></p>114 *115 * Creates a new [viewport](@@viewport@@) and adds it to the container.116 *117 * @param {Object} viewport An object with all the properties needed to create a [viewport](@@viewport@@)118 *119 * @return {Object} The newly created [viewport](@@viewport@@). If it already exists, the existing one is returned120 */121 addFromObject: function(viewport) {122 var name = viewport.name;123 if (!viewports[name]) {124 var v = create(125 name,126 viewport.width,127 viewport.height,128 viewport.offsetX,129 viewport.offsetY,130 viewport.scaleX,131 viewport.scaleY,132 viewport.layers,133 viewport.stroke.color,134 viewport.stroke.width,135 viewport.worldFit,136 viewport.culling,137 viewport.clipping138 );139 viewports[name] = v;140 viewportsArray.push(v);141 this.execute(this.ADD, v);142 return v;143 }144 return viewports[name];145 },146 /**147 * --------------------------------148 */149 /**150 * <p style='color:#AD071D'><strong>removeViewport</strong></p>151 *152 * Removes the specified [viewport](@@viewport@@)153 *154 * @param {String} name Id of the [viewport](@@viewport@@) to remove155 */156 removeViewport: function(name) {157 if (!viewports[name]) {158 ErrorPrinter.printError('Viewports', 'Viewport with id:' + name + ' does not exist.');159 }160 var v = viewports[name];161 viewportsArray.splice(viewportsArray.indexOf(v), 1);162 viewports[name] = null;163 delete viewports[name];164 this.execute(this.REMOVE, v);165 v.destroy();166 },167 /**168 * --------------------------------169 */170 /**171 * <p style='color:#AD071D'><strong>change</strong></p>172 *173 * Change the position of the specified viewport174 *175 * @param {String} [name] Name [viewport](@@viewport@@) to change176 * @param {Number} [index] New index177 */178 change: function(name, index) {179 var viewport = viewports[name];180 var viewportIndex = viewportsArray.indexOf(viewport);181 viewportsArray.splice(viewportIndex, 1);182 viewportsArray.splice(index, 0, viewport);183 this.execute(this.CHANGE, viewport);184 },185 /**186 * --------------------------------187 */188 /**189 * <p style='color:#AD071D'><strong>after</strong></p>190 *191 * Place the [viewport](@@viewport@@) specified by the first argument after192 * the one specified by the second argument.193 *194 * @param {String} [name] Name [viewport](@@viewport@@) to change195 * @param {String} [other] Name [viewport](@@viewport@@) which should come before to the one in the first argument196 */197 after: function(name, other) {198 move.call(this, 'after', name, other);199 },200 /**201 * --------------------------------202 */203 /**204 * <p style='color:#AD071D'><strong>before</strong></p>205 *206 * Place the [viewport](@@viewport@@) specified by the first argument before207 * the one specified by the second argument.208 *209 * @param {String} [name] Name [viewport](@@viewport@@) to change210 * @param {String} [other] Name [viewport](@@viewport@@) which should come after to the one in the first argument211 */212 before: function(name, other) {213 move.call(this, 'before', name, other);214 },215 /**216 * --------------------------------217 */218 /**219 * <p style='color:#AD071D'><strong>removeAll</strong></p>220 *221 * Destroys all the [viewports](@@viewport@@)222 */223 removeAll: function() {224 for (var i = viewportsArray.length - 1; i >= 0; i--) {225 this.removeViewport(viewportsArray[i].name);226 }227 },228 /**229 * --------------------------------230 */231 /**232 * <p style='color:#AD071D'><strong>show</strong></p>233 *234 * Makes the specified [viewport](@@viewport@@) visible235 *236 * @param {String} name Id of the [viewport](@@viewport@@) to make visible237 *238 * @throws {Error} If the id specified does not exist239 */240 show: function(name) {241 if (!viewports[name]) {242 ErrorPrinter.printError('Viewports', 'Viewport with id:' + name + ' does not exist.');243 }244 viewports[name].show();245 },246 /**247 * --------------------------------248 */249 /**250 * <p style='color:#AD071D'><strong>hide</strong></p>251 *252 * Makes the specified [viewport](@@viewport@@) invisible253 *254 * @param {String} name Id of the [viewport](@@viewport@@) to make invisible255 *256 * @throws {Error} If the id specified does not exist257 */258 hide: function(name) {259 if (!viewports[name]) {260 ErrorPrinter.printError('Viewports', 'Viewport with id:' + name + ' does not exist.');261 }262 viewports[name].hide();263 },264 /**265 * --------------------------------266 */267 /**268 * <p style='color:#AD071D'><strong>get</strong></p>269 *270 * Get a reference to the specified [viewport](@@viewport@@)271 *272 * @param {String} name Id of the [viewport](@@viewport@@) to get273 *274 * @throws {Error} If the id specified does not exist275 */276 get: function(name) {277 if (!viewports[name]) {278 ErrorPrinter.printError('Viewports', 'Viewport with id:' + name + ' does not exist.');279 }280 return viewports[name];281 },282 /**283 * --------------------------------284 */285 /**286 * <p style='color:#AD071D'><strong>exists</strong></p>287 *288 * @param {String} name Id of the [viewport](@@viewport@@) to check289 *290 * @throws {Boolean} Whether the [viewport](@@viewport@@) exists or not291 */292 exists: function(name) {293 return viewports[name];294 },295 /**296 * --------------------------------297 */298 /**299 * <p style='color:#AD071D'><strong>iterate</strong></p>300 *301 * Iterate through all the viewports executing the callback function with each [viewport](@@viewport@@) as argument302 *303 * @param {Function} method The method to execute for each [viewport](@@viewport@@)304 */305 iterate: function(scope, method) {306 for (var i = 0; i < viewportsArray.length; i++) {307 method.call(scope, viewportsArray[i]);308 }309 },310 /**311 * --------------------------------312 */313 /**314 * <p style='color:#AD071D'><strong>all</strong></p>315 *316 * Get a reference to an object containing all the created [viewports](@@viewport@@)317 *318 * @return {Object} An object with all the [viewport](@@viewport@@) objects319 */320 all: function() {321 return viewports;322 },323 /**324 * --------------------------------325 */326 /**327 * <p style='color:#AD071D'><strong>allAsArray</strong></p>328 *329 * A reference to an array containing all the created [viewports](@@viewport@@)330 *331 * @return {Array} An array with all the [viewport](@@viewport@@) objects332 */333 allAsArray: function() {334 return viewportsArray;335 }336 /**337 * --------------------------------338 */339 });340 var create = function(name, width, height, offsetX, offsetY, scaleX, scaleY, layers, strokeColor, strokeWidth, worldFit, culling, clipping) {341 var v = new Viewport(name, width, height, offsetX, offsetY, scaleX, scaleY);342 v.setStroke(strokeWidth, strokeColor);343 if (Util.isBoolean(worldFit)) {344 v.WorldFit = worldFit;345 }346 if (Util.isBoolean(culling)) {347 v.Culling = culling;348 }349 if (Util.isBoolean(clipping)) {350 v.Clipping = clipping;351 }352 if (layers) {353 for (var i = 0; i < layers.length; i++) {354 v.addLayer(layers[i]);355 }356 }357 return v;358 }359 var move = function(type, current, pivot) {360 if (!viewports[current]) {361 ErrorPrinter.printError('Viewports', 'Viewport with id:' + current + ' does not exist.');362 }363 if (!viewports[pivot]) {364 ErrorPrinter.printError('Viewports', 'Viewport with id:' + pivot + ' does not exist.');365 }366 var current = viewports[current];367 var pivot = viewports[pivot];368 var currentIndex = viewportsArray.indexOf(current);369 var pivotIndex;370 if (type == 'before') {371 pivotIndex = viewportsArray.indexOf(pivot);372 }373 if (type == 'after') {374 pivotIndex = viewportsArray.indexOf(pivot) + 1;375 }376 viewportsArray.splice(pivotIndex, 0, viewportsArray.splice(currentIndex, 1)[0]);377 this.execute(this.MOVE, current);378 }379 Object.defineProperty(ViewportContainer.prototype, "ADD", {380 get: function() {381 return 'add';382 }383 });384 Object.defineProperty(ViewportContainer.prototype, "REMOVE", {385 get: function() {386 return 'remove';387 }388 });389 Object.defineProperty(ViewportContainer.prototype, "CHANGE", {390 get: function() {391 return 'change';392 }393 });394 Object.defineProperty(ViewportContainer.prototype, "MOVE", {395 get: function() {396 return 'move';397 }398 });399 return new ViewportContainer();...

Full Screen

Full Screen

Panel.test.js

Source:Panel.test.js Github

copy

Full Screen

1import React from 'react';2import { shallow } from 'enzyme';3import { document } from 'global';4import { Panel } from '../Panel';5import { resetViewport, viewportsTransformer } from '../viewportInfo';6import * as styles from '../styles';7import { DEFAULT_VIEWPORT, INITIAL_VIEWPORTS } from '../../../shared';8const initialViewportAt = index => Object.keys(INITIAL_VIEWPORTS)[index];9const transformedInitialViewports = viewportsTransformer(INITIAL_VIEWPORTS);10jest.mock('lodash.debounce', () => jest.fn(fn => fn));11describe('Viewport/Panel', () => {12 const props = {13 channel: {14 on: jest.fn(),15 emit: jest.fn(),16 removeListener: jest.fn(),17 },18 api: {19 onStory: jest.fn(),20 },21 };22 let subject;23 beforeEach(() => {24 subject = shallow(<Panel {...props} />);25 });26 describe('construct', () => {27 it('creates the initial state', () => {28 expect(subject.instance().state).toEqual({29 viewport: DEFAULT_VIEWPORT,30 defaultViewport: DEFAULT_VIEWPORT,31 viewports: transformedInitialViewports,32 isLandscape: false,33 });34 });35 });36 describe('componentDidMount', () => {37 let previousGet;38 beforeEach(() => {39 subject.instance().iframe = undefined;40 previousGet = document.getElementById;41 document.getElementById = jest.fn(() => 'iframe');42 subject.instance().componentDidMount();43 });44 afterEach(() => {45 document.getElementById = previousGet;46 });47 it('gets the iframe', () => {48 expect(subject.instance().iframe).toEqual('iframe');49 });50 it('listens on `configure` channel', () => {51 expect(props.channel.on).toHaveBeenCalledWith(52 'addon:viewport:configure',53 subject.instance().configure54 );55 });56 it('listens on `update` channel', () => {57 expect(props.channel.on).toHaveBeenCalledWith(58 'addon:viewport:update',59 subject.instance().changeViewport60 );61 });62 it('listens on `setStoryDefaultViewport` channel', () => {63 expect(props.channel.on).toHaveBeenCalledWith(64 'addon:viewport:setStoryDefaultViewport',65 subject.instance().setStoryDefaultViewport66 );67 });68 });69 describe('componentWillUnmount', () => {70 beforeEach(() => {71 subject.instance().componentWillUnmount();72 });73 it('removes `update` channel listener', () => {74 expect(props.channel.removeListener).toHaveBeenCalledWith(75 'addon:viewport:update',76 subject.instance().changeViewport77 );78 });79 it('removes `configure` channel listener', () => {80 expect(props.channel.removeListener).toHaveBeenCalledWith(81 'addon:viewport:configure',82 subject.instance().configure83 );84 });85 it('removes `setStoryDefaultViewport` channel listener', () => {86 expect(props.channel.removeListener).toHaveBeenCalledWith(87 'addon:viewport:setStoryDefaultViewport',88 subject.instance().setStoryDefaultViewport89 );90 });91 });92 describe('configure', () => {93 const initialConfigs = {94 defaultViewport: 'bar',95 viewports: {96 foo: {97 styles: {98 width: '0',99 },100 },101 bar: {102 styles: {103 width: '0',104 },105 },106 },107 };108 beforeEach(() => {109 subject.instance().setState = jest.fn();110 subject.instance().updateIframe = jest.fn();111 subject.instance().configure(initialConfigs);112 });113 it('sets the state with the new information', () => {114 expect(subject.instance().setState).toHaveBeenCalledWith(115 {116 ...initialConfigs,117 viewport: 'bar',118 viewports: viewportsTransformer(initialConfigs.viewports),119 },120 subject.instance().updateIframe121 );122 });123 it('makes first viewport default if default does not exist', () => {124 subject.instance().configure({125 ...initialConfigs,126 defaultViewport: 'iphone6',127 });128 expect(subject.instance().setState).toHaveBeenCalledWith(129 {130 defaultViewport: 'foo',131 viewport: 'foo',132 viewports: viewportsTransformer(initialConfigs.viewports),133 },134 subject.instance().updateIframe135 );136 });137 it('sets viewports to INITIAL_VIEWPORTS if viewports is empty', () => {138 subject.instance().configure({139 viewports: {},140 });141 expect(subject.instance().setState).toHaveBeenCalledWith(142 {143 defaultViewport: DEFAULT_VIEWPORT,144 viewport: DEFAULT_VIEWPORT,145 viewports: transformedInitialViewports,146 },147 subject.instance().updateIframe148 );149 });150 });151 describe('changeViewport', () => {152 beforeEach(() => {153 subject.instance().setState = jest.fn();154 subject.instance().updateIframe = jest.fn();155 });156 describe('new viewport', () => {157 beforeEach(() => {158 subject.instance().changeViewport(initialViewportAt(1));159 });160 it('sets the state with the new information', () => {161 expect(subject.instance().setState.mock.calls[0][0]).toEqual({162 viewport: initialViewportAt(1),163 isLandscape: false,164 });165 });166 });167 describe('same as previous viewport', () => {168 beforeEach(() => {169 subject.instance().changeViewport(DEFAULT_VIEWPORT);170 });171 it('doesnt update the state', () => {172 expect(subject.instance().setState).not.toHaveBeenCalled();173 });174 });175 });176 describe('setStoryDefaultViewport', () => {177 beforeEach(() => {178 subject.instance().setState = jest.fn();179 subject.instance().updateIframe = jest.fn();180 subject.instance().emitViewportChanged = jest.fn();181 subject.instance().setStoryDefaultViewport(initialViewportAt(1));182 });183 it('sets the state with the new information', () => {184 expect(subject.instance().setState.mock.calls).toHaveLength(2);185 expect(subject.instance().setState.mock.calls[0][0]).toEqual({186 storyDefaultViewport: 'iphone5',187 });188 expect(subject.instance().setState.mock.calls[1][0]).toEqual({189 viewport: initialViewportAt(1),190 isLandscape: false,191 });192 expect(typeof subject.instance().setState.mock.calls[1][1]).toEqual('function');193 const updaterFunction = subject.instance().setState.mock.calls[1][1];194 updaterFunction();195 expect(subject.instance().updateIframe).toHaveBeenCalled();196 expect(subject.instance().emitViewportChanged).toHaveBeenCalled();197 });198 });199 describe('emitViewportChanged', () => {200 beforeEach(() => {201 subject.instance().setState = jest.fn();202 subject.instance().updateIframe = jest.fn();203 });204 describe('new viewport', () => {205 beforeEach(() => {206 subject.instance().state = {207 ...subject.instance().state,208 viewport: initialViewportAt(1),209 };210 subject.instance().emitViewportChanged();211 });212 it('emits viewport changed event', () => {213 const viewport = transformedInitialViewports[initialViewportAt(1)];214 expect(props.channel.emit).toHaveBeenCalledWith('addon:viewport:viewportChanged', {215 viewport,216 });217 });218 });219 describe('same as previous viewport', () => {220 beforeEach(() => {221 subject.instance().emitViewportChanged();222 });223 it('does not emit viewport changed event', () => {224 expect(props.channel.emit).not.toHaveBeenCalled();225 });226 });227 });228 describe('toggleLandscape', () => {229 beforeEach(() => {230 subject.setState({ isLandscape: false });231 subject.instance().setState = jest.fn();232 subject.instance().toggleLandscape();233 });234 it('updates the landscape to be the opposite', () => {235 expect(subject.instance().setState).toHaveBeenCalledWith(236 { isLandscape: true },237 subject.instance().updateIframe238 );239 });240 });241 describe('updateIframe', () => {242 let iframe;243 describe('no iframe found', () => {244 beforeEach(() => {245 subject.instance().iframe = null;246 });247 it('throws a TypeError', () => {248 expect(() => {249 subject.instance().updateIframe();250 }).toThrow('Cannot find Storybook iframe');251 });252 });253 describe('iframe found', () => {254 beforeEach(() => {255 iframe = { style: {} };256 subject.instance().iframe = iframe;257 });258 it('sets the viewport information on the iframe', () => {259 subject.instance().updateIframe();260 expect(subject.instance().iframe.style).toEqual(resetViewport.styles);261 });262 it('swaps the height/width when in landscape', () => {263 subject.instance().state.isLandscape = true;264 subject.instance().updateIframe();265 expect(subject.instance().iframe.style).toEqual(266 expect.objectContaining({267 height: resetViewport.styles.width,268 width: resetViewport.styles.height,269 })270 );271 });272 });273 });274 describe('render', () => {275 describe('reset button', () => {276 let resetBtn;277 beforeEach(() => {278 subject.instance().changeViewport = jest.fn();279 resetBtn = subject.find('button');280 });281 it('styles the reset button as disabled if viewport is default', () => {282 expect(resetBtn.props().style).toEqual(expect.objectContaining(styles.disabled));283 });284 it('enabels the reset button if not default', () => {285 subject.setState({ viewport: 'iphone6' });286 // Find updated button287 resetBtn = subject.find('button');288 expect(resetBtn.props().style).toEqual({289 ...styles.button,290 marginTop: 30,291 padding: 20,292 });293 });294 it('toggles the landscape on click', () => {295 resetBtn.simulate('click');296 expect(subject.instance().changeViewport).toHaveBeenCalledWith(DEFAULT_VIEWPORT);297 });298 });299 describe('SelectViewport', () => {300 let select;301 beforeEach(() => {302 select = subject.find('SelectViewport');303 subject.instance().changeViewport = jest.fn();304 });305 it('passes the activeViewport', () => {306 expect(select.props()).toEqual(307 expect.objectContaining({308 activeViewport: DEFAULT_VIEWPORT,309 })310 );311 });312 it('passes the defaultViewport', () => {313 expect(select.props()).toEqual(314 expect.objectContaining({315 defaultViewport: DEFAULT_VIEWPORT,316 })317 );318 });319 it('passes the INITIAL_VIEWPORTS', () => {320 expect(select.props()).toEqual(321 expect.objectContaining({322 viewports: transformedInitialViewports,323 })324 );325 });326 it('onChange it updates the viewport', () => {327 const e = { target: { value: 'iphone6' } };328 select.simulate('change', e);329 expect(subject.instance().changeViewport).toHaveBeenCalledWith(e.target.value);330 });331 });332 describe('RotateView', () => {333 let toggle;334 beforeEach(() => {335 toggle = subject.find('RotateViewport');336 jest.spyOn(subject.instance(), 'toggleLandscape');337 subject.instance().forceUpdate();338 });339 it('passes the active prop based on the state of the panel', () => {340 expect(toggle.props().active).toEqual(subject.state('isLandscape'));341 });342 describe('is on the default viewport', () => {343 beforeEach(() => {344 subject.setState({ viewport: DEFAULT_VIEWPORT });345 });346 it('sets the disabled property', () => {347 expect(toggle.props().disabled).toEqual(true);348 });349 });350 describe('is on a non-default viewport', () => {351 beforeEach(() => {352 subject.setState({ viewport: 'iphone6' });353 toggle = subject.find('RotateViewport');354 });355 it('the disabled property is false', () => {356 expect(toggle.props().disabled).toEqual(false);357 });358 });359 });360 });...

Full Screen

Full Screen

camera.js

Source:camera.js Github

copy

Full Screen

1/** A module for dealing with perspective and rendering */2export const Camera = {3 /**4 * setCanvasResolution.5 * receives a canvas and the resolution to set it to,6 * then sets the width and height of that canvas.7 *8 * @param {Canvas} canvas9 * @param {number} canvasWidth10 * @param {number} canvasHeight11 * @returns {undefined}12 */13 setCanvasResolution(canvas, canvasWidth, canvasHeight) {14 /* eslint-disable no-param-reassign */15 // Set the new rounded size16 canvas.style.width = canvasWidth;17 canvas.style.height = canvasHeight;18 // Set the resolution19 canvas.width = canvasWidth;20 canvas.height = canvasHeight;21 /* eslint-enable no-param-reassign */22 },23 /**24 * getCanvasData.25 * This is used when initializing the game world.26 * It should (generally) only be called once for each layer.27 * @param {Canvas} canvas28 * @returns {Object} - An object containing: context, bounds, ration, canvasWidth, canvasHeight29 */30 getCanvasData(canvas) {31 const bounds = canvas.getBoundingClientRect();32 const ratio = bounds.width / bounds.height;33 const canvasWidth = Math.round(Math.min(bounds.width, 800) * ratio);34 const canvasHeight = Math.round(Math.min(bounds.height, 800));35 const context = canvas.getContext('2d');36 return { context, bounds, ratio, canvasWidth, canvasHeight };37 },38 /**39 * getContextPixels.40 * This returns an 2D array with the values of the alpha layer of a context.41 * We use data calculated in this function to in the physics engine42 * to do collision detection between actors and the terrain.43 *44 * @param {Object} arguments45 * @param {CanvasRenderingContext2D} arguments.context - context to read the alpha pixels from46 * @param {number} arguments.canvasWidth - absolute width of the canvas to process47 * @param {number} arguments.canvasHeight - absolute height of the canvas to process48 * @returns {Uint8Array[]}49 */50 getContextPixels({ context, canvasWidth, canvasHeight }) {51 const imageData = context.getImageData(0, 0, canvasWidth, canvasHeight);52 const allAlpha = imageData.data53 .filter((_, index) => (index + 1) % 4 === 0);54 const pixels = {};55 // Split them into the map for faster access56 for (let i = 0; i < imageData.height; i++) {57 const start = i * imageData.width;58 const slice = allAlpha.slice(start, start + imageData.width);59 if (slice.every((t) => t === 0)) { continue; }60 pixels[i] = Uint8Array.from(allAlpha.slice(start, start + imageData.width));61 }62 return pixels;63 },64 /**65 * updateViewport.66 * Calculates what the new viewport should be.67 *68 * @param {Object} arguments69 * @param {Viewport} arguments.oldViewport - old viewport which will be returned if there70 * is no difference between the new and the old viewport71 * @param {number} arguments.canvasWidth - absolute width of the canvas/screen72 * @param {number} arguments.canvasHeight - absolute height of the canvas/screen73 * @param {number} arguments.mapWidth - absolute width of the map74 * @param {number} arguments.mapHeight - absolute height of the map75 * @param {number} arguments.scale - an integer, 1 => no scaling76 * @param {Actor} arguments.player - the player to center the viewport on77 * @returns {Viewport}78 */79 updateViewport({80 oldViewport, player, mapWidth, mapHeight, scale, canvasWidth, canvasHeight,81 }) {82 const viewportWidth = canvasWidth / scale;83 const viewportHeight = canvasHeight / scale;84 // Constantly updating viewport85 const centerx = Math.round((player.x + player.width / 2));86 const centery = Math.round((player.y + player.height / 2));87 const viewport = {88 x: Math.min(89 Math.max(0, Math.round(centerx - viewportWidth / 2)),90 mapWidth - viewportWidth,91 ),92 y: Math.min(93 Math.max(0, Math.round(centery - viewportHeight / 2)),94 mapHeight - viewportHeight,95 ),96 width: Math.round(viewportWidth),97 height: Math.round(viewportHeight),98 scale,99 };100 if (oldViewport101 && oldViewport.x === viewport.x102 && oldViewport.y === viewport.y103 && oldViewport.width === viewport.width104 && oldViewport.height === viewport.height105 && oldViewport.scale === viewport.scale) {106 return oldViewport;107 }108 return viewport;109 },110 /**111 * drawScene.112 * Draws an entire scene.113 * This function should be called once per frame to redraw the three layers.114 * @param {Object} arguments115 * @param {Actor} arguments.player,116 * @param {Actor[]} arguments.characters,117 * @param {Actor[]} arguments.items,118 * @param {Actor[]} arguments.oldItems,119 * @param {CanvasRenderingContext2D} arguments.context,120 * @param {number} arguments.width,121 * @param {number} arguments.height,122 * @param {number} arguments.sprites,123 * @param {Viewport} arguments.viewport,124 * @param {Viewport} arguments.oldViewport,125 * @param {CanvasRenderingContext2D} arguments.layoutContext,126 * @param {CanvasRenderingContext2D} arguments.aboveContext,127 * @param {function} arguments.drawActorToContext,128 * @returns undefined129 */130 drawScene({131 player,132 characters,133 items,134 oldItems,135 context,136 width,137 height,138 sprites,139 viewport,140 oldViewport,141 layoutContext,142 aboveContext,143 drawActorToContext,144 }) {145 if (oldViewport !== viewport || oldItems !== items) {146 if (aboveContext) {147 aboveContext.clearRect(0, 0, width, height);148 const aboveData = sprites.above[width * viewport.scale];149 aboveContext.drawImage(150 aboveData.canvas,151 viewport.x * viewport.scale,152 viewport.y * viewport.scale,153 viewport.width * viewport.scale,154 viewport.height * viewport.scale,155 0, 0,156 viewport.width * viewport.scale,157 viewport.height * viewport.scale,158 );159 }160 const layoutData = sprites.background[width * viewport.scale];161 layoutContext.drawImage(162 layoutData.canvas,163 viewport.x * viewport.scale,164 viewport.y * viewport.scale,165 viewport.width * viewport.scale,166 viewport.height * viewport.scale,167 0, 0,168 viewport.width * viewport.scale,169 viewport.height * viewport.scale,170 );171 // Draw Items on the background172 for (let i = 0; i < items.length; i++) {173 const actor = items[i];174 if (actor.inInventory || actor.hidden) { continue; }175 if (!Camera.isWithinViewport({ viewport, actor })) { continue; }176 drawActorToContext({177 context: layoutContext,178 sprites,179 actor,180 offset: viewport,181 scale: viewport.scale,182 defaultSprite: 'itemSprite',183 color: 'lightblue',184 });185 }186 }187 // Remove old188 context.clearRect(0, 0, width, height);189 // Draw new position player position190 drawActorToContext({191 context,192 sprites,193 actor: player,194 offset: viewport,195 scale: viewport.scale,196 defaultSprite: 'characterSprite',197 color: 'white',198 });199 for (let i = 0; i < characters.length; i++) {200 const actor = characters[i];201 if (!Camera.isWithinViewport({ viewport, actor })) { continue; }202 // Draw new position203 drawActorToContext({204 context,205 sprites,206 actor,207 offset: viewport,208 scale: viewport.scale,209 defaultSprite: 'characterSprite',210 color: actor.color || 'darkblue',211 });212 }213 },214 /**215 * drawGraph.216 * Draws out a graph of areas and their connection points.217 * This function is used for debugging path-finding and player movement.218 * @param {Object} args219 * @param {Object[]} args.graph - the graph220 * @param {CanvasRenderingContext2D} args.context the context to draw to221 * @param {Object} args.viewport the vewport to draw in222 * @returns {undefined}223 */224 drawGraph({ graph, context, viewport }) {225 graph.forEach((area) => {226 context.strokeStyle = 'black';227 context.strokeRect(228 (area.x - viewport.x) * viewport.scale,229 (area.y - viewport.y) * viewport.scale,230 area.width * viewport.scale,231 area.height * viewport.scale,232 );233 context.strokeStyle = 'red';234 area.points.forEach((point) => {235 context.strokeRect(236 (point.x - viewport.x - 1) * viewport.scale,237 (point.y - viewport.y - 1) * viewport.scale,238 2,239 2,240 );241 });242 });243 },244 /**245 * drawDestinations.246 * Draws all of the characters paths and247 * This function is used for debugging path-finding and player movement.248 * @param {Object} args249 * @param {Actor[]} args.characters250 * @param {CanvasRenderingContext2D} args.context251 * @param {Viewport} args.viewport252 * @returns {undefined}253 */254 drawDestinations({ characters, context, viewport }) {255 context.clearRect(0, 0, context.canvas.width, context.canvas.height);256 context.fillStyle = 'black';257 const colors = ['lightblue', 'red', 'yellow', 'green', 'blue', 'brown', 'purple', 'pink', 'magenta'];258 characters.forEach((c) => {259 context.strokeStyle = 'black';260 const dest = (c.waypoints && c.waypoints[c.waypoints.length - 1]) || c.destination;261 if (!dest) { return; }262 context.fillRect(263 (dest.x - 5 - viewport.x) * viewport.scale,264 (dest.y - 5 - viewport.y) * viewport.scale,265 10 * viewport.scale,266 10 * viewport.scale,267 );268 if (!c.waypoints) { return; }269 context.strokeStyle = colors[c.waypoints.length % colors.length];270 context.beginPath();271 context.moveTo(272 (Math.round(c.x + c.width / 2) - viewport.x) * viewport.scale,273 (Math.round(c.y + c.height / 2) - viewport.y) * viewport.scale,274 );275 context.lineTo(276 (c.destination.x - viewport.x) * viewport.scale,277 (c.destination.y - viewport.y) * viewport.scale,278 );279 c.waypoints.forEach((t) => {280 context.lineTo((t.x - viewport.x) * viewport.scale, (t.y - viewport.y) * viewport.scale);281 });282 context.stroke();283 });284 },285 /**286 * isWithinViewport.287 * Returns truy if an actor is within a viewport.288 * Used to select which actors to draw.289 * @param {Object} args290 * @param {Viewport} args.viewport291 * @param {Actor} args.actor292 * @returns {boolean}293 */294 isWithinViewport({ viewport, actor }) {295 if (viewport.x > (actor.x + actor.width) || (viewport.x + viewport.width) < actor.x) {296 return false;297 }298 if (viewport.y > (actor.y + actor.height) || (viewport.y + viewport.height) < actor.y) {299 return false;300 }301 return true;302 },...

Full Screen

Full Screen

Default.js

Source:Default.js Github

copy

Full Screen

1describe("Ext.viewport.Default", function() {2 var addWindowListenerSpy,3 Viewport = Ext.viewport.Default;4 Viewport.override({5 addWindowListener: function() {6 if (!addWindowListenerSpy) return this.callOverridden(arguments);7 addWindowListenerSpy.apply(this, arguments);8 },9 getWindowOrientation: function() {10 return 0;11 },12 waitUntil: function(condition, onSatisfied) {13 onSatisfied.call(this);14 }15 });16 beforeEach(function() {17 addWindowListenerSpy = jasmine.createSpy();18 });19 describe("constructor()", function(){20 it("should attach initial listeners", function(){21 var viewport = new Viewport();22 expect(addWindowListenerSpy).toHaveBeenCalled();23 viewport.destroy();24 });25 });26 describe("methods", function(){27 var viewport;28 beforeEach(function() {29 viewport = new Viewport();30 });31 afterEach(function(){32 viewport.destroy();33 });34 describe("onWindowReady()", function() {35 it("should set isReady flag to true", function() {36 viewport.onDomReady();37 expect(viewport.isReady).toBe(true);38 });39 });40 describe("doAddListener()", function(){41 it("should invoke the listener immediately if eventName is 'ready' and isReady flag equals 'true'", function(){42 var fn = jasmine.createSpy();43 viewport.isReady = true;44 viewport.addListener('ready', fn);45 expect(fn).toHaveBeenCalled();46 });47 it("should proxy to observable mixin's doAddListener() otherwise", function(){48 var fn = jasmine.createSpy();49 viewport.isReady = false;50 viewport.addListener('ready', fn);51 expect(fn).not.toHaveBeenCalled();52 expect(viewport.events.ready.listeners.length).toBe(1);53 });54 });55 describe("onResize()", function(){56 it("should invoke getWindowWidth() and getWindowHeight()", function(){57 spyOn(viewport, 'getWindowWidth');58 spyOn(viewport, 'getWindowHeight');59 viewport.onResize();60 expect(viewport.getWindowWidth).toHaveBeenCalled();61 expect(viewport.getWindowHeight).toHaveBeenCalled();62 });63 it("should NOT fire a 'resize' event if the size doesn't change", function(){64 spyOn(viewport, 'fireEvent');65 viewport.onResize();66 expect(viewport.fireEvent).not.toHaveBeenCalled();67 });68 });69 describe("determineOrientation()", function(){70 describe("if supportOrientation is true", function(){71 beforeEach(function() {72 spyOn(viewport, 'supportsOrientation').andReturn(true);73 });74 it("should invoke getWindowOrientation()", function(){75 spyOn(viewport, 'getWindowOrientation');76 viewport.determineOrientation();77 expect(viewport.getWindowOrientation).toHaveBeenCalled();78 });79 it("should return viewport.PORTRAIT if orientation equals 0", function(){80 spyOn(viewport, 'getWindowOrientation').andReturn(0);81 var orientation = viewport.determineOrientation();82 expect(orientation).toBe(viewport.PORTRAIT);83 });84 it("should return viewport.PORTRAIT if orientation equals 180", function(){85 spyOn(viewport, 'getWindowOrientation').andReturn(180);86 var orientation = viewport.determineOrientation();87 expect(orientation).toBe(viewport.PORTRAIT);88 });89 it("should return viewport.LANDSCAPE if orientation equals 90", function(){90 spyOn(viewport, 'getWindowOrientation').andReturn(90);91 var orientation = viewport.determineOrientation();92 expect(orientation).toBe(viewport.LANDSCAPE);93 });94 it("should return viewport.LANDSCAPE if orientation equals -90", function(){95 spyOn(viewport, 'getWindowOrientation').andReturn(-90);96 var orientation = viewport.determineOrientation();97 expect(orientation).toBe(viewport.LANDSCAPE);98 });99 it("should return viewport.LANDSCAPE if orientation equals 270", function(){100 spyOn(viewport, 'getWindowOrientation').andReturn(270);101 var orientation = viewport.determineOrientation();102 expect(orientation).toBe(viewport.LANDSCAPE);103 });104 });105 describe("if supportOrientation is false", function(){106 beforeEach(function() {107 spyOn(viewport, 'supportsOrientation').andReturn(false);108 });109 it("should return a value other then null", function(){110 var orientation = viewport.determineOrientation();111 expect(orientation).not.toBeNull();112 });113 });114 });115 describe("onOrientationChange()", function(){116 it("should invoke determineOrientation()", function(){117 spyOn(viewport, 'determineOrientation');118 viewport.onOrientationChange();119 expect(viewport.determineOrientation).toHaveBeenCalled();120 });121 it("should NOT fire an 'orientationchange' event if the orientation didn't change", function(){122 spyOn(viewport, 'fireEvent');123 viewport.onOrientationChange();124 expect(viewport.fireEvent).not.toHaveBeenCalled();125 });126 it("should fire an 'orientationchange' event and pass the new orientation, width and height as arguments, if the orientation did change", function(){127 var newOrientation = viewport.LANDSCAPE;128 viewport.setWidth(100);129 viewport.setHeight(200);130 viewport.setOrientation(viewport.PORTRAIT);131 spyOn(viewport, 'determineOrientation').andReturn(newOrientation);132 spyOn(viewport, 'fireEvent');133 viewport.onOrientationChange();134 expect(viewport.fireEvent).toHaveBeenCalledWith('orientationchange', viewport, newOrientation, 100, 200);135 });136 });137 });...

Full Screen

Full Screen

Panel.js

Source:Panel.js Github

copy

Full Screen

1import React, { Component } from 'react';2import PropTypes from 'prop-types';3import { baseFonts } from '@storybook/components';4import { document } from 'global';5import debounce from 'lodash.debounce';6import { resetViewport, viewportsTransformer } from './viewportInfo';7import { SelectViewport } from './SelectViewport';8import { RotateViewport } from './RotateViewport';9import {10 SET_STORY_DEFAULT_VIEWPORT_EVENT_ID,11 CONFIGURE_VIEWPORT_EVENT_ID,12 UPDATE_VIEWPORT_EVENT_ID,13 VIEWPORT_CHANGED_EVENT_ID,14 INITIAL_VIEWPORTS,15 DEFAULT_VIEWPORT,16} from '../../shared';17import * as styles from './styles';18const storybookIframe = 'storybook-preview-iframe';19const containerStyles = {20 padding: 15,21 width: '100%',22 boxSizing: 'border-box',23 ...baseFonts,24};25const getDefaultViewport = (viewports, candidateViewport) =>26 candidateViewport in viewports ? candidateViewport : Object.keys(viewports)[0];27const getViewports = viewports =>28 Object.keys(viewports).length > 0 ? viewports : INITIAL_VIEWPORTS;29const setStoryDefaultViewportWait = 100;30export class Panel extends Component {31 static propTypes = {32 channel: PropTypes.shape({}).isRequired,33 api: PropTypes.shape({}).isRequired,34 };35 static defaultOptions = {36 viewports: INITIAL_VIEWPORTS,37 defaultViewport: DEFAULT_VIEWPORT,38 };39 constructor(props, context) {40 super(props, context);41 this.state = {42 viewport: DEFAULT_VIEWPORT,43 defaultViewport: DEFAULT_VIEWPORT,44 viewports: viewportsTransformer(INITIAL_VIEWPORTS),45 isLandscape: false,46 };47 this.previousViewport = DEFAULT_VIEWPORT;48 this.setStoryDefaultViewport = debounce(49 this.setStoryDefaultViewport,50 setStoryDefaultViewportWait51 );52 }53 componentDidMount() {54 const { channel, api } = this.props;55 this.iframe = document.getElementById(storybookIframe);56 channel.on(UPDATE_VIEWPORT_EVENT_ID, this.changeViewport);57 channel.on(CONFIGURE_VIEWPORT_EVENT_ID, this.configure);58 channel.on(SET_STORY_DEFAULT_VIEWPORT_EVENT_ID, this.setStoryDefaultViewport);59 this.unsubscribeFromOnStory = api.onStory(() => {60 this.setStoryDefaultViewport(this.state.defaultViewport);61 });62 }63 componentWillUnmount() {64 const { channel } = this.props;65 if (this.unsubscribeFromOnStory) {66 this.unsubscribeFromOnStory();67 }68 channel.removeListener(UPDATE_VIEWPORT_EVENT_ID, this.changeViewport);69 channel.removeListener(CONFIGURE_VIEWPORT_EVENT_ID, this.configure);70 channel.removeListener(SET_STORY_DEFAULT_VIEWPORT_EVENT_ID, this.setStoryDefaultViewport);71 }72 setStoryDefaultViewport = viewport => {73 const { viewports } = this.state;74 const defaultViewport = getDefaultViewport(viewports, viewport);75 this.setState({76 storyDefaultViewport: defaultViewport,77 });78 this.changeViewport(defaultViewport);79 };80 configure = (options = Panel.defaultOptions) => {81 const viewports = getViewports(options.viewports);82 const defaultViewport = getDefaultViewport(viewports, options.defaultViewport);83 this.setState(84 {85 defaultViewport,86 viewport: defaultViewport,87 viewports: viewportsTransformer(viewports),88 },89 this.updateIframe90 );91 };92 iframe = undefined;93 changeViewport = viewport => {94 const { viewport: previousViewport } = this.state;95 if (previousViewport !== viewport) {96 this.setState(97 {98 viewport,99 isLandscape: false,100 },101 () => {102 this.updateIframe();103 this.emitViewportChanged();104 }105 );106 }107 };108 emitViewportChanged = () => {109 const { channel } = this.props;110 const { viewport, viewports } = this.state;111 if (!this.shouldNotify()) {112 return;113 }114 this.previousViewport = viewport;115 channel.emit(VIEWPORT_CHANGED_EVENT_ID, {116 viewport: viewports[viewport],117 });118 };119 shouldNotify = () => this.previousViewport !== this.state.viewport;120 toggleLandscape = () => {121 const { isLandscape } = this.state;122 this.setState({ isLandscape: !isLandscape }, this.updateIframe);123 };124 updateIframe = () => {125 const { viewports, viewport: viewportKey, isLandscape } = this.state;126 const viewport = viewports[viewportKey] || resetViewport;127 if (!this.iframe) {128 throw new Error('Cannot find Storybook iframe');129 }130 Object.keys(viewport.styles).forEach(prop => {131 this.iframe.style[prop] = viewport.styles[prop];132 });133 if (isLandscape) {134 this.iframe.style.height = viewport.styles.width;135 this.iframe.style.width = viewport.styles.height;136 }137 // Always make parent's height equals iframe138 if (this.iframe.parentElement) {139 this.iframe.parentElement.style.height = this.iframe.style.height;140 }141 };142 render() {143 const {144 isLandscape,145 defaultViewport,146 storyDefaultViewport = defaultViewport,147 viewport,148 viewports,149 } = this.state;150 const disableDefault = viewport === storyDefaultViewport;151 const disabledStyles = disableDefault ? styles.disabled : {};152 const buttonStyles = {153 ...styles.button,154 ...disabledStyles,155 marginTop: 30,156 padding: 20,157 };158 return (159 <div style={containerStyles}>160 <SelectViewport161 viewports={viewports}162 defaultViewport={storyDefaultViewport}163 activeViewport={viewport}164 onChange={e => this.changeViewport(e.target.value)}165 />166 <RotateViewport167 onClick={this.toggleLandscape}168 disabled={disableDefault}169 active={isLandscape}170 />171 <button172 style={buttonStyles}173 onClick={() => this.changeViewport(storyDefaultViewport)}174 disabled={disableDefault}175 >176 Reset Viewport177 </button>178 </div>179 );180 }...

Full Screen

Full Screen

f3e337635dadf8853a1deceac44ebfc92da37abd_0_1.js

Source:f3e337635dadf8853a1deceac44ebfc92da37abd_0_1.js Github

copy

Full Screen

1function loadMap(theTile) {2 3 Crafty("remove").each(function() {4 this.destroy();5 });6 7 if(theTile === tile4){8 theTileC = tile4c;9 } else {10 theTileC = tile5c;11 }12 13 for(var k = 1; k <= player.hp.max; k++){14 hearts[k-1].attr({ x: (480 - (k * 34))-Crafty.viewport.x , y: 3-Crafty.viewport.y});15 }16 17 if(theTile === tile4 || theTile === tile5){18 for(var i = 0; i < 15; i++){19 for(var j = 0; j < 10; j++) {20 Crafty.e("2D, DOM, remove, cavefloor" + Crafty.math.randomInt(1, 4))21 .attr({x: (i * 32)-Crafty.viewport.x, y: (j * 32)-Crafty.viewport.y, z:2});22 }23 }24 for(var i = 0; i < 95; i++) { 25 cavey[i] = Crafty.e("2D, DOM, solid, remove, cavewall" + Crafty.math.randomInt(1, 3));26 }27 for(var i = 0; i < 15; i++){28 for(var j = 0; j < 10; j++) {29 if(theTileC[j][i] === BUSH) {30 cavey[cCount].attr({x: (i * 32)-Crafty.viewport.x, y: (j * 32)-Crafty.viewport.y, z:2});31 cCount = cCount + 1;32 } else if(theTileC[j][i] === TLLAVA) {33 Crafty.e("2D, DOM, tllava, remove, Collision,solid")34 .attr({x:(i * 32)-Crafty.viewport.x, 35 y: (j * 32)-Crafty.viewport.y,36 z:3});37 } else if(theTileC[j][i] === LLAVA) {38 Crafty.e("2D, DOM, llava, remove, Collision,solid")39 .attr({x:(i * 32)-Crafty.viewport.x, 40 y: (j * 32)-Crafty.viewport.y,41 z:3});42 } else if(theTileC[j][i] === BLLAVA) {43 Crafty.e("2D, DOM, bllava, remove, Collision,solid")44 .attr({x:(i * 32)-Crafty.viewport.x, 45 y: (j * 32)-Crafty.viewport.y,46 z:3});47 } else if(theTileC[j][i] === TLAVA) {48 Crafty.e("2D, DOM, tlava, remove, Collision,solid")49 .attr({x:(i * 32)-Crafty.viewport.x, 50 y: (j * 32)-Crafty.viewport.y,51 z:3});52 } else if(theTileC[j][i] === LAVA) {53 Crafty.e("2D, DOM, lava, remove, Collision,solid")54 .attr({x:(i * 32)-Crafty.viewport.x, 55 y: (j * 32)-Crafty.viewport.y,56 z:3});57 } else if(theTileC[j][i] === BLAVA) {58 Crafty.e("2D, DOM, blava, remove, Collision,solid")59 .attr({x:(i * 32)-Crafty.viewport.x, 60 y: (j * 32)-Crafty.viewport.y,61 z:3});62 } else if(theTileC[j][i] === TRLAVA) {63 Crafty.e("2D, DOM, trlava, remove, Collision,solid")64 .attr({x:(i * 32)-Crafty.viewport.x, 65 y: (j * 32)-Crafty.viewport.y,66 z:3});67 } else if(theTileC[j][i] === RLAVA) {68 Crafty.e("2D, DOM, rlava, remove, Collision,solid")69 .attr({x:(i * 32)-Crafty.viewport.x, 70 y: (j * 32)-Crafty.viewport.y,71 z:3});72 } else if(theTileC[j][i] === BRLAVA) {73 Crafty.e("2D, DOM, brlava, remove, Collision,solid")74 .attr({x:(i * 32)-Crafty.viewport.x, 75 y: (j * 32)-Crafty.viewport.y,76 z:3});77 }78 }79 }80 }81 82 if(mspawn){83 84 for(var i = 0; i< 10; i++){85 mbars[i].attr({ x: 448-Crafty.viewport.x , y:103-(i*8)-Crafty.viewport.y});86 }87 88 bars[0].attr({x:480-34-Crafty.viewport.x,y:37-Crafty.viewport.y});89 bars[1].attr({x:480-34-Crafty.viewport.x,y:37+22-Crafty.viewport.y});90 bars[2].attr({x:480-34-Crafty.viewport.x,y:37+21+22-Crafty.viewport.y});91 bars[3].attr({x:480-34-Crafty.viewport.x,y:37+21+22+17-Crafty.viewport.y});92 } 93 94 for(var i = 0; i < 30; i++) {95 for(var j = 0; j < 20; j++) {96 97 grassy[gCount].attr({x: (i * 16)-Crafty.viewport.x, y: (j * 16)-Crafty.viewport.y});98 gCount = gCount + 1;99 100 if (theTile[j][i] === BUSH && !(theTile === tile4 || theTile === tile5)) {101 bushy[bCount].attr({x: (i * 16)-Crafty.viewport.x, y: (j * 16)-Crafty.viewport.y, z:2});102 bCount = bCount + 1;103 }104 else if (theTile[j][i] === OBST) {105 Crafty.e("2D, DOM, solid, remove, SpriteAnimation, stuff" + Crafty.math.randomInt(1, 4))106 .attr({x: (i * 16)-Crafty.viewport.x,107 y: (j * 16)-Crafty.viewport.y,108 z:2});109 }110 else if (theTile[j][i] === ENEMY) {111 Crafty.e("Enemy", "remove", "kill")112 .attr({x:(i * 16)-Crafty.viewport.x, 113 y: (j * 16)-Crafty.viewport.y,114 z:3});115 } else if (theTile[j][i] === BOSS1 && !mspawn) {116 Crafty.e("Boss1", "remove", "kill")117 .attr({x:(i * 16)-Crafty.viewport.x, 118 y: (j * 16)-Crafty.viewport.y,119 z:3});120 } else if (theTile[j][i] === BOSS2 && !bspawn) {121 Crafty.e("Boss2", "remove")122 .attr({x:(i * 16)-Crafty.viewport.x, 123 y: (j * 16)-Crafty.viewport.y,124 z:3});125 }else if(theTile[j][i] === ARENEMY) {126 Crafty.e("AEnemy", "remove", "kill")127 .attr({x:(i * 16)-Crafty.viewport.x, 128 y: (j * 16)-Crafty.viewport.y,129 z:3});130 }else if(theTile[j][i] === LRIVER) {131 Crafty.e("2D, DOM leriv, remove, Collision, solid")132 .attr({x:(i * 16)-Crafty.viewport.x, 133 y: (j * 16)-Crafty.viewport.y,134 z:3});135 } else if(theTile[j][i] === CRIVER) {136 Crafty.e("2D, DOM, ceriv, remove, Collision,solid")137 .attr({x:(i * 16)-Crafty.viewport.x, 138 y: (j * 16)-Crafty.viewport.y,139 z:3});140 } else if(theTile[j][i] === RRIVER) {141 Crafty.e("2D, DOM, ririv, remove, Collision,solid")142 .attr({x:(i * 16)-Crafty.viewport.x, 143 y: (j * 16)-Crafty.viewport.y,144 z:3});145 } 146 }147 }148 149 bCount = 0;150 gCount = 0; 151 cCount = 0;...

Full Screen

Full Screen

a1805a9f1a002d7e3bc904f11ede840a6f39776b_0_1.js

Source:a1805a9f1a002d7e3bc904f11ede840a6f39776b_0_1.js Github

copy

Full Screen

1function loadMap(theTile) {2 3 Crafty("remove").each(function() {4 this.destroy();5 });6 7 var theTileC = theTile + "c";8 for(var k = 1; k <= player.hp.max; k++){9 hearts[k-1].attr({ x: (480 - (k * 34))-Crafty.viewport.x , y: 3-Crafty.viewport.y});10 }11 12 if(theTile === tile4 || theTile === tile5){13 for(var i = 0; i < 15; i++){14 for(var j = 0; j < 10; j++) {15 Crafty.e("2D, DOM, remove, cavefloor" + Crafty.math.randomInt(1, 4))16 .attr({x: (i * 32)-Crafty.viewport.x, y: (j * 32)-Crafty.viewport.y, z:2});17 }18 }19 for(var i = 0; i < 95; i++) { 20 cavey[i] = Crafty.e("2D, DOM, solid, remove, cavewall" + Crafty.math.randomInt(1, 3));21 }22 for(var i = 0; i < 15; i++){23 for(var i = 0; i < 10; i++) {24 if(theTileC[j][i] === BUSH) {25 cavey[cCount].attr({x: (i * 32)-Crafty.viewport.x, y: (j * 32)-Crafty.viewport.y, z:2});26 cCount = cCount + 1;27 } else if(theTileC[j][i] === TLLAVA) {28 Crafty.e("2D, DOM, tllava, remove, Collision,solid")29 .attr({x:(i * 32)-Crafty.viewport.x, 30 y: (j * 32)-Crafty.viewport.y,31 z:3});32 } else if(theTileC[j][i] === LLAVA) {33 Crafty.e("2D, DOM, llava, remove, Collision,solid")34 .attr({x:(i * 32)-Crafty.viewport.x, 35 y: (j * 32)-Crafty.viewport.y,36 z:3});37 } else if(theTileC[j][i] === BLLAVA) {38 Crafty.e("2D, DOM, bllava, remove, Collision,solid")39 .attr({x:(i * 32)-Crafty.viewport.x, 40 y: (j * 32)-Crafty.viewport.y,41 z:3});42 } else if(theTileC[j][i] === TLAVA) {43 Crafty.e("2D, DOM, tlava, remove, Collision,solid")44 .attr({x:(i * 32)-Crafty.viewport.x, 45 y: (j * 32)-Crafty.viewport.y,46 z:3});47 } else if(theTileC[j][i] === LAVA) {48 Crafty.e("2D, DOM, lava, remove, Collision,solid")49 .attr({x:(i * 32)-Crafty.viewport.x, 50 y: (j * 32)-Crafty.viewport.y,51 z:3});52 } else if(theTileC[j][i] === BLAVA) {53 Crafty.e("2D, DOM, blava, remove, Collision,solid")54 .attr({x:(i * 32)-Crafty.viewport.x, 55 y: (j * 32)-Crafty.viewport.y,56 z:3});57 } else if(theTileC[j][i] === TRLAVA) {58 Crafty.e("2D, DOM, trlava, remove, Collision,solid")59 .attr({x:(i * 32)-Crafty.viewport.x, 60 y: (j * 32)-Crafty.viewport.y,61 z:3});62 } else if(theTileC[j][i] === RLAVA) {63 Crafty.e("2D, DOM, rlava, remove, Collision,solid")64 .attr({x:(i * 32)-Crafty.viewport.x, 65 y: (j * 32)-Crafty.viewport.y,66 z:3});67 } else if(theTileC[j][i] === BRLAVA) {68 Crafty.e("2D, DOM, brlava, remove, Collision,solid")69 .attr({x:(i * 32)-Crafty.viewport.x, 70 y: (j * 32)-Crafty.viewport.y,71 z:3});72 }73 }74 }75 }76 77 if(mspawn){78 79 for(var i = 0; i< 10; i++){80 mbars[i].attr({ x: 448-Crafty.viewport.x , y:103-(i*8)-Crafty.viewport.y});81 }82 83 bars[0].attr({x:480-34-Crafty.viewport.x,y:37-Crafty.viewport.y});84 bars[1].attr({x:480-34-Crafty.viewport.x,y:37+22-Crafty.viewport.y});85 bars[2].attr({x:480-34-Crafty.viewport.x,y:37+21+22-Crafty.viewport.y});86 bars[3].attr({x:480-34-Crafty.viewport.x,y:37+21+22+17-Crafty.viewport.y});87 } 88 89 for(var i = 0; i < 30; i++) {90 for(var j = 0; j < 20; j++) {91 92 grassy[gCount].attr({x: (i * 16)-Crafty.viewport.x, y: (j * 16)-Crafty.viewport.y});93 gCount = gCount + 1;94 95 if (theTile[j][i] === BUSH && !(theTile === tile4 || theTile === tile5)) {96 bushy[bCount].attr({x: (i * 16)-Crafty.viewport.x, y: (j * 16)-Crafty.viewport.y, z:2});97 bCount = bCount + 1;98 }99 else if (theTile[j][i] === OBST) {100 Crafty.e("2D, DOM, solid, remove, SpriteAnimation, stuff" + Crafty.math.randomInt(1, 4))101 .attr({x: (i * 16)-Crafty.viewport.x,102 y: (j * 16)-Crafty.viewport.y,103 z:2});104 }105 else if (theTile[j][i] === ENEMY) {106 Crafty.e("Enemy", "remove", "kill")107 .attr({x:(i * 16)-Crafty.viewport.x, 108 y: (j * 16)-Crafty.viewport.y,109 z:3});110 } else if (theTile[j][i] === BOSS1 && !mspawn) {111 Crafty.e("Boss1", "remove", "kill")112 .attr({x:(i * 16)-Crafty.viewport.x, 113 y: (j * 16)-Crafty.viewport.y,114 z:3});115 } else if (theTile[j][i] === BOSS2 && !bspawn) {116 Crafty.e("Boss2", "remove")117 .attr({x:(i * 16)-Crafty.viewport.x, 118 y: (j * 16)-Crafty.viewport.y,119 z:3});120 }else if(theTile[j][i] === ARENEMY) {121 Crafty.e("AEnemy", "remove", "kill")122 .attr({x:(i * 16)-Crafty.viewport.x, 123 y: (j * 16)-Crafty.viewport.y,124 z:3});125 }else if(theTile[j][i] === LRIVER) {126 Crafty.e("2D, DOM leriv, remove, Collision, solid")127 .attr({x:(i * 16)-Crafty.viewport.x, 128 y: (j * 16)-Crafty.viewport.y,129 z:3});130 } else if(theTile[j][i] === CRIVER) {131 Crafty.e("2D, DOM, ceriv, remove, Collision,solid")132 .attr({x:(i * 16)-Crafty.viewport.x, 133 y: (j * 16)-Crafty.viewport.y,134 z:3});135 } else if(theTile[j][i] === RRIVER) {136 Crafty.e("2D, DOM, ririv, remove, Collision,solid")137 .attr({x:(i * 16)-Crafty.viewport.x, 138 y: (j * 16)-Crafty.viewport.y,139 z:3});140 } 141 }142 }143 144 bCount = 0;145 gCount = 0; 146 cCount = 0;...

Full Screen

Full Screen

836b1c2698f40abcd431174cb7cffc773aa8a5a0_0_1.js

Source:836b1c2698f40abcd431174cb7cffc773aa8a5a0_0_1.js Github

copy

Full Screen

1function loadMap(theTile) {2 3 Crafty("remove").each(function() {4 this.destroy();5 });6 7 var theTileC = theTile + "c";8 for(var k = 1; k <= player.hp.max; k++){9 hearts[k-1].attr({ x: (480 - (k * 34))-Crafty.viewport.x , y: 3-Crafty.viewport.y});10 }11 12 if(theTile === tile4 || theTile === tile5){13 for(var i = 0; i < 15; i++){14 for(var j = 0; j < 10; j++) {15 Crafty.e("2D, DOM, remove, cavefloor" + Crafty.math.randomInt(1, 4))16 .attr({x: (i * 32)-Crafty.viewport.x, y: (j * 32)-Crafty.viewport.y, z:2});17 }18 }19 for(var i = 0; i < 95; i++) { 20 cavey[i] = Crafty.e("2D, DOM, solid, remove, cavewall" + Crafty.math.randomInt(1, 3));21 }22 for(var i = 0; i < 15; i++){23 for(var i = 0; i < 10; i++) {24 if(theTileC[j][i] === BUSH) {25 cavey[cCount].attr({x: (i * 32)-Crafty.viewport.x, y: (j * 32)-Crafty.viewport.y, z:2});26 cCount = cCount + 1;27 } else if(theTileC[j][i] === TLLAVA) {28 Crafty.e("2D, DOM, tllava, remove, Collision,solid")29 .attr({x:(i * 32)-Crafty.viewport.x, 30 y: (j * 32)-Crafty.viewport.y,31 z:3});32 } else if(theTileC[j][i] === LLAVA) {33 Crafty.e("2D, DOM, llava, remove, Collision,solid")34 .attr({x:(i * 32)-Crafty.viewport.x, 35 y: (j * 32)-Crafty.viewport.y,36 z:3});37 } else if(theTileC[j][i] === BLLAVA) {38 Crafty.e("2D, DOM, bllava, remove, Collision,solid")39 .attr({x:(i * 32)-Crafty.viewport.x, 40 y: (j * 32)-Crafty.viewport.y,41 z:3});42 } else if(theTileC[j][i] === TLAVA) {43 Crafty.e("2D, DOM, tlava, remove, Collision,solid")44 .attr({x:(i * 32)-Crafty.viewport.x, 45 y: (j * 32)-Crafty.viewport.y,46 z:3});47 } else if(theTileC[j][i] === LAVA) {48 Crafty.e("2D, DOM, lava, remove, Collision,solid")49 .attr({x:(i * 32)-Crafty.viewport.x, 50 y: (j * 32)-Crafty.viewport.y,51 z:3});52 } else if(theTileC[j][i] === BLAVA) {53 Crafty.e("2D, DOM, blava, remove, Collision,solid")54 .attr({x:(i * 32)-Crafty.viewport.x, 55 y: (j * 32)-Crafty.viewport.y,56 z:3});57 } else if(theTileC[j][i] === TRLAVA) {58 Crafty.e("2D, DOM, trlava, remove, Collision,solid")59 .attr({x:(i * 32)-Crafty.viewport.x, 60 y: (j * 32)-Crafty.viewport.y,61 z:3});62 } else if(theTileC[j][i] === RLAVA) {63 Crafty.e("2D, DOM, rlava, remove, Collision,solid")64 .attr({x:(i * 32)-Crafty.viewport.x, 65 y: (j * 32)-Crafty.viewport.y,66 z:3});67 } else if(theTileC[j][i] === BRLAVA) {68 Crafty.e("2D, DOM, brlava, remove, Collision,solid")69 .attr({x:(i * 32)-Crafty.viewport.x, 70 y: (j * 32)-Crafty.viewport.y,71 z:3});72 }73 }74 }75 }76 77 if(mspawn){78 79 for(var i = 0; i< 10; i++){80 mbars[i].attr({ x: 448-Crafty.viewport.x , y:103-(i*8)-Crafty.viewport.y});81 }82 83 bars[0].attr({x:480-34-Crafty.viewport.x,y:37-Crafty.viewport.y});84 bars[1].attr({x:480-34-Crafty.viewport.x,y:37+22-Crafty.viewport.y});85 bars[2].attr({x:480-34-Crafty.viewport.x,y:37+21+22-Crafty.viewport.y});86 bars[3].attr({x:480-34-Crafty.viewport.x,y:37+21+22+17-Crafty.viewport.y});87 } 88 89 for(var i = 0; i < 30; i++) {90 for(var j = 0; j < 20; j++) {91 92 grassy[gCount].attr({x: (i * 16)-Crafty.viewport.x, y: (j * 16)-Crafty.viewport.y});93 gCount = gCount + 1;94 95 if (theTile[j][i] === BUSH && !(theTile === tile4 || theTile === tile5)) {96 bushy[bCount].attr({x: (i * 16)-Crafty.viewport.x, y: (j * 16)-Crafty.viewport.y, z:2});97 bCount = bCount + 1;98 }99 else if (theTile[j][i] === OBST) {100 Crafty.e("2D, DOM, solid, remove, SpriteAnimation, stuff" + Crafty.math.randomInt(1, 4))101 .attr({x: (i * 16)-Crafty.viewport.x,102 y: (j * 16)-Crafty.viewport.y,103 z:2});104 }105 else if (theTile[j][i] === ENEMY) {106 Crafty.e("Enemy", "remove", "kill")107 .attr({x:(i * 16)-Crafty.viewport.x, 108 y: (j * 16)-Crafty.viewport.y,109 z:3});110 } else if (theTile[j][i] === BOSS1 && !mspawn) {111 Crafty.e("Boss1", "remove", "kill")112 .attr({x:(i * 16)-Crafty.viewport.x, 113 y: (j * 16)-Crafty.viewport.y,114 z:3});115 } else if (theTile[j][i] === BOSS2 && !bspawn) {116 Crafty.e("Boss2", "remove")117 .attr({x:(i * 16)-Crafty.viewport.x, 118 y: (j * 16)-Crafty.viewport.y,119 z:3});120 }else if(theTile[j][i] === ARENEMY) {121 Crafty.e("AEnemy", "remove", "kill")122 .attr({x:(i * 16)-Crafty.viewport.x, 123 y: (j * 16)-Crafty.viewport.y,124 z:3});125 }else if(theTile[j][i] === LRIVER) {126 Crafty.e("2D, DOM leriv, remove, Collision, solid")127 .attr({x:(i * 16)-Crafty.viewport.x, 128 y: (j * 16)-Crafty.viewport.y,129 z:3});130 } else if(theTile[j][i] === CRIVER) {131 Crafty.e("2D, DOM, ceriv, remove, Collision,solid")132 .attr({x:(i * 16)-Crafty.viewport.x, 133 y: (j * 16)-Crafty.viewport.y,134 z:3});135 } else if(theTile[j][i] === RRIVER) {136 Crafty.e("2D, DOM, ririv, remove, Collision,solid")137 .attr({x:(i * 16)-Crafty.viewport.x, 138 y: (j * 16)-Crafty.viewport.y,139 z:3});140 } 141 }142 }143 144 bCount = 0;145 gCount = 0; 146 cCount = 0;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const devices = require('puppeteer/DeviceDescriptors');3const iPhone = devices['iPhone 6'];4(async () => {5 const browser = await puppeteer.launch();6 const page = await browser.newPage();7 await page.emulate(iPhone);8 await page.screenshot({path: 'example.png'});9 await browser.close();10})();11const puppeteer = require('puppeteer');12const devices = require('puppeteer/DeviceDescriptors');13const iPhone = devices['iPhone 6'];14(async () => {15 const browser = await puppeteer.launch();16 const page = await browser.newPage();17 await page.emulate(iPhone);18 await page.screenshot({path: 'example.png'});19 await browser.close();20})();21const puppeteer = require('puppeteer');22const devices = require('puppeteer/DeviceDescriptors');23const iPhone = devices['iPhone 6'];24(async () => {25 const browser = await puppeteer.launch();26 const page = await browser.newPage();27 await page.emulate(iPhone);28 await page.screenshot({path: 'example.png'});29 await browser.close();30})();31const puppeteer = require('puppeteer');32const devices = require('puppeteer/DeviceDescriptors');33const iPhone = devices['iPhone 6'];34(async () => {35 const browser = await puppeteer.launch();36 const page = await browser.newPage();37 await page.emulate(iPhone);38 await page.screenshot({path: 'example.png'});39 await browser.close();40})();41const puppeteer = require('puppeteer');42const devices = require('

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.setViewport({6 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3const browser = await puppeteer.launch({headless: false});4const page = await browser.newPage();5await page.setViewport({6});7await page.screenshot({path: 'google.png'});8await browser.close();9})();10const puppeteer = require('puppeteer');11(async () => {12const browser = await puppeteer.launch({headless: false});13const page = await browser.newPage();14await page.emulate({15viewport: {16},17});18await page.screenshot({path: 'google.png'});19await browser.close();20})();21const puppeteer = require('puppeteer');22(async () => {23const browser = await puppeteer.launch({headless: false});24const page = await browser.newPage();25await page.emulateMedia('screen');26await page.screenshot({path: 'google.png'});27await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31const browser = await puppeteer.launch({headless: false});32const page = await browser.newPage();33const title = await page.evaluate(() => {34return document.title;35});36console.log(`Title is: ${title}`);37await browser.close();38})();39const puppeteer = require('puppeteer');40(async () => {41const browser = await puppeteer.launch({headless: false});42const page = await browser.newPage();43const titleHandle = await page.evaluateHandle(() => document.title);44console.log(`Title is: ${await titleHandle.jsonValue()}`);45await browser.close();46})();47const puppeteer = require('puppeteer');48(async () => {49const browser = await puppeteer.launch({headless: false});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer 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