Commit d452afe4 authored by Tt's avatar Tt

OPW25

parent ca083805
export const defaultData = { export const defaultData = {
"pic_url": "http://staging-teach.cdn.ireadabc.com/ed94332a503c31e0908bd4c6923a2665.png", "pic_url": "http://staging-teach.cdn.ireadabc.com/ed94332a503c31e0908bd4c6923a2665.png",
"pic_url_2": "http://staging-teach.cdn.ireadabc.com/5fb60317ade0195d35ad8034d5370a7f.png", "pic_url_2": "http://staging-teach.cdn.ireadabc.com/5fb60317ade0195d35ad8034d5370a7f.png",
"text": "This is a test label.", "text": "This is a test label.",
"audio_url": "http://staging-teach.cdn.ireadabc.com/f47f1d7b5c160fe1c59500d180346240.mp3" "audio_url": "http://staging-teach.cdn.ireadabc.com/f47f1d7b5c160fe1c59500d180346240.mp3"
} }
\ No newline at end of file
/** /**
* Copyright (c) 2014-present, Facebook, Inc. * Copyright (c) 2014-present, Facebook, Inc.
* *
* This source code is licensed under the MIT license found in the * This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
!(function (global) { !(function (global) {
"use strict"; "use strict";
var Op = Object.prototype; var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty; var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0. var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {}; var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator"; var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
var inModule = typeof module === "object"; var inModule = typeof module === "object";
var runtime = global.regeneratorRuntime; var runtime = global.regeneratorRuntime;
if (runtime) { if (runtime) {
if (inModule) { if (inModule) {
// If regeneratorRuntime is defined globally and we're in a module, // If regeneratorRuntime is defined globally and we're in a module,
// make the exports object identical to regeneratorRuntime. // make the exports object identical to regeneratorRuntime.
module.exports = runtime; module.exports = runtime;
} }
// Don't bother evaluating the rest of this file if the runtime was // Don't bother evaluating the rest of this file if the runtime was
// already defined globally. // already defined globally.
return; return;
} }
// Define the runtime globally (as expected by generated code) as either // Define the runtime globally (as expected by generated code) as either
// module.exports (if we're in a module) or a new, empty object. // module.exports (if we're in a module) or a new, empty object.
runtime = global.regeneratorRuntime = inModule ? module.exports : {}; runtime = global.regeneratorRuntime = inModule ? module.exports : {};
function wrap(innerFn, outerFn, self, tryLocsList) { function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype); var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []); var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next, // The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods. // .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context); generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator; return generator;
} }
runtime.wrap = wrap; runtime.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion // Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could // record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be // have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we // invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need // already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming // to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true // the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The // in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which // only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate. // has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) { function tryCatch(fn, obj, arg) {
try { try {
return { type: "normal", arg: fn.call(obj, arg) }; return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) { } catch (err) {
return { type: "throw", arg: err }; return { type: "throw", arg: err };
} }
} }
var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield"; var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing"; var GenStateExecuting = "executing";
var GenStateCompleted = "completed"; var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as // Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement. // breaking out of the dispatch switch statement.
var ContinueSentinel = {}; var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and // Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator // .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your // objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions. // minifier not to mangle the names of these two functions.
function Generator() { } function Generator() { }
function GeneratorFunction() { } function GeneratorFunction() { }
function GeneratorFunctionPrototype() { } function GeneratorFunctionPrototype() { }
// This is a polyfill for %IteratorPrototype% for environments that // This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it. // don't natively support it.
var IteratorPrototype = {}; var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () { IteratorPrototype[iteratorSymbol] = function () {
return this; return this;
}; };
var getProto = Object.getPrototypeOf; var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype && if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op && NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead // This environment has a native %IteratorPrototype%; use it instead
// of the polyfill. // of the polyfill.
IteratorPrototype = NativeIteratorPrototype; IteratorPrototype = NativeIteratorPrototype;
} }
var Gp = GeneratorFunctionPrototype.prototype = var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype); Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunctionPrototype[toStringTagSymbol] =
GeneratorFunction.displayName = "GeneratorFunction"; GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the // Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method. // Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) { function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) { ["next", "throw", "return"].forEach(function (method) {
prototype[method] = function (arg) { prototype[method] = function (arg) {
return this._invoke(method, arg); return this._invoke(method, arg);
}; };
}); });
} }
runtime.isGeneratorFunction = function (genFun) { runtime.isGeneratorFunction = function (genFun) {
var ctor = typeof genFun === "function" && genFun.constructor; var ctor = typeof genFun === "function" && genFun.constructor;
return ctor return ctor
? ctor === GeneratorFunction || ? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can // For the native GeneratorFunction constructor, the best we can
// do is to check its .name property. // do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction" (ctor.displayName || ctor.name) === "GeneratorFunction"
: false; : false;
}; };
runtime.mark = function (genFun) { runtime.mark = function (genFun) {
if (Object.setPrototypeOf) { if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else { } else {
genFun.__proto__ = GeneratorFunctionPrototype; genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) { if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction"; genFun[toStringTagSymbol] = "GeneratorFunction";
} }
} }
genFun.prototype = Object.create(Gp); genFun.prototype = Object.create(Gp);
return genFun; return genFun;
}; };
// Within the body of any async function, `await x` is transformed to // Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is // `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited. // meant to be awaited.
runtime.awrap = function (arg) { runtime.awrap = function (arg) {
return { __await: arg }; return { __await: arg };
}; };
function AsyncIterator(generator) { function AsyncIterator(generator) {
function invoke(method, arg, resolve, reject) { function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg); var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") { if (record.type === "throw") {
reject(record.arg); reject(record.arg);
} else { } else {
var result = record.arg; var result = record.arg;
var value = result.value; var value = result.value;
if (value && if (value &&
typeof value === "object" && typeof value === "object" &&
hasOwn.call(value, "__await")) { hasOwn.call(value, "__await")) {
return Promise.resolve(value.__await).then(function (value) { return Promise.resolve(value.__await).then(function (value) {
invoke("next", value, resolve, reject); invoke("next", value, resolve, reject);
}, function (err) { }, function (err) {
invoke("throw", err, resolve, reject); invoke("throw", err, resolve, reject);
}); });
} }
return Promise.resolve(value).then(function (unwrapped) { return Promise.resolve(value).then(function (unwrapped) {
// When a yielded Promise is resolved, its final value becomes // When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the // the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the // current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same // result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not // reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case // thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in // when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it // behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded // allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back // rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With // into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the // await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the // rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and // only option is to throw it from the await expression, and
// let the generator function handle the exception. // let the generator function handle the exception.
result.value = unwrapped; result.value = unwrapped;
resolve(result); resolve(result);
}, reject); }, reject);
} }
} }
var previousPromise; var previousPromise;
function enqueue(method, arg) { function enqueue(method, arg) {
function callInvokeWithMethodAndArg() { function callInvokeWithMethodAndArg() {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
invoke(method, arg, resolve, reject); invoke(method, arg, resolve, reject);
}); });
} }
return previousPromise = return previousPromise =
// If enqueue has been called before, then we want to wait until // If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke, // all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If // so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to // enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire, // call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do // so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability // any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its // is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously // executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple // execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially // async functions in terms of async generators, it is especially
// important to get this right, even though it requires care. // important to get this right, even though it requires care.
previousPromise ? previousPromise.then( previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg, callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later // Avoid propagating failures to Promises returned by later
// invocations of the iterator. // invocations of the iterator.
callInvokeWithMethodAndArg callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg(); ) : callInvokeWithMethodAndArg();
} }
// Define the unified helper method that is used to implement .next, // Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods). // .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue; this._invoke = enqueue;
} }
defineIteratorMethods(AsyncIterator.prototype); defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () { AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this; return this;
}; };
runtime.AsyncIterator = AsyncIterator; runtime.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of // Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of // AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator. // the final result produced by the iterator.
runtime.async = function (innerFn, outerFn, self, tryLocsList) { runtime.async = function (innerFn, outerFn, self, tryLocsList) {
var iter = new AsyncIterator( var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList) wrap(innerFn, outerFn, self, tryLocsList)
); );
return runtime.isGeneratorFunction(outerFn) return runtime.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator. ? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function (result) { : iter.next().then(function (result) {
return result.done ? result.value : iter.next(); return result.done ? result.value : iter.next();
}); });
}; };
function makeInvokeMethod(innerFn, self, context) { function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart; var state = GenStateSuspendedStart;
return function invoke(method, arg) { return function invoke(method, arg) {
if (state === GenStateExecuting) { if (state === GenStateExecuting) {
throw new Error("Generator is already running"); throw new Error("Generator is already running");
} }
if (state === GenStateCompleted) { if (state === GenStateCompleted) {
if (method === "throw") { if (method === "throw") {
throw arg; throw arg;
} }
// Be forgiving, per 25.3.3.3.3 of the spec: // Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult(); return doneResult();
} }
context.method = method; context.method = method;
context.arg = arg; context.arg = arg;
while (true) { while (true) {
var delegate = context.delegate; var delegate = context.delegate;
if (delegate) { if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context); var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) { if (delegateResult) {
if (delegateResult === ContinueSentinel) continue; if (delegateResult === ContinueSentinel) continue;
return delegateResult; return delegateResult;
} }
} }
if (context.method === "next") { if (context.method === "next") {
// Setting context._sent for legacy support of Babel's // Setting context._sent for legacy support of Babel's
// function.sent implementation. // function.sent implementation.
context.sent = context._sent = context.arg; context.sent = context._sent = context.arg;
} else if (context.method === "throw") { } else if (context.method === "throw") {
if (state === GenStateSuspendedStart) { if (state === GenStateSuspendedStart) {
state = GenStateCompleted; state = GenStateCompleted;
throw context.arg; throw context.arg;
} }
context.dispatchException(context.arg); context.dispatchException(context.arg);
} else if (context.method === "return") { } else if (context.method === "return") {
context.abrupt("return", context.arg); context.abrupt("return", context.arg);
} }
state = GenStateExecuting; state = GenStateExecuting;
var record = tryCatch(innerFn, self, context); var record = tryCatch(innerFn, self, context);
if (record.type === "normal") { if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state === // If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation. // GenStateExecuting and loop back for another invocation.
state = context.done state = context.done
? GenStateCompleted ? GenStateCompleted
: GenStateSuspendedYield; : GenStateSuspendedYield;
if (record.arg === ContinueSentinel) { if (record.arg === ContinueSentinel) {
continue; continue;
} }
return { return {
value: record.arg, value: record.arg,
done: context.done done: context.done
}; };
} else if (record.type === "throw") { } else if (record.type === "throw") {
state = GenStateCompleted; state = GenStateCompleted;
// Dispatch the exception by looping back around to the // Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above. // context.dispatchException(context.arg) call above.
context.method = "throw"; context.method = "throw";
context.arg = record.arg; context.arg = record.arg;
} }
} }
}; };
} }
// Call delegate.iterator[context.method](context.arg) and handle the // Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the // result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg, // delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel. // setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) { function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method]; var method = delegate.iterator[context.method];
if (method === undefined) { if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw // A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop. // method always terminates the yield* loop.
context.delegate = null; context.delegate = null;
if (context.method === "throw") { if (context.method === "throw") {
if (delegate.iterator.return) { if (delegate.iterator.return) {
// If the delegate iterator has a return method, give it a // If the delegate iterator has a return method, give it a
// chance to clean up. // chance to clean up.
context.method = "return"; context.method = "return";
context.arg = undefined; context.arg = undefined;
maybeInvokeDelegate(delegate, context); maybeInvokeDelegate(delegate, context);
if (context.method === "throw") { if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from // If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below. // "return" to "throw", let that override the TypeError below.
return ContinueSentinel; return ContinueSentinel;
} }
} }
context.method = "throw"; context.method = "throw";
context.arg = new TypeError( context.arg = new TypeError(
"The iterator does not provide a 'throw' method"); "The iterator does not provide a 'throw' method");
} }
return ContinueSentinel; return ContinueSentinel;
} }
var record = tryCatch(method, delegate.iterator, context.arg); var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") { if (record.type === "throw") {
context.method = "throw"; context.method = "throw";
context.arg = record.arg; context.arg = record.arg;
context.delegate = null; context.delegate = null;
return ContinueSentinel; return ContinueSentinel;
} }
var info = record.arg; var info = record.arg;
if (!info) { if (!info) {
context.method = "throw"; context.method = "throw";
context.arg = new TypeError("iterator result is not an object"); context.arg = new TypeError("iterator result is not an object");
context.delegate = null; context.delegate = null;
return ContinueSentinel; return ContinueSentinel;
} }
if (info.done) { if (info.done) {
// Assign the result of the finished delegate to the temporary // Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield). // variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value; context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield). // Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc; context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the // If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If // exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been // context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was // "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the // "return", allow the original .return call to continue in the
// outer generator. // outer generator.
if (context.method !== "return") { if (context.method !== "return") {
context.method = "next"; context.method = "next";
context.arg = undefined; context.arg = undefined;
} }
} else { } else {
// Re-yield the result returned by the delegate method. // Re-yield the result returned by the delegate method.
return info; return info;
} }
// The delegate iterator is finished, so forget it and continue with // The delegate iterator is finished, so forget it and continue with
// the outer generator. // the outer generator.
context.delegate = null; context.delegate = null;
return ContinueSentinel; return ContinueSentinel;
} }
// Define Generator.prototype.{next,throw,return} in terms of the // Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method. // unified ._invoke helper method.
defineIteratorMethods(Gp); defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator"; Gp[toStringTagSymbol] = "Generator";
// A Generator should always return itself as the iterator object when the // A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the // @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator // iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen. // object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details. // See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function () { Gp[iteratorSymbol] = function () {
return this; return this;
}; };
Gp.toString = function () { Gp.toString = function () {
return "[object Generator]"; return "[object Generator]";
}; };
function pushTryEntry(locs) { function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] }; var entry = { tryLoc: locs[0] };
if (1 in locs) { if (1 in locs) {
entry.catchLoc = locs[1]; entry.catchLoc = locs[1];
} }
if (2 in locs) { if (2 in locs) {
entry.finallyLoc = locs[2]; entry.finallyLoc = locs[2];
entry.afterLoc = locs[3]; entry.afterLoc = locs[3];
} }
this.tryEntries.push(entry); this.tryEntries.push(entry);
} }
function resetTryEntry(entry) { function resetTryEntry(entry) {
var record = entry.completion || {}; var record = entry.completion || {};
record.type = "normal"; record.type = "normal";
delete record.arg; delete record.arg;
entry.completion = record; entry.completion = record;
} }
function Context(tryLocsList) { function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch // The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from // or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement. // locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }]; this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this); tryLocsList.forEach(pushTryEntry, this);
this.reset(true); this.reset(true);
} }
runtime.keys = function (object) { runtime.keys = function (object) {
var keys = []; var keys = [];
for (var key in object) { for (var key in object) {
keys.push(key); keys.push(key);
} }
keys.reverse(); keys.reverse();
// Rather than returning an object with a next method, we keep // Rather than returning an object with a next method, we keep
// things simple and return the next function itself. // things simple and return the next function itself.
return function next() { return function next() {
while (keys.length) { while (keys.length) {
var key = keys.pop(); var key = keys.pop();
if (key in object) { if (key in object) {
next.value = key; next.value = key;
next.done = false; next.done = false;
return next; return next;
} }
} }
// To avoid creating an additional object, we just hang the .value // To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This // and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function. // also ensures that the minifier will not anonymize the function.
next.done = true; next.done = true;
return next; return next;
}; };
}; };
function values(iterable) { function values(iterable) {
if (iterable) { if (iterable) {
var iteratorMethod = iterable[iteratorSymbol]; var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) { if (iteratorMethod) {
return iteratorMethod.call(iterable); return iteratorMethod.call(iterable);
} }
if (typeof iterable.next === "function") { if (typeof iterable.next === "function") {
return iterable; return iterable;
} }
if (!isNaN(iterable.length)) { if (!isNaN(iterable.length)) {
var i = -1, next = function next() { var i = -1, next = function next() {
while (++i < iterable.length) { while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) { if (hasOwn.call(iterable, i)) {
next.value = iterable[i]; next.value = iterable[i];
next.done = false; next.done = false;
return next; return next;
} }
} }
next.value = undefined; next.value = undefined;
next.done = true; next.done = true;
return next; return next;
}; };
return next.next = next; return next.next = next;
} }
} }
// Return an iterator with no values. // Return an iterator with no values.
return { next: doneResult }; return { next: doneResult };
} }
runtime.values = values; runtime.values = values;
function doneResult() { function doneResult() {
return { value: undefined, done: true }; return { value: undefined, done: true };
} }
Context.prototype = { Context.prototype = {
constructor: Context, constructor: Context,
reset: function (skipTempReset) { reset: function (skipTempReset) {
this.prev = 0; this.prev = 0;
this.next = 0; this.next = 0;
// Resetting context._sent for legacy support of Babel's // Resetting context._sent for legacy support of Babel's
// function.sent implementation. // function.sent implementation.
this.sent = this._sent = undefined; this.sent = this._sent = undefined;
this.done = false; this.done = false;
this.delegate = null; this.delegate = null;
this.method = "next"; this.method = "next";
this.arg = undefined; this.arg = undefined;
this.tryEntries.forEach(resetTryEntry); this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) { if (!skipTempReset) {
for (var name in this) { for (var name in this) {
// Not sure about the optimal order of these conditions: // Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" && if (name.charAt(0) === "t" &&
hasOwn.call(this, name) && hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) { !isNaN(+name.slice(1))) {
this[name] = undefined; this[name] = undefined;
} }
} }
} }
}, },
stop: function () { stop: function () {
this.done = true; this.done = true;
var rootEntry = this.tryEntries[0]; var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion; var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") { if (rootRecord.type === "throw") {
throw rootRecord.arg; throw rootRecord.arg;
} }
return this.rval; return this.rval;
}, },
dispatchException: function (exception) { dispatchException: function (exception) {
if (this.done) { if (this.done) {
throw exception; throw exception;
} }
var context = this; var context = this;
function handle(loc, caught) { function handle(loc, caught) {
record.type = "throw"; record.type = "throw";
record.arg = exception; record.arg = exception;
context.next = loc; context.next = loc;
if (caught) { if (caught) {
// If the dispatched exception was caught by a catch block, // If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally. // then let that catch block handle the exception normally.
context.method = "next"; context.method = "next";
context.arg = undefined; context.arg = undefined;
} }
return !!caught; return !!caught;
} }
for (var i = this.tryEntries.length - 1; i >= 0; --i) { for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i]; var entry = this.tryEntries[i];
var record = entry.completion; var record = entry.completion;
if (entry.tryLoc === "root") { if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle // Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to // it, so set the completion value of the entire function to
// throw the exception. // throw the exception.
return handle("end"); return handle("end");
} }
if (entry.tryLoc <= this.prev) { if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc"); var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) { if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) { if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true); return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) { } else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc); return handle(entry.finallyLoc);
} }
} else if (hasCatch) { } else if (hasCatch) {
if (this.prev < entry.catchLoc) { if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true); return handle(entry.catchLoc, true);
} }
} else if (hasFinally) { } else if (hasFinally) {
if (this.prev < entry.finallyLoc) { if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc); return handle(entry.finallyLoc);
} }
} else { } else {
throw new Error("try statement without catch or finally"); throw new Error("try statement without catch or finally");
} }
} }
} }
}, },
abrupt: function (type, arg) { abrupt: function (type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) { for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i]; var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") && hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) { this.prev < entry.finallyLoc) {
var finallyEntry = entry; var finallyEntry = entry;
break; break;
} }
} }
if (finallyEntry && if (finallyEntry &&
(type === "break" || (type === "break" ||
type === "continue") && type === "continue") &&
finallyEntry.tryLoc <= arg && finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) { arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a // Ignore the finally entry if control is not jumping to a
// location outside the try/catch block. // location outside the try/catch block.
finallyEntry = null; finallyEntry = null;
} }
var record = finallyEntry ? finallyEntry.completion : {}; var record = finallyEntry ? finallyEntry.completion : {};
record.type = type; record.type = type;
record.arg = arg; record.arg = arg;
if (finallyEntry) { if (finallyEntry) {
this.method = "next"; this.method = "next";
this.next = finallyEntry.finallyLoc; this.next = finallyEntry.finallyLoc;
return ContinueSentinel; return ContinueSentinel;
} }
return this.complete(record); return this.complete(record);
}, },
complete: function (record, afterLoc) { complete: function (record, afterLoc) {
if (record.type === "throw") { if (record.type === "throw") {
throw record.arg; throw record.arg;
} }
if (record.type === "break" || if (record.type === "break" ||
record.type === "continue") { record.type === "continue") {
this.next = record.arg; this.next = record.arg;
} else if (record.type === "return") { } else if (record.type === "return") {
this.rval = this.arg = record.arg; this.rval = this.arg = record.arg;
this.method = "return"; this.method = "return";
this.next = "end"; this.next = "end";
} else if (record.type === "normal" && afterLoc) { } else if (record.type === "normal" && afterLoc) {
this.next = afterLoc; this.next = afterLoc;
} }
return ContinueSentinel; return ContinueSentinel;
}, },
finish: function (finallyLoc) { finish: function (finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) { for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i]; var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) { if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc); this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry); resetTryEntry(entry);
return ContinueSentinel; return ContinueSentinel;
} }
} }
}, },
"catch": function (tryLoc) { "catch": function (tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) { for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i]; var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) { if (entry.tryLoc === tryLoc) {
var record = entry.completion; var record = entry.completion;
if (record.type === "throw") { if (record.type === "throw") {
var thrown = record.arg; var thrown = record.arg;
resetTryEntry(entry); resetTryEntry(entry);
} }
return thrown; return thrown;
} }
} }
// The context.catch method must only be called with a location // The context.catch method must only be called with a location
// argument that corresponds to a known catch block. // argument that corresponds to a known catch block.
throw new Error("illegal catch attempt"); throw new Error("illegal catch attempt");
}, },
delegateYield: function (iterable, resultName, nextLoc) { delegateYield: function (iterable, resultName, nextLoc) {
this.delegate = { this.delegate = {
iterator: values(iterable), iterator: values(iterable),
resultName: resultName, resultName: resultName,
nextLoc: nextLoc nextLoc: nextLoc
}; };
if (this.method === "next") { if (this.method === "next") {
// Deliberately forget the last sent value so that we don't // Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate. // accidentally pass it on to the delegate.
this.arg = undefined; this.arg = undefined;
} }
return ContinueSentinel; return ContinueSentinel;
} }
}; };
})( })(
// In sloppy mode, unbound `this` refers to the global object, fallback to // In sloppy mode, unbound `this` refers to the global object, fallback to
// Function constructor if we're in global strict mode. That is sadly a form // Function constructor if we're in global strict mode. That is sadly a form
// of indirect eval which violates Content Security Policy. // of indirect eval which violates Content Security Policy.
(function () { return this })() || Function("return this")() (function () { return this })() || Function("return this")()
); );
export function getPosByAngle(angle, len) { export function getPosByAngle(angle, len) {
const radian = angle * Math.PI / 180; const radian = angle * Math.PI / 180;
const x = Math.sin(radian) * len; const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len; const y = Math.cos(radian) * len;
return { x, y }; return { x, y };
} }
export function getAngleByPos(px, py, mx, my) { export function getAngleByPos(px, py, mx, my) {
const x = Math.abs(px - mx); const x = Math.abs(px - mx);
const y = Math.abs(py - my); const y = Math.abs(py - my);
const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
const cos = y / z; const cos = y / z;
const radina = Math.acos(cos); // 用反三角函数求弧度 const radina = Math.acos(cos); // 用反三角函数求弧度
let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度 let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度
if (mx > px && my > py) {// 鼠标在第四象限 if (mx > px && my > py) {// 鼠标在第四象限
angle = 180 - angle; angle = 180 - angle;
} }
if (mx === px && my > py) {// 鼠标在y轴负方向上 if (mx === px && my > py) {// 鼠标在y轴负方向上
angle = 180; angle = 180;
} }
if (mx > px && my === py) {// 鼠标在x轴正方向上 if (mx > px && my === py) {// 鼠标在x轴正方向上
angle = 90; angle = 90;
} }
if (mx < px && my > py) {// 鼠标在第三象限 if (mx < px && my > py) {// 鼠标在第三象限
angle = 180 + angle; angle = 180 + angle;
} }
if (mx < px && my === py) {// 鼠标在x轴负方向 if (mx < px && my === py) {// 鼠标在x轴负方向
angle = 270; angle = 270;
} }
if (mx < px && my < py) {// 鼠标在第二象限 if (mx < px && my < py) {// 鼠标在第二象限
angle = 360 - angle; angle = 360 - angle;
} }
// console.log('angle: ', angle); // console.log('angle: ', angle);
return angle; return angle;
} }
export function exchangeNodePos(baseNode, targetNode) { export function exchangeNodePos(baseNode, targetNode) {
return baseNode.convertToNodeSpaceAR(targetNode._parent.convertToWorldSpaceAR(cc.v2(targetNode.x, targetNode.y))); return baseNode.convertToNodeSpaceAR(targetNode._parent.convertToWorldSpaceAR(cc.v2(targetNode.x, targetNode.y)));
} }
export function RandomInt(a, b = 0) { export function RandomInt(a, b = 0) {
let max = Math.max(a, b); let max = Math.max(a, b);
let min = Math.min(a, b); let min = Math.min(a, b);
return Math.floor(Math.random() * (max - min) + min); return Math.floor(Math.random() * (max - min) + min);
} }
export function randomSortByArr(arr) { export function randomSortByArr(arr) {
const newArr = []; const newArr = [];
const tmpArr = arr.concat(); const tmpArr = arr.concat();
while (tmpArr.length > 0) { while (tmpArr.length > 0) {
const randomIndex = Math.floor(tmpArr.length * Math.random()); const randomIndex = Math.floor(tmpArr.length * Math.random());
newArr.push(tmpArr[randomIndex]); newArr.push(tmpArr[randomIndex]);
tmpArr.splice(randomIndex, 1); tmpArr.splice(randomIndex, 1);
} }
return newArr; return newArr;
} }
export function setSprNodeMaxLen(sprNode, maxW, maxH) { export function setSprNodeMaxLen(sprNode, maxW, maxH) {
const sx = maxW / sprNode.width; const sx = maxW / sprNode.width;
const sy = maxH / sprNode.height; const sy = maxH / sprNode.height;
const s = Math.min(sx, sy); const s = Math.min(sx, sy);
sprNode.scale = Math.round(s * 1000) / 1000; sprNode.scale = Math.round(s * 1000) / 1000;
} }
export function localPosTolocalPos(baseNode, targetNode) { export function localPosTolocalPos(baseNode, targetNode) {
const worldPos = targetNode.parent.convertToWorldSpaceAR(cc.v2(targetNode.x, targetNode.y)); const worldPos = targetNode.parent.convertToWorldSpaceAR(cc.v2(targetNode.x, targetNode.y));
const localPos = baseNode.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y)); const localPos = baseNode.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
return localPos; return localPos;
} }
export function worldPosToLocalPos(worldPos, baseNode) { export function worldPosToLocalPos(worldPos, baseNode) {
const localPos = baseNode.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y)); const localPos = baseNode.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
return localPos; return localPos;
} }
export function getScaleRateBy2Node(baseNode, targetNode, maxFlag = true) { export function getScaleRateBy2Node(baseNode, targetNode, maxFlag = true) {
const worldRect1 = targetNode.getBoundingBoxToWorld(); const worldRect1 = targetNode.getBoundingBoxToWorld();
const worldRect2 = baseNode.getBoundingBoxToWorld(); const worldRect2 = baseNode.getBoundingBoxToWorld();
const sx = worldRect1.width / worldRect2.width; const sx = worldRect1.width / worldRect2.width;
const sy = worldRect1.height / worldRect2.height; const sy = worldRect1.height / worldRect2.height;
if (maxFlag) { if (maxFlag) {
return Math.max(sx, sy); return Math.max(sx, sy);
} else { } else {
return Math.min(sx, sy); return Math.min(sx, sy);
} }
} }
export function getDistance (start, end){ export function getDistance (start, end){
var pos = cc.v2(start.x - end.x, start.y - end.y); var pos = cc.v2(start.x - end.x, start.y - end.y);
var dis = Math.sqrt(pos.x*pos.x + pos.y*pos.y); var dis = Math.sqrt(pos.x*pos.x + pos.y*pos.y);
return dis; return dis;
} }
export function playAudioByUrl(audio_url, cb=null) { export function playAudioByUrl(audio_url, cb=null) {
if (audio_url) { if (audio_url) {
cc.assetManager.loadRemote(audio_url, (err, audioClip) => { cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
const audioId = cc.audioEngine.play(audioClip, false, 0.8); const audioId = cc.audioEngine.play(audioClip, false, 0.8);
if (cb) { if (cb) {
cc.audioEngine.setFinishCallback(audioId, () => { cc.audioEngine.setFinishCallback(audioId, () => {
cb(); cb();
}); });
} }
}); });
} }
} }
export function btnClickAnima(btn, time=0.15, rate=1.05) { export function btnClickAnima(btn, time=0.15, rate=1.05) {
btn.tmpScale = btn.scale; btn.tmpScale = btn.scale;
btn.on(cc.Node.EventType.TOUCH_START, () => { btn.on(cc.Node.EventType.TOUCH_START, () => {
cc.tween(btn) cc.tween(btn)
.to(time / 2, {scale: btn.scale * rate}) .to(time / 2, {scale: btn.scale * rate})
.start() .start()
}) })
btn.on(cc.Node.EventType.TOUCH_CANCEL, () => { btn.on(cc.Node.EventType.TOUCH_CANCEL, () => {
cc.tween(btn) cc.tween(btn)
.to(time / 2, {scale: btn.tmpScale}) .to(time / 2, {scale: btn.tmpScale})
.start() .start()
}) })
btn.on(cc.Node.EventType.TOUCH_END, () => { btn.on(cc.Node.EventType.TOUCH_END, () => {
cc.tween(btn) cc.tween(btn)
.to(time / 2, {scale: btn.tmpScale}) .to(time / 2, {scale: btn.tmpScale})
.start() .start()
}) })
} }
export function getSpriteFrimeByUrl(url, cb) { export function getSpriteFrimeByUrl(url, cb) {
cc.loader.load({ url }, (err, img) => { cc.loader.load({ url }, (err, img) => {
const spriteFrame = new cc.SpriteFrame(img) const spriteFrame = new cc.SpriteFrame(img)
if (cb) { if (cb) {
cb(spriteFrame); cb(spriteFrame);
} }
}) })
} }
export function getSprNode(resName) { export function getSprNode(resName) {
const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame; const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
const node = new cc.Node(); const node = new cc.Node();
node.addComponent(cc.Sprite).spriteFrame = sf; node.addComponent(cc.Sprite).spriteFrame = sf;
return node; return node;
} }
export function getSprNodeByUrl(url, cb) { export function getSprNodeByUrl(url, cb) {
const node = new cc.Node(); const node = new cc.Node();
const spr = node.addComponent(cc.Sprite); const spr = node.addComponent(cc.Sprite);
getSpriteFrimeByUrl(url, (sf) => { getSpriteFrimeByUrl(url, (sf) => {
spr.spriteFrame = sf; spr.spriteFrame = sf;
if (cb) { if (cb) {
cb(spr); cb(spr);
} }
}) })
} }
export function playAudio(audioClip, cb = null) { export function playAudio(audioClip, cb = null) {
if (audioClip) { if (audioClip) {
const audioId = cc.audioEngine.playEffect(audioClip, false, 0.8); const audioId = cc.audioEngine.playEffect(audioClip, false, 0.8);
if (cb) { if (cb) {
cc.audioEngine.setFinishCallback(audioId, () => { cc.audioEngine.setFinishCallback(audioId, () => {
cb(); cb();
}); });
} }
} }
} }
export async function asyncDelay(time) { export async function asyncDelay(time) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try { try {
setTimeout(() => { setTimeout(() => {
resolve(); resolve();
}, time * 1000); }, time * 1000);
} catch (e) { } catch (e) {
reject(e); reject(e);
} }
}) })
} }
export class FireworkSettings { export class FireworkSettings {
baseNode; // 父节点 baseNode; // 父节点
nodeList; // 火花节点的array nodeList; // 火花节点的array
pos; // 发射点 pos; // 发射点
side; // 发射方向 side; // 发射方向
range; // 扩散范围 range; // 扩散范围
number; // 发射数量 number; // 发射数量
scalseRange; // 缩放范围 scalseRange; // 缩放范围
constructor(baseNode, nodeList, constructor(baseNode, nodeList,
pos = cc.v2(0, 0), pos = cc.v2(0, 0),
side = cc.v2(0, 100), side = cc.v2(0, 100),
range = 50, range = 50,
number = 100, number = 100,
scalseRange = 0 scalseRange = 0
) { ) {
this.baseNode = baseNode; this.baseNode = baseNode;
this.nodeList = nodeList; this.nodeList = nodeList;
this.pos = pos; this.pos = pos;
this.side = side; this.side = side;
this.range = range; this.range = range;
this.number = number; this.number = number;
this.scalseRange = scalseRange; this.scalseRange = scalseRange;
} }
static copy(firework) { static copy(firework) {
return new FireworkSettings( return new FireworkSettings(
firework.baseNode, firework.baseNode,
firework.nodeList, firework.nodeList,
firework.pos, firework.pos,
firework.side, firework.side,
firework.range, firework.range,
firework.number, firework.number,
); );
} }
} }
export async function showFireworks(fireworkSettings) { export async function showFireworks(fireworkSettings) {
const { baseNode, nodeList, pos, side, range, number, scalseRange } = fireworkSettings; const { baseNode, nodeList, pos, side, range, number, scalseRange } = fireworkSettings;
new Array(number).fill(' ').forEach(async (_, i) => { new Array(number).fill(' ').forEach(async (_, i) => {
let rabbonNode = new cc.Node(); let rabbonNode = new cc.Node();
rabbonNode.parent = baseNode; rabbonNode.parent = baseNode;
rabbonNode.x = pos.x; rabbonNode.x = pos.x;
rabbonNode.y = pos.y; rabbonNode.y = pos.y;
rabbonNode.angle = 60 * Math.random() - 30; rabbonNode.angle = 60 * Math.random() - 30;
let node = cc.instantiate(nodeList[RandomInt(nodeList.length)]); let node = cc.instantiate(nodeList[RandomInt(nodeList.length)]);
node.parent = rabbonNode; node.parent = rabbonNode;
node.active = true; node.active = true;
node.x = 0; node.x = 0;
node.y = 0; node.y = 0;
node.angle = 0; node.angle = 0;
node.scale = (Math.random() - 0.5) * scalseRange + 1; node.scale = (Math.random() - 0.5) * scalseRange + 1;
const rate = Math.random(); const rate = Math.random();
const angle = Math.PI * (Math.random() * 2 - 1); const angle = Math.PI * (Math.random() * 2 - 1);
await asyncTweenBy(rabbonNode, 0.3, { await asyncTweenBy(rabbonNode, 0.3, {
x: side.x * rate + Math.cos(angle) * range * rate, x: side.x * rate + Math.cos(angle) * range * rate,
y: side.y * rate + Math.sin(angle) * range * rate y: side.y * rate + Math.sin(angle) * range * rate
}, { }, {
easing: 'quadIn' easing: 'quadIn'
}); });
cc.tween(rabbonNode) cc.tween(rabbonNode)
.by(8, { y: -2000 }) .by(8, { y: -2000 })
.start(); .start();
cc.tween(rabbonNode) cc.tween(rabbonNode)
.to(5, { scale: (Math.random() - 0.5) * scalseRange + 1 }) .to(5, { scale: (Math.random() - 0.5) * scalseRange + 1 })
.start(); .start();
rabbonFall(rabbonNode); rabbonFall(rabbonNode);
await asyncDelay(Math.random()); await asyncDelay(Math.random());
cc.tween(node) cc.tween(node)
.by(0.15, { x: -10, angle: -10 }) .by(0.15, { x: -10, angle: -10 })
.by(0.3, { x: 20, angle: 20 }) .by(0.3, { x: 20, angle: 20 })
.by(0.15, { x: -10, angle: -10 }) .by(0.15, { x: -10, angle: -10 })
.union() .union()
.repeatForever() .repeatForever()
.start(); .start();
cc.tween(rabbonNode) cc.tween(rabbonNode)
.delay(5) .delay(5)
.to(0.3, { opacity: 0 }) .to(0.3, { opacity: 0 })
.call(() => { .call(() => {
node.stopAllActions(); node.stopAllActions();
node.active = false; node.active = false;
node.parent = null; node.parent = null;
node = null; node = null;
}) })
.start(); .start();
}); });
} }
async function rabbonFall(node) { async function rabbonFall(node) {
const time = 1 + Math.random(); const time = 1 + Math.random();
const offsetX = RandomInt(-200, 200) * time; const offsetX = RandomInt(-200, 200) * time;
await asyncTweenBy(node, time, { x: offsetX, angle: offsetX * 60 / 200 }); await asyncTweenBy(node, time, { x: offsetX, angle: offsetX * 60 / 200 });
rabbonFall(node); rabbonFall(node);
} }
export async function asyncTweenTo(node, duration, obj, ease = undefined) { export async function asyncTweenTo(node, duration, obj, ease = undefined) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try { try {
cc.tween(node) cc.tween(node)
.to(duration, obj, ease) .to(duration, obj, ease)
.call(() => { .call(() => {
resolve(); resolve();
}) })
.start(); .start();
} catch (e) { } catch (e) {
reject(e); reject(e);
} }
}); });
} }
export async function asyncTweenBy(node, duration, obj, ease = undefined) { export async function asyncTweenBy(node, duration, obj, ease = undefined) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try { try {
cc.tween(node) cc.tween(node)
.by(duration, obj, ease) .by(duration, obj, ease)
.call(() => { .call(() => {
resolve(); resolve();
}) })
.start(); .start();
} catch (e) { } catch (e) {
reject(e); reject(e);
} }
}); });
} }
export function showTrebleFirework(baseNode, rabbonList) { export function showTrebleFirework(baseNode, rabbonList) {
const middle = new FireworkSettings(baseNode, rabbonList); const middle = new FireworkSettings(baseNode, rabbonList);
middle.pos = cc.v2(0, -400); middle.pos = cc.v2(0, -400);
middle.side = cc.v2(0, 1000); middle.side = cc.v2(0, 1000);
middle.range = 200; middle.range = 200;
middle.number = 100; middle.number = 100;
middle.scalseRange = 0.4; middle.scalseRange = 0.4;
const left = FireworkSettings.copy(middle); const left = FireworkSettings.copy(middle);
left.pos = cc.v2(-600, -400); left.pos = cc.v2(-600, -400);
left.side = cc.v2(200, 1000); left.side = cc.v2(200, 1000);
const right = FireworkSettings.copy(middle); const right = FireworkSettings.copy(middle);
right.pos = cc.v2(600, -400); right.pos = cc.v2(600, -400);
right.side = cc.v2(-200, 1000); right.side = cc.v2(-200, 1000);
showFireworks(middle); showFireworks(middle);
showFireworks(left); showFireworks(left);
showFireworks(right); showFireworks(right);
} }
export function onHomeworkFinish() { export function onHomeworkFinish() {
const middleLayer = cc.find('middleLayer'); const middleLayer = cc.find('middleLayer');
if (middleLayer) { if (middleLayer) {
const middleLayerComponent = middleLayer.getComponent('middleLayer'); const middleLayerComponent = middleLayer.getComponent('middleLayer');
if (middleLayerComponent.role == 'student') { if (middleLayerComponent.role == 'student') {
middleLayerComponent.onHomeworkFinish(() => { }); middleLayerComponent.onHomeworkFinish(() => { });
} }
} else { } else {
console.log('onHomeworkFinish'); console.log('onHomeworkFinish');
} }
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment