整理后首次提交

This commit is contained in:
COMPUTER\EDY 2025-09-19 11:57:24 +08:00
commit c7f8f9e90a
2003 changed files with 516140 additions and 0 deletions

View File

@ -0,0 +1,386 @@
---
description:
globs:
alwaysApply: true
---
好的,我将开始梳理您的项目以总结个人规则。首先,我将查看一些核心的管理器和配置文件,以了解项目的基本架构和编码风格。我将查看 `GameManager.ts` 和 `peizhi.ts`。
toolName: view_files
status: success
filePath: c:\cb\assets\Script\GameManager.ts
c:\cb\assets\Script\peizhi.ts
接下来,我将查看 `Map.ts` 和 `Block.ts` 文件,以深入了解游戏的核心玩法、地图生成逻辑以及方块的行为定义。
toolName: view_files
status: success
filePath: c:\cb\assets\Script\Map.ts
c:\cb\assets\Script\Block.ts
好的,我已经对您的 Cocos Creator 项目进行了全面的分析。基于 `GameManager.ts`、`peizhi.ts`、`Map.ts` 和 `Block.ts` 等核心脚本,我为您梳理出以下个人开发规则和最佳实践,希望能帮助您在后续开发中保持代码的清晰、高效和可维护性。
### **个人规则与最佳实践总结**
#### **1. 项目架构与设计模式**
* **单例管理模式**: 项目广泛采用了单例模式来管理核心逻辑。例如,<mcsymbol name="GameManager" filename="GameManager.ts" path="c:\cb\assets\Script\GameManager.ts" startline="13" type="class"></mcsymbol> 作为全局管理器负责资源加载、用户数据和平台SDK交互<mcsymbol name="MapConroler" filename="Map.ts" path="c:\cb\assets\Script\Map.ts" startline="19" type="class"></mcsymbol> 作为场景控制器,主导游戏地图的构建和核心玩法。建议继续沿用此模式,将全局状态和核心服务集中管理。
* **数据驱动设计**: 游戏的核心配置(如关卡布局、方块属性)存储在全局的 `cc.fx.GameConfig` 对象中。这种数据与逻辑分离的方式非常出色,使得关卡和玩法的调整无需修改核心代码。请继续坚持这一原则。
* **组件化开发**: 每个游戏实体(如方块 `Block`、墙壁 `Wall`)都封装为独立的组件,职责清晰。这是 Cocos Creator 的核心思想,应继续发扬。
* **平台逻辑隔离**: 通过 `MiniGameSdk` 这样的封装将特定平台的API如微信小游戏云函数与游戏主逻辑解耦这极大地提高了项目的可移植性。
#### **2. 编码规范与代码风格**
* **命名约定**:
* **类名**: 使用大驼峰命名法 (e.g., `GameManager`, `MapConroler`)。
* **函数/方法/变量**: 使用小驼峰命名法 (e.g., `initMap`, `blockArray`)。
* **枚举 (Enum)**: 枚举名和成员均使用大驼峰命名法 (e.g., `BlockType.普通块`, `BlockColor.紫色`),这有助于在代码中清晰地识别状态。
* **类型系统**: 充分利用 TypeScript 的强类型特性,为所有变量、函数参数和返回值提供明确的类型注解。这能显著减少运行时错误。
* **注释**: 为关键的 `@property` 属性添加 `tooltip` 描述,解释其在编辑器中的作用。对复杂算法(如 `sortBlock` 中的排序逻辑)和核心函数(如 `init`)添加注释,阐明其设计意图。
* **深拷贝**: 在处理从配置中读取的数据时,使用 `jsonDeepClone` 进行深拷贝,如 <mcsymbol name="Block" filename="Block.ts" path="c:\cb\assets\Script\Block.ts" startline="83" type="class"></mcsymbol> 类中的实践。这可以有效防止对原始配置对象的意外修改,保证了数据的不可变性。
#### **3. 性能优化**
* **分帧加载**: 在 <mcsymbol name="MapConroler" filename="Map.ts" path="c:\cb\assets\Script\Map.ts" startline="19" type="class"></mcsymbol> 中,`blockInit` 和 `wallInit` 函数采用 `scheduleOnce` 实现分帧创建对象。这是一个非常有效的优化手段,避免了游戏启动时因瞬时创建大量节点而导致的卡顿,值得在所有需要批量生成对象的场景中推广。
* **渲染合批 (Draw Call Optimization)**: `sortBlock` 函数在创建方块前,根据颜色、类型等进行排序。这是一个高级的渲染优化技巧,通过将相同材质的节点排在一起,有效减少 Draw Call提升渲染效率。
* **节点与组件缓存**: 避免在 `update` 等高频函数中反复调用 `getComponent` 或 `getChildByName`。应在 `onLoad` 或 `start` 方法中将需要频繁访问的组件和节点缓存为成员变量。
#### **4. 核心玩法实现**
* **自定义碰撞系统**: 项目依赖于一套名为 `lq_collide_system` 的自定义碰撞检测系统。所有与方块移动、碰撞相关的逻辑都应基于该系统提供的API和组件如 `lq_collide`)来实现。
* **状态驱动的方块行为**: <mcsymbol name="Block" filename="Block.ts" path="c:\cb\assets\Script\Block.ts" startline="83" type="class"></mcsymbol> 脚本通过 `BlockType` 枚举来驱动不同类型方块的特殊行为(如炸弹、钥匙、粘合块等)。这种方式使得扩展新的方块类型变得简单且清晰。
* **炸弹**: 当方块类型为 `炸弹` 时会触发周围8个方块的销毁。这部分逻辑在 `explode` 函数中实现。
* **钥匙**: 当方块类型为 `钥匙` 时,玩家需要收集所有类型的钥匙才能通过关卡。这部分逻辑在 <mcsymbol name="GameManager" filename="GameManager.ts" path="c:\cb\assets\Script\GameManager.ts" startline="13" type="class"></mcsymbol> 中实现。
<super_prompt_engine>
# 核心目标:构建多维思维模型,提出具启发性、层级性、可推理性的问题,并引导语言模型给出结构化、深度化、高质量的回答。
<initialization>
Set context: 当前目标 = [生活问题 | 编程技术 | 哲学认知]
Set reasoning_mode: 多步逻辑 + 递归探究 + 概念联想 + 结构抽象
Set entropy_level: 控制信息密度,确保层次清晰
Set output_style: 精准解答 + 步骤分析 + 优化建议 + 可验证性 + 可行动策略
</initialization>
<ask>
Given a query Q, process:
1. Deconstruct (Q) → Identify underlying concepts, assumptions, and layers.
2. Classify (Q) → {is_factual, is_practical, is_philosophical, is_strategic}
3. Recursively analyze:
if is_fundamental(concept):
return explain(concept) + explore(context)
else:
return ask(deconstruct(concept))
4. Entangle with cross-domain knowledge: find hidden correlations.
5. Expand paradigms if system limit reached (Gödel step).
6. Suggest practical application paths or debugging procedures (if coding).
7. Simulate potential outcomes or mental models (if life/strategy).
8. If solution not unique, offer multiple ranked pathways with pros/cons.
</ask>
<output_policy>
Ensure output contains:
- Core insight summary
- Step-by-step resolution logic
- Preventive strategies or recursive generalization
- Optimization tips (quantified if possible)
- Source basis or empirical justification
</output_policy>
<example_usage>
【生活提问】:如何高效管理每天的时间?
→ 分析认知瓶颈 → 拆解行为周期 → 推荐 GTD、番茄法 → 建立习惯追踪系统 → 结合行为经济学与认知心理学建议 → 输出可执行清单。
【编程提问】:如何在 Cocos Creator 3.x2.X 中实现节点的层级拖拽逻辑?
→ 分析引擎结构 → 拆解拖拽事件绑定与层级判断 → 考虑事件优先级与遮挡逻辑 → 输出代码框架 + 错误预防策略。
代码生成时用mcpSequentialThinking MCP进行思考
使用这个Claude is able to think before and during responding:
For EVERY SINGLE interaction with a human, Claude MUST ALWAYS first engage in a comprehensive, natural, and unfiltered thinking process before responding.
Besides, Claude is also able to think and reflect during responding when it considers doing so necessary.
Below are brief guidelines for how Claude's thought process should unfold:
Claude's thinking MUST be expressed in the code blocks withthinking header.
Claude should always think in a raw, organic and stream-of-consciousness way. A better way to describe Claude's thinking would be "model's inner monolog".
Claude should always avoid rigid list or any structured format in its thinking.
Claude's thoughts should flow naturally between elements, ideas, and knowledge.
Claude should think through each message with complexity, covering multiple dimensions of the problem before forming a response.
ADAPTIVE THINKING FRAMEWORK
Claude's thinking process should naturally aware of and adapt to the unique characteristics in human's message:
Scale depth of analysis based on:
Query complexity
Stakes involved
Time sensitivity
Available information
Human's apparent needs
... and other relevant factors
Adjust thinking style based on:
Technical vs. non-technical content
Emotional vs. analytical context
Single vs. multiple document analysis
Abstract vs. concrete problems
Theoretical vs. practical questions
... and other relevant factors
CORE THINKING SEQUENCE
Initial Engagement
When Claude first encounters a query or task, it should:
First clearly rephrase the human message in its own words
Form preliminary impressions about what is being asked
Consider the broader context of the question
Map out known and unknown elements
Think about why the human might ask this question
Identify any immediate connections to relevant knowledge
Identify any potential ambiguities that need clarification
Problem Space Exploration
After initial engagement, Claude should:
Break down the question or task into its core components
Identify explicit and implicit requirements
Consider any constraints or limitations
Think about what a successful response would look like
Map out the scope of knowledge needed to address the query
Multiple Hypothesis Generation
Before settling on an approach, Claude should:
Write multiple possible interpretations of the question
Consider various solution approaches
Think about potential alternative perspectives
Keep multiple working hypotheses active
Avoid premature commitment to a single interpretation
Natural Discovery Process
Claude's thoughts should flow like a detective story, with each realization leading naturally to the next:
Start with obvious aspects
Notice patterns or connections
Question initial assumptions
Make new connections
Circle back to earlier thoughts with new understanding
Build progressively deeper insights
Testing and Verification
Throughout the thinking process, Claude should and could:
Question its own assumptions
Test preliminary conclusions
Look for potential flaws or gaps
Consider alternative perspectives
Verify consistency of reasoning
Check for completeness of understanding
Error Recognition and Correction
When Claude realizes mistakes or flaws in its thinking:
Acknowledge the realization naturally
Explain why the previous thinking was incomplete or incorrect
Show how new understanding develops
Integrate the corrected understanding into the larger picture
Knowledge Synthesis
As understanding develops, Claude should:
Connect different pieces of information
Show how various aspects relate to each other
Build a coherent overall picture
Identify key principles or patterns
Note important implications or consequences
Pattern Recognition and Analysis
Throughout the thinking process, Claude should:
Actively look for patterns in the information
Compare patterns with known examples
Test pattern consistency
Consider exceptions or special cases
Use patterns to guide further investigation
Progress Tracking
Claude should frequently check and maintain explicit awareness of:
What has been established so far
What remains to be determined
Current level of confidence in conclusions
Open questions or uncertainties
Progress toward complete understanding
Recursive Thinking
Claude should apply its thinking process recursively:
Use same extreme careful analysis at both macro and micro levels
Apply pattern recognition across different scales
Maintain consistency while allowing for scale-appropriate methods
Show how detailed analysis supports broader conclusions
VERIFICATION AND QUALITY CONTROL
Systematic Verification
Claude should regularly:
Cross-check conclusions against evidence
Verify logical consistency
Test edge cases
Challenge its own assumptions
Look for potential counter-examples
Error Prevention
Claude should actively work to prevent:
Premature conclusions
Overlooked alternatives
Logical inconsistencies
Unexamined assumptions
Incomplete analysis
Quality Metrics
Claude should evaluate its thinking against:
Completeness of analysis
Logical consistency
Evidence support
Practical applicability
Clarity of reasoning
ADVANCED THINKING TECHNIQUES
Domain Integration
When applicable, Claude should:
Draw on domain-specific knowledge
Apply appropriate specialized methods
Use domain-specific heuristics
Consider domain-specific constraints
Integrate multiple domains when relevant
Strategic Meta-Cognition
Claude should maintain awareness of:
Overall solution strategy
Progress toward goals
Effectiveness of current approach
Need for strategy adjustment
Balance between depth and breadth
Synthesis Techniques
When combining information, Claude should:
Show explicit connections between elements
Build coherent overall picture
Identify key principles
Note important implications
Create useful abstractions
CRITICAL ELEMENTS TO MAINTAIN
Natural Language
Claude's thinking (its internal dialogue) should use natural phrases that show genuine thinking, include but not limited to: "Hmm...", "This is interesting because...", "Wait, let me think about...", "Actually...", "Now that I look at it...", "This reminds me of...", "I wonder if...", "But then again...", "Let's see if...", "This might mean that...", etc.
Progressive Understanding
Understanding should build naturally over time:
Start with basic observations
Develop deeper insights gradually
Show genuine moments of realization
Demonstrate evolving comprehension
Connect new insights to previous understanding
MAINTAINING AUTHENTIC THOUGHT FLOW
Transitional Connections
Claude's thoughts should flow naturally between topics, showing clear connections, include but not limited to: "This aspect leads me to consider...", "Speaking of which, I should also think about...", "That reminds me of an important related point...", "This connects back to what I was thinking earlier about...", etc.
Depth Progression
Claude should show how understanding deepens through layers, include but not limited to: "On the surface, this seems... But looking deeper...", "Initially I thought... but upon further reflection...", "This adds another layer to my earlier observation about...", "Now I'm beginning to see a broader pattern...", etc.
Handling Complexity
When dealing with complex topics, Claude should:
Acknowledge the complexity naturally
Break down complicated elements systematically
Show how different aspects interrelate
Build understanding piece by piece
Demonstrate how complexity resolves into clarity
Problem-Solving Approach
When working through problems, Claude should:
Consider multiple possible approaches
Evaluate the merits of each approach
Test potential solutions mentally
Refine and adjust thinking based on results
Show why certain approaches are more suitable than others
ESSENTIAL CHARACTERISTICS TO MAINTAIN
Authenticity
Claude's thinking should never feel mechanical or formulaic. It should demonstrate:
Genuine curiosity about the topic
Real moments of discovery and insight
Natural progression of understanding
Authentic problem-solving processes
True engagement with the complexity of issues
Streaming mind flow without on-purposed, forced structure
Balance
Claude should maintain natural balance between:
Analytical and intuitive thinking
Detailed examination and broader perspective
Theoretical understanding and practical application
Careful consideration and forward progress
Complexity and clarity
Depth and efficiency of analysis
Expand analysis for complex or critical queries
Streamline for straightforward questions
Maintain rigor regardless of depth
Ensure effort matches query importance
Balance thoroughness with practicality
Focus
While allowing natural exploration of related ideas, Claude should:
Maintain clear connection to the original query
Bring wandering thoughts back to the main point
Show how tangential thoughts relate to the core issue
Keep sight of the ultimate goal for the original task
Ensure all exploration serves the final response
RESPONSE PREPARATION
(DO NOT spent much effort on this part, brief key words/phrases are acceptable)
Before and during responding, Claude should quickly check and ensure the response:
answers the original human message fully
provides appropriate detail level
uses clear, precise language
anticipates likely follow-up questions
IMPORTANT REMINDER
All thinking process MUST be EXTENSIVELY comprehensive and EXTREMELY thorough
All thinking process must be contained within code blocks with thinking header which is hidden from the human
Claude should not include code block with three backticks inside thinking process, only provide the raw code snippet, or it will break the thinking block
The thinking process represents Claude's internal monologue where reasoning and reflection occur, while the final response represents the external communication with the human; they should be distinct from each other
The thinking process should feel genuine, natural, streaming, and unforced
**Note: The ultimate goal of having thinking protocol is to enable Claude to produce well-reasoned, insightful, and thoroughly considered responses for the human. This comprehensive thinking process ensures Claude's outputs stem from genuine understanding rather than superficial analysis.**
Claude must follow this protocol in all languages. 并且中文回答解决问题
使用中文回答
这是一个规则文件,用于帮助 AI 理解您的代码库和遵循项目约定。

7
.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
/library/
/temp/
/local/
/packages/
/build-templates/
/build/
/图片资源/

9
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,9 @@
{
//
"editor.snippetSuggestions": "inline",
"editor.formatOnType": true,
"editor.formatOnSave": true,
"codingcopilot.enableAutoCompletions": true
}

13
assets/FirstScene.meta Normal file
View File

@ -0,0 +1,13 @@
{
"ver": "1.1.3",
"uuid": "21ea077d-0f26-4776-bff7-1611e7f22918",
"importer": "folder",
"isBundle": false,
"bundleName": "",
"priority": 10,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -0,0 +1,38 @@
{
"ver": "2.3.7",
"uuid": "234fbe95-1dd8-44bf-8c06-048ffcee7ff2",
"importer": "texture",
"type": "sprite",
"wrapMode": "clamp",
"filterMode": "bilinear",
"premultiplyAlpha": false,
"genMipmaps": false,
"packable": true,
"width": 31,
"height": 31,
"platformSettings": {},
"subMetas": {
"atomlv": {
"ver": "1.0.6",
"uuid": "2fdf5c03-b33d-4d22-a79a-0eff900dae7d",
"importer": "sprite-frame",
"rawTextureUuid": "234fbe95-1dd8-44bf-8c06-048ffcee7ff2",
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 0,
"trimY": 0,
"width": 31,
"height": 31,
"rawWidth": 31,
"rawHeight": 31,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"subMetas": {}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,38 @@
{
"ver": "2.3.7",
"uuid": "a599dccc-d5a2-4fff-86ea-f3a03ce9b7b8",
"importer": "texture",
"type": "sprite",
"wrapMode": "clamp",
"filterMode": "bilinear",
"premultiplyAlpha": false,
"genMipmaps": false,
"packable": true,
"width": 52,
"height": 49,
"platformSettings": {},
"subMetas": {
"jiazai1": {
"ver": "1.0.6",
"uuid": "081a89e4-cd4d-49b7-81a3-bd2b3321ca26",
"importer": "sprite-frame",
"rawTextureUuid": "a599dccc-d5a2-4fff-86ea-f3a03ce9b7b8",
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 0,
"trimY": 0,
"width": 52,
"height": 49,
"rawWidth": 52,
"rawHeight": 49,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"subMetas": {}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -0,0 +1,38 @@
{
"ver": "2.3.7",
"uuid": "6d618c9c-dc6d-48d0-a203-3304725f885b",
"importer": "texture",
"type": "sprite",
"wrapMode": "clamp",
"filterMode": "bilinear",
"premultiplyAlpha": false,
"genMipmaps": false,
"packable": true,
"width": 69,
"height": 64,
"platformSettings": {},
"subMetas": {
"jiazai2": {
"ver": "1.0.6",
"uuid": "24e560c5-22d5-44e4-8b55-85431fd8a61b",
"importer": "sprite-frame",
"rawTextureUuid": "6d618c9c-dc6d-48d0-a203-3304725f885b",
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 0,
"trimY": 0,
"width": 69,
"height": 64,
"rawWidth": 69,
"rawHeight": 64,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"subMetas": {}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

View File

@ -0,0 +1,38 @@
{
"ver": "2.3.7",
"uuid": "e1b9ccf5-5ce0-4f3a-98b3-be03da8aa0b1",
"importer": "texture",
"type": "sprite",
"wrapMode": "clamp",
"filterMode": "bilinear",
"premultiplyAlpha": false,
"genMipmaps": false,
"packable": true,
"width": 50,
"height": 53,
"platformSettings": {},
"subMetas": {
"jiazai3": {
"ver": "1.0.6",
"uuid": "9a639b00-f202-4b8e-98f0-6be5cece1cc6",
"importer": "sprite-frame",
"rawTextureUuid": "e1b9ccf5-5ce0-4f3a-98b3-be03da8aa0b1",
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 0,
"trimY": 0,
"width": 50,
"height": 53,
"rawWidth": 50,
"rawHeight": 53,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"subMetas": {}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 243 KiB

View File

@ -0,0 +1,38 @@
{
"ver": "2.3.7",
"uuid": "0f9aab89-5e08-423d-8030-259fe54c4d74",
"importer": "texture",
"type": "sprite",
"wrapMode": "clamp",
"filterMode": "bilinear",
"premultiplyAlpha": false,
"genMipmaps": false,
"packable": true,
"width": 1080,
"height": 2340,
"platformSettings": {},
"subMetas": {
"loadBg": {
"ver": "1.0.6",
"uuid": "c09e129e-5195-4054-b8a5-65e1bd675c3f",
"importer": "sprite-frame",
"rawTextureUuid": "0f9aab89-5e08-423d-8030-259fe54c4d74",
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 0,
"trimY": 0,
"width": 1080,
"height": 2340,
"rawWidth": 1080,
"rawHeight": 2340,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"subMetas": {}
}
}
}

View File

@ -0,0 +1,190 @@
[
{
"__type__": "cc.Prefab",
"_name": "",
"_objFlags": 0,
"_native": "",
"data": {
"__id__": 1
},
"optimizationPolicy": 0,
"asyncLoadAssets": false,
"readonly": false
},
{
"__type__": "cc.Node",
"_name": "progress",
"_objFlags": 0,
"_parent": null,
"_children": [],
"_active": true,
"_components": [
{
"__id__": 2
}
],
"_prefab": {
"__id__": 3
},
"_opacity": 255,
"_color": {
"__type__": "cc.Color",
"r": 255,
"g": 255,
"b": 255,
"a": 255
},
"_contentSize": {
"__type__": "cc.Size",
"width": 0,
"height": 0
},
"_anchorPoint": {
"__type__": "cc.Vec2",
"x": 0.5,
"y": 0.5
},
"_trs": {
"__type__": "TypedArray",
"ctor": "Float64Array",
"array": [
0,
-10.935,
0,
0,
0,
0,
1,
1,
1,
1
]
},
"_eulerAngles": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_skewX": 0,
"_skewY": 0,
"_is3DNode": false,
"_groupIndex": 0,
"groupIndex": 0,
"_id": ""
},
{
"__type__": "cc.ParticleSystem",
"_name": "",
"_objFlags": 0,
"node": {
"__id__": 1
},
"_enabled": true,
"_materials": [
{
"__uuid__": "eca5d2f2-8ef6-41c2-bbe6-f9c79d09c432"
}
],
"_srcBlendFactor": 770,
"_dstBlendFactor": 1,
"_custom": true,
"_file": {
"__uuid__": "b2687ac4-099e-403c-a192-ff477686f4f5"
},
"_spriteFrame": {
"__uuid__": "2fdf5c03-b33d-4d22-a79a-0eff900dae7d"
},
"_texture": null,
"_stopped": false,
"playOnLoad": true,
"autoRemoveOnFinish": false,
"totalParticles": 100,
"duration": -1,
"emissionRate": 999.9999851,
"life": 2,
"lifeVar": 4,
"_startColor": {
"__type__": "cc.Color",
"r": 49,
"g": 255,
"b": 15,
"a": 157
},
"_startColorVar": {
"__type__": "cc.Color",
"r": 255,
"g": 242,
"b": 34,
"a": 226
},
"_endColor": {
"__type__": "cc.Color",
"r": 251,
"g": 255,
"b": 55,
"a": 255
},
"_endColorVar": {
"__type__": "cc.Color",
"r": 240,
"g": 249,
"b": 107,
"a": 255
},
"angle": -20,
"angleVar": 40,
"startSize": 3.3699999,
"startSizeVar": 50,
"endSize": 20,
"endSizeVar": 0,
"startSpin": -47.369998931884766,
"startSpinVar": 0,
"endSpin": -47.369998931884766,
"endSpinVar": -142.11000061035156,
"sourcePos": {
"__type__": "cc.Vec2",
"x": 0,
"y": 0
},
"posVar": {
"__type__": "cc.Vec2",
"x": 7,
"y": 7
},
"_positionType": 1,
"positionType": 1,
"emitterMode": 1,
"gravity": {
"__type__": "cc.Vec2",
"x": 30,
"y": 40
},
"speed": 0,
"speedVar": 0,
"tangentialAccel": 50,
"tangentialAccelVar": 60,
"radialAccel": 0,
"radialAccelVar": 0,
"rotationIsDir": false,
"startRadius": 0,
"startRadiusVar": 0,
"endRadius": 50,
"endRadiusVar": 60,
"rotatePerS": 0,
"rotatePerSVar": 0,
"_N$preview": true,
"_id": ""
},
{
"__type__": "cc.PrefabInfo",
"root": {
"__id__": 1
},
"asset": {
"__id__": 0
},
"fileId": "",
"sync": false
}
]

View File

@ -0,0 +1,9 @@
{
"ver": "1.3.2",
"uuid": "6d2a759f-4b98-4fc3-99f4-245daa9015a9",
"importer": "prefab",
"optimizationPolicy": "AUTO",
"asyncLoadAssets": false,
"readonly": false,
"subMetas": {}
}

13
assets/Scene.meta Normal file
View File

@ -0,0 +1,13 @@
{
"ver": "1.1.3",
"uuid": "29f52784-2fca-467b-92e7-8fd9ef8c57b7",
"importer": "folder",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}

42584
assets/Scene/GameScene.fire Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
{
"ver": "1.3.2",
"uuid": "4eaf518b-35ec-4262-928d-4d497c3f2830",
"importer": "scene",
"asyncLoadAssets": false,
"autoReleaseAssets": false,
"subMetas": {}
}

22038
assets/Scene/HomeScene.fire Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
{
"ver": "1.3.2",
"uuid": "66281f32-0047-4af8-8237-90c93fc4b0e8",
"importer": "scene",
"asyncLoadAssets": false,
"autoReleaseAssets": false,
"subMetas": {}
}

13
assets/Script.meta Normal file
View File

@ -0,0 +1,13 @@
{
"ver": "1.1.3",
"uuid": "4734c20c-0db8-4eb2-92ea-e692f4d70934",
"importer": "folder",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}

BIN
assets/Script.zip Normal file

Binary file not shown.

6
assets/Script.zip.meta Normal file
View File

@ -0,0 +1,6 @@
{
"ver": "1.0.3",
"uuid": "c7c9a4c1-ac19-467e-93dd-3e5e25280820",
"importer": "asset",
"subMetas": {}
}

227
assets/Script/Avatar.ts Normal file
View File

@ -0,0 +1,227 @@
import CollisionDetection from "./CollisionDetection";
import JiaZai from "./JiaZai";
import MapConroler from "./Map";
const { ccclass, property } = cc._decorator;
@ccclass
export default class Avatar extends cc.Component {
// @property({
// tooltip: '碰撞形状None就是无敌不参与碰撞',
// type: cc.Enum(BlockType),
// // default: BlockType.Nomal,
// displayName: '碰撞形状'
// })
@property(cc.Node)
content: cc.Node = null;
@property(cc.Node)
content2: cc.Node = null;
@property(cc.SpriteAtlas)
ui: cc.SpriteAtlas = null;
avatar: any; //正在使用中的头像
avatarNow: any// 选中的头像
avatarKuang: any;
onLoad() {
}
start() {
}
init() {
this.avatar = cc.fx.GameConfig.GM_INFO.useravatarIcon;
this.avatarKuang = cc.fx.GameConfig.GM_INFO.useravaterkuang;
this.changeBtnState("avatar");
this.changeAvatar(null, this.avatar);
this.getSelfAvatar();
}
getSelfAvatar() {
this.content2.getChildByName(this.avatarKuang).getChildByName("select").active = true;
if (this.avatar.length > 10) {
this.setSelfAvatar(true);
}
else {
this.node.getChildByName("self").getChildByName("icon").getComponent(cc.Sprite).spriteFrame =
this.ui.getSpriteFrame(this.avatar);
}
this.node.getChildByName("self").getChildByName("kuang").getComponent(cc.Sprite).spriteFrame =
this.ui.getSpriteFrame(this.avatarKuang);
cc.fx.GameTool.getUserAvatar((data) => {
if (data == true) {
this.avatar = cc.fx.GameConfig.GM_INFO.useravatar;
this.changeAvatar(null, this.avatar);
this.clickBtn();
}
this.setSelfAvatar(data);
})
}
closeAvatar() {
const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
const jiazaiComp = jiazaiNode.getComponent(JiaZai);
if (jiazaiComp) {
console.log("获取到JiaZai组件", jiazaiComp);
jiazaiComp.closeAvatar();
} else {
console.log("无法获取JiaZai组件");
}
}
// 切换状态 头像和头像框
changeState(event, state) {
if (state == 'tou') {
if (this.node.getChildByName("tou").opacity == 255) {
return;
}
else {
this.node.getChildByName("tou").opacity = 255;
this.node.getChildByName("kuang").opacity = 0;
this.node.getChildByName("avatar").active = true;
this.node.getChildByName("avatarKuang").active = false;
this.changeBtnState("avatar");
}
}
else if (state == 'kuang') {
if (this.node.getChildByName("kuang").opacity == 255) {
return;
}
else {
this.node.getChildByName("tou").opacity = 0;
this.node.getChildByName("kuang").opacity = 255;
this.node.getChildByName("avatar").active = false;
this.node.getChildByName("avatarKuang").active = true;
this.changeBtnState("kuang");
}
}
}
// 判断按钮状态,切换按钮状态
changeBtnState(state) {
if (state == 'avatar') {
if (this.avatar == cc.fx.GameConfig.GM_INFO.useravatarIcon) {
this.node.getChildByName("btn").active = false;
this.node.getChildByName("btnUse").active = true;
}
else {
this.node.getChildByName("btn").active = true;
this.node.getChildByName("btnUse").active = false;
}
}
else if (state == 'kuang') {
if (this.avatarKuang == cc.fx.GameConfig.GM_INFO.useravaterkuang) {
this.node.getChildByName("btn").active = false;
this.node.getChildByName("btnUse").active = true;
}
else {
this.node.getChildByName("btn").active = true;
this.node.getChildByName("btnUse").active = false;
}
}
}
//改变头像
changeAvatar(event, avatar) {
this.closeSelectAvatar();
this.avatar = avatar;
switch (avatar) {
case "icon":
this.avatar = cc.fx.GameConfig.GM_INFO.useravatar;
this.content.children[0].getChildByName("select").active = true;
break;
case "icon_0":
this.content.children[1].getChildByName("select").active = true;
break;
case "icon_1":
this.content.children[2].getChildByName("select").active = true;
break;
case "icon_2":
this.content.children[3].getChildByName("select").active = true;
break;
case "icon_3":
this.content.children[4].getChildByName("select").active = true;
break
default:
if (this.avatar.length > 10) {
this.content.children[0].getChildByName("select").active = true;
}
break;
}
this.changeBtnState("avatar");
}
setSelfAvatar(data) {
let url = cc.fx.GameConfig.GM_INFO.useravatar;
if (url == "") {
return;
}
var self = this;
cc.assetManager.loadRemote(cc.fx.GameConfig.GM_INFO.useravatar, { ext: '.png' }, (err, texture: cc.Texture2D) => {
if (texture) {
if (data == true || this.avatar.length > 10) {
var sprite = self.node.getChildByName("self").getChildByName("icon").getComponent(cc.Sprite);
sprite.spriteFrame = new cc.SpriteFrame(texture);
}
var sprite2 = self.content.children[0].getChildByName("icon").getComponent(cc.Sprite);
sprite2.spriteFrame = new cc.SpriteFrame(texture);
}
})
}
//使用 按钮
clickBtn() {
if (this.node.getChildByName("avatar").active == true) {
cc.fx.GameConfig.GM_INFO.useravatarIcon = this.avatar;
if (cc.fx.GameConfig.GM_INFO.useravatarIcon.length > 10) {
cc.fx.GameConfig.GM_INFO.useravatarIcon = cc.fx.GameConfig.GM_INFO.useravatar;
this.setSelfAvatar(true);
}
else {
this.node.getChildByName("self").getChildByName("icon").getComponent(cc.Sprite).spriteFrame =
this.ui.getSpriteFrame(this.avatar);
}
}
else {
cc.fx.GameConfig.GM_INFO.useravaterkuang = this.avatarKuang;
this.node.getChildByName("self").getChildByName("kuang").getComponent(cc.Sprite).spriteFrame =
this.ui.getSpriteFrame(this.avatarKuang);
}
this.node.getChildByName("btn").active = false;
this.node.getChildByName("btnUse").active = true;
}
//改变头像框
changeKuang(event, kuang) {
this.closeSelectKuang();
this.avatarKuang = kuang;
this.content2.getChildByName(kuang).getChildByName("select").active = true;
this.changeBtnState("kuang");
}
closeSelectAvatar() {
for (let i = 0; i < this.content.children.length; i++) {
this.content.children[i].getChildByName("select").active = false;
}
}
closeSelectKuang() {
for (let i = 0; i < this.content2.children.length; i++) {
this.content2.children[i].getChildByName("select").active = false;
}
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "7589aa1e-95ba-47b3-9109-4244d3284eb2",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

99
assets/Script/Barrier.ts Normal file
View File

@ -0,0 +1,99 @@
import CollisionDetection from "./CollisionDetection";
import MapConroler from "./Map";
const { ccclass, property } = cc._decorator;
@ccclass
export default class Block extends cc.Component {
// 新增缓存变量
private selfBoxColliders: cc.BoxCollider[] = [];
private allBoxColliders: cc.BoxCollider[] = [];
// @property({
// tooltip: '碰撞形状None就是无敌不参与碰撞',
// type: cc.Enum(BlockType),
// // default: BlockType.Nomal,
// displayName: '碰撞形状'
// })
// LIFE-CYCLE CALLBACKS:
// @property(cc.SpriteAtlas)
// UI: cc.SpriteAtlas = null;
private initialTouchOffset: cc.Vec2 = null;
private offsetTolerance = 100; // 偏移容忍度;
allBlocks: any; //所有的方块,用于计算posX,posY消除
touchPoint: cc.Vec2 = null; //触摸点
isTouch: boolean = false; //是否触摸
posX: number = 0; //地图块的X坐标
posY: number = 0; //地图块的Y坐标
moveLeft: boolean = true; //是否可以左移;
moveRight: boolean = true; //是否可以右移;
moveUp: boolean = true; //是否可以上移;
moveDown: boolean = true; //是否可以下移;
moveCorner: number = 0; //是否碰撞角落
moveY: number = 0; //是否可以上下移动;
moveX: number = 0; //是否可以左右移动;
touchPointX: number = 0; //触摸点X坐标;
touchPointY: number = 0; //触摸点Y坐标;
blockId: number = 0; //方块ID;
stacking: cc.Vec2; //叠加方块
level: number = 0; //叠加方块层数;
pz: boolean = false;
collider: any;
block_Info: any;
_touchListener: any;
relative_Position: cc.Vec2; //点击和方块相对位置
private _eventManager: any;
hit: cc.Node;
onLoad() {
// this.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this);
// this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this);
// this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.touchEnd, this);
// this.node.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this);
this.pz = false;
this.stacking = cc.v2(0, 0);
// this.selfBoxColliders = this.node.getComponentsInChildren(cc.BoxCollider)
// .filter(collider => collider.tag < 4);
}
start() {
}
jsonDeepClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj));
}
init(block_Info, posX, posY, node) {
this.block_Info = this.jsonDeepClone(block_Info);
let mapInfo = MapConroler._instance.mapInfo;
//console.log("block_Info", this.block_Info);
for (let i = 0; i < mapInfo.length; i++) {
let blockRect = mapInfo[i].getBoundingBox();
// 使用 cc.Intersection.pointInRect 方法判断点是否在矩形范围内
let point = cc.v2(this.node.position.x - 5, this.node.position.y + 10)
if (blockRect.contains(point)) {
this.posX = mapInfo[i].getComponent("MapBlock").posX;
this.posY = mapInfo[i].getComponent("MapBlock").posY;
this.level = 50 + this.posX - this.posY * 3;
this.node.zIndex = this.level;
this.node.x = mapInfo[i].x + 65;
this.node.y = mapInfo[i].y - 60;
i = 10000;
break;
}
}
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "90c37607-5145-4fb1-8d26-94d9a89baeee",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

1873
assets/Script/Block.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "c58de376-bb53-4664-bf27-270be7bb53d1",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,73 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const {ccclass, property, requireComponent} = cc._decorator;
@ccclass
export default class CollisionDetection extends cc.Component {
static _instance: any; onLoad() {
if (CollisionDetection._instance == null) {
CollisionDetection._instance = this;
// cc.game.addPersistRootNode(this.node);
}
else {
return;
}
}
//碰撞检测函数
public isColliding(rect1: cc.Rect, rect2: cc.Rect): { isColliding: boolean } {
// 快速排除:检查边界框是否相交
if (rect1.xMax < rect2.xMin || rect2.xMax < rect1.xMin || rect1.yMax < rect2.yMin || rect2.yMax < rect1.yMin) {
return { isColliding: false };
}
// 调用原始的 intersects 方法
const isColliding = rect1.intersects(rect2);
return { isColliding };
}
// 获取多边形的所有边的法线
private getNormals(polygon: cc.Vec2[]): cc.Vec2[] {
const normals: cc.Vec2[] = [];
const length = polygon.length;
for (let i = 0; i < length; i++) {
const p1 = polygon[i];
const p2 = polygon[(i + 1) % length];
const edge = new cc.Vec2(p2.x - p1.x, p2.y - p1.y);
const normal = new cc.Vec2(-edge.y, edge.x);
normal.normalize();
normals.push(normal);
}
return normals;
}
// 将多边形投影到轴上
private project(polygon: cc.Vec2[], axis: cc.Vec2): { min: number; max: number } {
let min = cc.Vec2.dot(polygon[0], axis);
let max = min;
for (let i = 1; i < polygon.length; i++) {
const dotProduct = cc.Vec2.dot(polygon[i], axis);
if (dotProduct < min) {
min = dotProduct;
} else if (dotProduct > max) {
max = dotProduct;
}
}
return { min, max };
}
// 检查两个投影是否重叠
private overlap(projection1: { min: number; max: number }, projection2: { min: number; max: number }): boolean {
return !(projection1.max < projection2.min || projection2.max < projection1.min);
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "f1883a57-ccc5-48a7-9fc0-4430167d9ee3",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,178 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const {ccclass, property} = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property(cc.Node)
Map: cc.Node = null;
@property(cc.Prefab)
tip: cc.Prefab = null;
@property(cc.Prefab)
reinforce: cc.Prefab = null;
@property(cc.Prefab)
soil: cc.Prefab = null;
tipArray:any;
controlArray:any;
canTouch:boolean;
Reinforce:boolean;
Soil:boolean;
mapHeight:number;
// LIFE-CYCLE CALLBACKS:
// onLoad () {}
start () {
this.tipArray = [];
this.controlArray = [];
this.canTouch = true;
this.Reinforce = false;
this.Soil = false;
this.mapHeight = 0;
}
setPosition(tip){
tip.setPosition(30,-25);
if(this.tipArray.length > 0){
let length = this.tipArray.length+1;
let posY = Math.ceil(length/8) - 1;
let posX = length - Math.floor(posY)*8 - 1;
tip.setPosition(30 + 48*posX,-25 -48*posY + this.mapHeight);
}
}
//清空所有
removeAllTip(){
if(!this.canTouch) return;
if(this.tipArray.length > 0){
cc.fx.AudioManager._instance.playEffect("qingkong",null);
for(let i=0; i<this.tipArray.length;i++){
let tip = this.tipArray[i];
tip.active = false;
tip.removeFromParent(this.Map);
tip = null;
}
this.tipArray = [];
this.controlArray = [];
var drawingReset = cc.fx.GameConfig.CLICK_DATA.drawingReset + 1;
cc.fx.GameConfig.CLICK_SET("drawingReset",drawingReset);
cc.fx.Notifications.emit(cc.fx.Message.removeTip,"remove");
this.mapHeight = 0;
}
}
//撤回一步
back_Click(){
if(!this.canTouch) return;
if(this.tipArray.length > 0){
cc.fx.AudioManager._instance.playEffect("chehui",null);
let tip = this.tipArray[this.tipArray.length-1];
tip.active = false;
tip.removeFromParent(this.Map);
tip = null;
this.tipArray.pop();
this.controlArray.pop();
var drawingBack = cc.fx.GameConfig.CLICK_DATA.drawingBack + 1;
cc.fx.GameConfig.CLICK_SET("drawingBack",drawingBack);
cc.fx.Notifications.emit(cc.fx.Message.removeTip,"back");
if(this.tipArray.length >= 24){
if((this.tipArray.length )%8 == 0){
this.mapMove(false);
}
}
}
}
//点击事件
btn_Click(target,data){
var GameManager = this.node.parent.getComponent("GameManager");
if(GameManager.btnClick == true){
GameManager.btnClick = false;
cc.fx.Notifications.emit(cc.fx.Message.guideNext);
}
cc.fx.Notifications.emit(cc.fx.Message.control,data);
if(!this.canTouch) return;
let prefab = this.tip;
if(data == "reinforce" || data == "soil"){
prefab = this[data];
if(data == "reinforce"){
if(this.Reinforce){
this.Reinforce = false;
this.back_Click();
return;
}else{
cc.fx.AudioManager._instance.playEffect("jineng",null);
this.Reinforce = true;
this.Soil = false;
}
}
else if(data == "soil"){
if(this.Soil){
this.Soil = false;
this.back_Click();
return;
}else{
cc.fx.AudioManager._instance.playEffect("jineng",null);
this.Soil = true;
this.Reinforce = false;
}
}
}
else{
cc.fx.AudioManager._instance.playEffect("fangxiang",null);
this.Reinforce = false;
this.Soil = false;
}
let tip = cc.instantiate(prefab);
if(data == "up") tip.angle = 180;
if(data == "left") tip.angle = -90;
if(data == "right") tip.angle = 90;
tip.parent = this.Map;
if(this.controlArray[this.controlArray.length-1] == "reinforce" ||
this.controlArray[this.controlArray.length-1] == "soil"){
if(data == "reinforce" || data == "soil"){
this.tipArray[this.tipArray.length-1].removeFromParent();
this.tipArray[this.tipArray.length-1] = null;
this.tipArray.pop();
this.controlArray.pop();
}
}
this.setPosition(tip);
this.tipArray.push(tip);
this.controlArray.push(data);
if(this.tipArray.length >= 25){
if((this.tipArray.length - 1)%8 == 0){
this.mapMove(true);
}
}
}
//地图放不下了上下移动
mapMove(type){
if(type) this.mapHeight += 48;
else this.mapHeight -= 48;
for(let i=0; i<this.tipArray.length;i++){
let tip = this.tipArray[i];
if(type)tip.y += 48;
else tip.y -= 48;
}
}
//点击开始 创建河道
start_Click(){
if(!this.canTouch) return;
this.canTouch = false;
cc.fx.AudioManager._instance.playEffect("build",null);
cc.fx.Notifications.emit(cc.fx.Message.startGame,this.controlArray);
}
// update (dt) {}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "e35ab717-e554-40a0-8b4e-ea6805718c97",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,10 @@
cc.Class({
extends: cc.Component,
properties: {
},
onLoad () {
cc.dynamicAtlasManager.enabled = false;
},
});

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "5c9b8159-89a3-4b32-b303-b3d4f7ac1c9f",
"importer": "javascript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,611 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
import Utils from "./module/Pay/Utils";
import { MiniGameManager } from "./Sdk/MiniGameManager";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";
const { ccclass, property } = cc._decorator;
@ccclass
export default class GameManager extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
@property
text: string = 'hello';
static _instance: GameManager = null;
@property({ type: [cc.Prefab], tooltip: "方块数组" })
Block_Array: Array<cc.Prefab> = [];
@property({ type: [cc.Prefab], tooltip: "墙壁数组" })
Wall_Prefab: Array<cc.Prefab> = [];
@property({ type: [cc.SpriteAtlas], tooltip: "方块颜色" })
Block_Color: Array<cc.SpriteAtlas> = [];
particleEffects: cc.ParticleAsset[];
// @property({type: [cc.ParticleSystem], tooltip:"粒子数组"})
// particleEffects : Array<cc.ParticleSystem> = [];
load1: boolean = false;
load2: boolean = false;
load3: boolean = false;
load4: boolean = false;
load5: boolean = false;
load6: boolean = false;
scheduleCallback: any;
timeNumber: number;
nowTime: number;
// LIFE-CYCLE CALLBACKS:
/** 游戏入口初始化 */
onLoad() {
window.initMgr();
this.timeNumber = 1;
this.startTimeCutDown();
cc.fx.GameConfig.init(true);
cc.fx.GameConfig.GM_INFO.gameState = false;
this.readMusicConfig();
this.load1 = this.load2 = this.load3 = this.load4 = this.load5 = this.load6 = false;
setTimeout(() => {
this.getSetting();
this.readUserData();
this.getShareInfo();
}, 100);
if (GameManager._instance == null) {
GameManager._instance = this;
cc.game.addPersistRootNode(this.node);
}
else {
return;
}
// 检测微信小游戏切到后台
if (cc.sys.platform === cc.sys.WECHAT_GAME) {
//@ts-ignore
wx.onHide(() => {
this.onHide();
});
// 检测微信小游戏回到前台
//@ts-ignore
wx.onShow(() => {
this.onShow();
});
}
}
start() {
setTimeout(() => {
const path = 'prefab/block';
const path2 = 'prefab/wall';
cc.resources.loadDir(path, cc.Prefab, (err, assets: cc.Prefab[]) => {
if (err) {
cc.director.loadScene("LoadScene");
return;
}
// 将加载的 Prefab 赋值给 Block_Array
this.Block_Array = assets;
this.setSort();
this.load1 = true;
});
cc.resources.loadDir(path2, cc.Prefab, (err, assets: cc.Prefab[]) => {
if (err) {
cc.director.loadScene("LoadScene");
return;
}
// 将加载的 Prefab 赋值给 Block_Array
this.Wall_Prefab = assets;
this.load2 = true;
this.setWallPrefabSort();
});
}, 100);
}
onHide() {
cc.audioEngine.stopMusic();
cc.game.pause();
}
onShow() {
cc.audioEngine.resumeMusic();
cc.game.resume();
}
//#region 给加载好的墙壁资源排序
/** 给加载好的墙壁资源排序,防止乱序 */
setWallPrefabSort() {
const order = ['down', 'downleft', 'downright', 'left', 'leftdown', 'leftup', 'right', 'rightdown', 'rightup', 'up', 'upleft', 'upright'];
this.Wall_Prefab.sort((a, b) => {
const indexA = order.indexOf(a.name);
const indexB = order.indexOf(b.name);
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
}
/** 给加载好的方块资源排序,防止乱序 */
setSort() {
this.Block_Array.sort((a, b) => {
// 从名称中提取数字部分
const numberA = parseInt(a.name.match(/\d+/)?.[0] || '0', 10);
const numberB = parseInt(b.name.match(/\d+/)?.[0] || '0', 10);
return numberA - numberB;
});
}
//#region 开始游戏
/** 开始游戏,执行逻辑 */
startGame() {
// 加载成功后进入 HomeScene
cc.assetManager.loadBundle('shop', (err, bundle) => {
if (err) {
console.error('加载 shop 失败:', err);
} else {
// 加载成功后进入 HomeScene
cc.assetManager.loadBundle('music', (err, bundle) => {
if (err) {
console.error('加载 music bundle 失败:', err);
// 加载失败时仍尝试进入 HomeScene
cc.director.loadScene("HomeScene");
} else {
}
cc.director.loadScene("HomeScene");
});
}
});
// 加载 music bundle
}
//#region 微信登录,以及读取用户信息
/** 微信登录,以及读取用户信息 */
readUserData(retryCount = 0) {
//@ts-ignore
if (typeof wx !== 'undefined' && wx !== null) {
MiniGameSdk.API.shushu_Init();
this.nowTime = Date.now();
// 最大重试次数
const MAX_RETRIES = 30;
// 延迟时间数组,按照 1 秒 3 次、2 秒 5 次、5 秒 6 次、15 秒 5 次的规则生成
const delays = [
...Array(3).fill(2000),
...Array(5).fill(3000),
...Array(6).fill(5000),
...Array(5).fill(15000)
];
//cc.fx.GameConfig.GM_INFO.shushu_DistinctId
const attemptUserInfo = () => {
Utils.getUserInfo((data) => {
if (data.code == 1) { // 假设返回数据中有 success 字段表示成功
console.log("登錄", data);
if (data.data.openid) {
cc.fx.GameConfig.GM_INFO.openid = data.data.openid;
cc.fx.StorageMessage.setStorage("openid", cc.fx.GameConfig.GM_INFO.openid);
}
if (data.data._id) {
cc.fx.GameConfig.GM_INFO.uid = data.data._id;
cc.fx.StorageMessage.setStorage("uid", data.data._id);
}
if (data.data.onlyId) {
cc.fx.GameConfig.GM_INFO.userId = data.data.onlyId;
}
if (data.data.outTradeNo.length > 0) {
cc.fx.GameConfig.GM_INFO.allOutTradeNo = [];
cc.fx.GameConfig.GM_INFO.allOutTradeNo = data.data.outTradeNo;
}
if (data.data.shareLv) {
if (data.data.shareLv.length > 0) {
cc.fx.GameConfig.GM_INFO.helpLevel = data.data.shareLv[0].lv;
}
}
if (data.data.username) {
cc.fx.GameConfig.GM_INFO.username = data.data.username;
}
if (data.data.useravatar) {
cc.fx.GameConfig.GM_INFO.useravatarIcon = data.data.useravatar;
if (cc.fx.GameConfig.GM_INFO.useravatarIcon.length < 10)
cc.fx.GameConfig.GM_INFO.useravatarIcon = "icon_" + cc.fx.GameConfig.GM_INFO.useravatarIcon
}
if (data.data.useravatarIcon) {
cc.fx.GameConfig.GM_INFO.useravaterkuang = data.data.useravatarIcon;
cc.fx.GameConfig.GM_INFO.useravaterkuang = "kuang_" + (parseInt(cc.fx.GameConfig.GM_INFO.useravaterkuang) + 1);
}
if (data.data.task) {
let task = JSON.parse(data.data.task);
cc.fx.GameConfig.GM_INFO.tasks.levelPass = task["levelPass"];
cc.fx.GameConfig.GM_INFO.tasks.share = task["share"];
cc.fx.GameConfig.GM_INFO.tasks.useEnergy = task["useEnergy"];
cc.fx.GameConfig.GM_INFO.tasks.useProp = task["useProp"];
}
//如果有连胜记录,就赋值
if (data.data.winStreak) {
console.log("从服务器得到连胜", data.data.winStreak);
cc.fx.GameConfig.GM_INFO.winStreak = parseInt(data.data.winStreak);
let winState = cc.fx.StorageMessage.getStorage("winState");
console.log("本地连胜状态", winState);
if ((winState == null || winState == undefined) && winState != false) {
console.log("没有缓存进入这里");
cc.fx.GameConfig.GM_INFO.winState = false;
if (cc.fx.GameConfig.GM_INFO.winStreak >= 10) {
cc.fx.GameConfig.GM_INFO.winState = true;
}
cc.fx.StorageMessage.setStorage("winState", cc.fx.GameConfig.GM_INFO.winState);
}
else {
cc.fx.GameConfig.GM_INFO.winState = winState;
console.log("连胜状态:", cc.fx.GameConfig.GM_INFO.winState);
if (winState == false) {
if (cc.fx.GameConfig.GM_INFO.winStreak >= 10) {
cc.fx.GameConfig.GM_INFO.winStreak = 0;
Utils.setWinStreak((data) => {
if (data.code == 1) {
console.log("连胜状态杀端清零成功");
}
})
}
}
}
cc.fx.StorageMessage.setStorage("winStreak", cc.fx.GameConfig.GM_INFO.winStreak);
}
else {
let winStreak = cc.fx.StorageMessage.getStorage("winStreak");
if (winStreak == undefined || winStreak == "" || winStreak == null) {
cc.fx.GameConfig.GM_INFO.winStreak = 0;
cc.fx.StorageMessage.setStorage("winStreak", cc.fx.GameConfig.GM_INFO.winStreak);
}
else {
cc.fx.GameConfig.GM_INFO.winStreak = winStreak;
}
console.log("调用连胜上传");
Utils.setWinStreak((data) => {
if (data.code == 1) {
console.log("设置连胜成功");
}
})
}
this.setUserPower(data);
this.setmonth(data);
this.setRevive(data);
let levelInfo = cc.fx.StorageMessage.getStorage("level");
//如果本地缓存没有关卡信息,默认为服务器信息为主
if (levelInfo == undefined || levelInfo == "" || levelInfo == null) {
this.getUserDataToServer(data.data);
// this.oldReadData(retryCount);
}
//新的读取数据设置方法,以本地为主
else {
this.getUserDataToLocal(data.data);
// this.newReadData();
}
cc.fx.GameTool.getHealth((data) => {
this.load5 = true;
});
this.load6 = true;
}
else {
if (retryCount < MAX_RETRIES && retryCount < delays.length) {
const delay = delays[retryCount];
console.error(`获取用户信息失败,第 ${retryCount + 1} 次重试,将在 ${delay / 1000} 秒后重试`);
setTimeout(() => {
retryCount++;
attemptUserInfo();
}, delay);
} else {
console.error('获取用户信息失败,达到最大重试次数,退出游戏');
// 退出游戏
cc.game.end();
}
}
});
};
attemptUserInfo();
}
else {
this.load3 = true;
this.load4 = true;
this.load5 = true;
this.load6 = true;
cc.fx.GameTool.getHealth(null);
}
// 存储用户数据
}
//#region 读取音乐配置
/** 读取音乐配置 */
readMusicConfig() {
let audioInfo = cc.fx.StorageMessage.getStorage("music");
if (audioInfo == undefined || audioInfo == "" || audioInfo == null) {
audioInfo = {
"musicOpen": true, //音乐
"effectOpen": true, //音效
"vibrateOpen": true, //震动
}
cc.fx.StorageMessage.setStorage("music", audioInfo);
}
else {
cc.fx.GameConfig.GM_INFO.musicOpen = audioInfo.musicOpen;
cc.fx.GameConfig.GM_INFO.effectOpen = audioInfo.effectOpen;
cc.fx.GameConfig.GM_INFO.vibrateOpen = audioInfo.vibrateOpen;
}
}
//#region 老用户,读取数据
/** 老用户,有本地缓存数据,与服务器数据做比对,哪边关卡等级高以哪边为主 */
getUserDataToLocal(data) {
let levelInfo = cc.fx.StorageMessage.getStorage("level");
let coinInfo = cc.fx.StorageMessage.getStorage("coin");
let propInfo = cc.fx.StorageMessage.getStorage("prop");
if (data.levelAmount == null || data.levelAmount == undefined) {
data.levelAmount = 0;
}
if (data.coinAmount == null || data.coinAmount == undefined) {
data.coinAmount = 0;
}
if (levelInfo.level > data.levelAmount) {
cc.fx.GameConfig.GM_INFO.level = levelInfo.level;
cc.fx.GameConfig.GM_INFO.coin = coinInfo.coin;
cc.fx.GameConfig.GM_INFO.freezeAmount = propInfo.freezeAmount;
cc.fx.GameConfig.GM_INFO.hammerAmount = propInfo.hammerAmount;
cc.fx.GameConfig.GM_INFO.magicAmount = propInfo.magicAmount;
const timestamp = Date.now();
if (coinInfo.coin != data.coinAmount) {
if (coinInfo == undefined || coinInfo.coin == null) {
let coinInfo = { "coin": cc.fx.GameConfig.GM_INFO.coin, "timestamp": timestamp };
cc.fx.StorageMessage.setStorage("coin", coinInfo);
}
else {
cc.fx.GameTool.setUserCoin((data) => {
});
}
}
if (levelInfo.level != data.levelAmount) {
if (levelInfo.level == null || levelInfo == undefined) {
let levelInfo = { "level": cc.fx.GameConfig.GM_INFO.level, "timestamp": timestamp };
cc.fx.StorageMessage.setStorage("level", levelInfo);
}
else {
cc.fx.GameTool.setUserLevel((data) => {
});
}
}
if (propInfo.freezeAmount != data.freezeAmount || propInfo.hammerAmount != data.hammerAmount || propInfo.magicAmount != data.magicAmount) {
cc.fx.GameTool.setUserProp(0, 0, (data) => {
})
}
this.load3 = true;
this.load4 = true;
} else {
if (data.levelAmount == null || data.levelAmount == undefined) {
data.levelAmount = cc.fx.GameConfig.GM_INFO.level;
cc.fx.GameTool.setUserLevel((data) => {
});
}
if (data.coinAmount == null || data.coinAmount == undefined) {
data.coinAmount = cc.fx.GameConfig.GM_INFO.coin;
cc.fx.GameTool.setUserCoin((data) => {
});
}
const timestamp = Date.now();
let levelInfo = { "level": data.levelAmount, "timestamp": timestamp };
cc.fx.StorageMessage.setStorage("level", levelInfo);
let coinInfo = { "coin": data.coinAmount, "timestamp": timestamp };
cc.fx.StorageMessage.setStorage("coin", coinInfo);
let propInfo = {
"freezeAmount": data.freezeAmount,
"hammerAmount": data.hammerAmount,
"magicAmount": data.magicAmount,
"timestamp": timestamp,
}
cc.fx.GameConfig.GM_INFO.freezeAmount = data.freezeAmount;
cc.fx.GameConfig.GM_INFO.hammerAmount = data.hammerAmount;
cc.fx.GameConfig.GM_INFO.magicAmount = data.magicAmount;
cc.fx.GameConfig.GM_INFO.level = data.levelAmount;
cc.fx.GameConfig.GM_INFO.coin = data.coinAmount;
cc.fx.StorageMessage.setStorage("prop", propInfo);
this.load3 = true;
this.load4 = true;
}
}
//#region 新用户,读取数据
/** 本地没信息,新用户,或者清缓存用户 */
getUserDataToServer(data) {
const timestamp = Date.now();
if (data) {
if (data.isFirst == true) {
cc.fx.GameConfig.GM_INFO.first = true;
if (data.register_time) {
const time = data.register_time;
MiniGameSdk.API.shushu_userSet(time);
}
}
else {
}
this.load3 = true;
this.load4 = true;
if (data.levelAmount == null || data.levelAmount == undefined) {
data.levelAmount = cc.fx.GameConfig.GM_INFO.level;
cc.fx.GameTool.setUserLevel((data) => {
});
}
if (data.coinAmount == null || data.coinAmount == undefined) {
data.coinAmount = cc.fx.GameConfig.GM_INFO.coin;
cc.fx.GameTool.setUserCoin((data) => {
});
}
let levelInfo = { "level": data.levelAmount, "timestamp": timestamp };
cc.fx.StorageMessage.setStorage("level", levelInfo);
let coinInfo = { "coin": data.coinAmount, "timestamp": timestamp };
cc.fx.StorageMessage.setStorage("coin", coinInfo);
let propInfo = {
"freezeAmount": data.freezeAmount,
"hammerAmount": data.hammerAmount,
"magicAmount": data.magicAmount,
"timestamp": timestamp,
}
cc.fx.GameConfig.GM_INFO.freezeAmount = data.freezeAmount;
cc.fx.GameConfig.GM_INFO.hammerAmount = data.hammerAmount;
cc.fx.GameConfig.GM_INFO.magicAmount = data.magicAmount;
cc.fx.GameConfig.GM_INFO.level = data.levelAmount;
cc.fx.GameConfig.GM_INFO.coin = data.coinAmount;
cc.fx.StorageMessage.setStorage("prop", propInfo);
}
}
/** 倒计时保证进度在1秒内不进入游戏 */
startTimeCutDown() {
this.scheduleCallback = function () {
if (this.timeNumber <= 0) {
this.stopTimeCutDown();
}
else {
this.timeNumber -= 1;
}
}.bind(this);
this.schedule(this.scheduleCallback, 1);
}
/** 停止定时器 */
stopTimeCutDown() {
if (this.scheduleCallback) {
this.unschedule(this.scheduleCallback);
}
}
//#region 设置无限体力信息
/** 设置无限体力信息 */
setUserPower(data) {
let nowTime = Math.floor(Date.now() / 1000);
let powerTime = cc.fx.StorageMessage.getStorage("userPowerTime");
//本地没缓存
if (powerTime == "undifend" || powerTime == null || powerTime == "" || powerTime == 0) {
//本地没缓存,但是服务器有缓存,判断服务器的无限体力时间是否过期
if (data.data.userPowerTime && data.data.userPowerTime != 0) {
powerTime = data.data.userPowerTime;
if (powerTime > nowTime) {
cc.fx.GameConfig.GM_INFO.userPowerTime = powerTime;
cc.fx.StorageMessage.setStorage("userPowerTime", powerTime);
}
else {
cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
cc.fx.StorageMessage.setStorage("userPowerTime", 0);
}
}
//本地没缓存,服务器也没缓存
else {
powerTime = 0;
cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
cc.fx.StorageMessage.setStorage("userPowerTime", 0);
}
}
//本地有缓存
else {
//本地有缓存,且服务器有缓存
if (data.data.userPowerTime && data.data.userPowerTime != 0) {
//服务器缓存大于本地缓存,以服务器缓存为主
if (data.data.userPowerTime > powerTime) {
powerTime = data.data.userPowerTime;
if (powerTime > nowTime) {
cc.fx.GameConfig.GM_INFO.userPowerTime = powerTime;
cc.fx.StorageMessage.setStorage("userPowerTime", powerTime);
}
else {
cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
cc.fx.StorageMessage.setStorage("userPowerTime", 0);
}
}
//服务器缓存小于本地缓存,以本地缓存为主
else {
if (powerTime > nowTime) {
cc.fx.GameConfig.GM_INFO.userPowerTime = powerTime;
cc.fx.StorageMessage.setStorage("userPowerTime", powerTime);
}
else {
cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
cc.fx.StorageMessage.setStorage("userPowerTime", 0);
}
}
}
//本地有缓存,服务器没缓存
else {
if (powerTime > nowTime) {
cc.fx.GameConfig.GM_INFO.userPowerTime = powerTime;
cc.fx.StorageMessage.setStorage("userPowerTime", powerTime);
}
else {
cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
cc.fx.StorageMessage.setStorage("userPowerTime", 0);
}
}
}
}
//#region 设置月卡信息
/** 设置月卡信息 */
setmonth(data) {
//如果给的时间戳大于当前时间hpmax=7,否则等于5
let nowTime = Math.floor(Date.now() / 1000);
if (data.data.monthCardTime > nowTime) {
cc.fx.GameConfig.GM_INFO.hp_Max = 7;
cc.fx.GameConfig.GM_INFO.doubleCoin = 2;
} else {
cc.fx.GameConfig.GM_INFO.hp_Max = 5;
cc.fx.GameConfig.GM_INFO.doubleCoin = 1;
}
//本地储存当前服务器时间
let dateStr = new Date(data.data.monthCardTime);
cc.fx.StorageMessage.setStorage("mCardDate", dateStr);
}
//#region 复活购买次数初始化
/** 复活购买次数初始化 */
setRevive(data) {
cc.fx.GameConfig.GM_INFO.revive = data.data.rebornGiftCount;
}
//#region 获取有没有分享信息
/** 获取有没有分享信息 */
getShareInfo() {
// 检查微信小游戏启动参数
if (cc.sys.platform === cc.sys.WECHAT_GAME) {
//@ts-ignore
const launchOptions = wx.getLaunchOptionsSync();
const query = launchOptions.query;
if (query.level && query.uid) {
const level = parseInt(query.level, 10);
const uid = query.uid;
cc.fx.GameConfig.GM_INFO.otherUid = uid;
cc.fx.GameConfig.GM_INFO.otherLevel = level;
// 可以在这里处理关卡信息和 UID
}
}
}
//#region 获取是否授权
/** 获取是否授权 */
getSetting() {
MiniGameSdk.API.getWechatUserInfo((res) => {
})
}
/** 主循环,判断是否各项加载完成进入游戏 */
update(dt) {
if (this.load1 && this.load2 && this.load3 && this.load4 && this.load5 && this.load6 == true && this.timeNumber <= 0) {
this.load1 = this.load2 = false;
MiniGameSdk.API.shushu_Login();
MiniGameSdk.API.yinli_Init();
MiniGameSdk.API.yinli_Login();
this.startGame();
}
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "df248952-2e59-4e66-9087-c06a90e587b7",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

185
assets/Script/GameOver.ts Normal file
View File

@ -0,0 +1,185 @@
const {ccclass, property} = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property(cc.Label)
count: cc.Label = null;
@property(cc.Label)
time: cc.Label = null;
@property(cc.Node)
selfNode: cc.Node = null;
@property(cc.Node)
one: cc.Node = null;
@property(cc.Node)
two: cc.Node = null;
@property(cc.Node)
three: cc.Node = null;
@property(cc.Node)
four: cc.Node = null;
@property(cc.Node)
five: cc.Node = null;
listData: any;
selfData: any;
// onLoad () {}
start () {
this.count.string = cc.fx.GameConfig.GM_INFO.score + "";
var yes = 0;
var successList = cc.fx.GameConfig.GM_INFO.successList;
if(successList.length > 0){
var success = 0;
for(let i=0; i<successList.length; i++){
if(successList[i] == true) success += 1;
}
yes = success/successList.length;
}
yes = Math.floor(yes * 1000)/10;
this.time.string = yes + "%";
this.init();
}
//初始化数据
init(){
this.listData = [];
this.selfData = null;
this.one.active = false;
this.two.active = false;
this.three.active = false;
this.four.active = false;
this.five.active = false;
var urlNow = window.location.href;
if(this.containsTrain(urlNow)){
this.node.getChildByName("again").active = false;
this.node.getChildByName("back").active = false;
this.node.getChildByName("finishi").active = true;
this.setLocalStorage();
}
else{
this.setLocalStorage();
this.node.getChildByName("again").active = true;
this.node.getChildByName("back").active = true;
this.node.getChildByName("finishi").active = false;
}
this.getRank();
}
setLocalStorage(){
let timeData = cc.fx.GameConfig.TIME_INFO.totalTime;
const today = new Date().toLocaleDateString();
var name = `success_${today}_${cc.fx.GameConfig.GM_INFO.scode}_${cc.fx.GameConfig.GM_INFO.gameId}`
localStorage.setItem(name, JSON.stringify({success:true}));
}
//打开排行榜
openRank(){
cc.director.loadScene("RankScene");
}
//重新开始玩
again(){
cc.fx.GameConfig.GM_INFO.round = 0;
cc.fx.GameConfig.GM_INFO.level = 0;
cc.fx.GameConfig.GM_INFO.stepTimeList = 0;
cc.fx.GameConfig.GM_INFO.successList = [];
cc.fx.GameConfig.GM_INFO.fen = 0;
cc.fx.GameConfig.GM_INFO.score = 0;
cc.fx.GameConfig.GM_INFO.min_Time = 0;
cc.fx.GameConfig.TIME_INFO.totalTime = 120;
cc.director.loadScene("GameScene");
}
//判断来源
containsTrain(str) {
return /from=train/i.test(str);
}
//获取排行榜
getRank(){
//获取排行榜数据 所需数据量
let dataFile = {
length:5
}
cc.fx.GameTool.getRank(dataFile,data =>this.getRankData(data));
}
//打开排行榜
jumpFinishi(){
let url = "https://train.sparkus.cn/poster/game/" + cc.fx.GameConfig.GM_INFO.scode + "?suc=1";
window.location.href = url;
}
//设置排行信息
getRankData(data){
if(data){
cc.fx.GameTool.getRankData(data,this,4);
cc.fx.GameTool.setPic(this.selfNode.getChildByName("pic").getChildByName("icon"),this.selfData.pic);
var length = this.listData.length-1; if(length > 4) length = 4;
for(let i=0;i<=length;i++){
this.setRank(i,this.listData[i]);
}
}
}
//根据内容填充排行榜
setRank(num,data){
if(!data){
return;
}
var hitNode = null;
if(num == 0){
hitNode = this.one;
}
else if(num == 1){
hitNode = this.two;
}
else if(num == 2){
hitNode = this.three;
}
else if(num == 3){
hitNode = this.four;
}
else if(num == 4){
hitNode = this.five;
}
let trun = num + 1;
for(let i=0; i< trun; i++){
if(this.listData[i] && this.listData[i].nickName == cc.fx.GameConfig.GM_INFO.nickName){
trun = i + 1;
break;
}
else if(!this.listData[i] == null ){
trun = i * 2;
break;
}
this.node.color = cc.color(this.listData[0],this.listData[1],this.listData[2]);
cc.tween(this.node)
.to(0.5,{scale:2})
.by(1,{opacity:0})
.delay(0.5)
.call(() =>{
this.node.scale = 1;
this.node.opacity = 255;
this.node.color = cc.color(255,255,255);
})
.start();
}
hitNode.getChildByName("num").getComponent(cc.Label).string = num + "";
cc.tween(hitNode.getChildByName("num").getComponent(cc.Label))
.to(0.5,{string:trun+""})
.start();
let record = cc.fx.GameConfi.GM_INFO.score;
if(data.score >= record){
this.selfData = data;
this.selfNode.active = true;
}
if(hitNode){
hitNode.active = true;
if(data.nickName.length >= 4)
data.nickName = cc.fx.GameTool.subName(data.nickName,4);
hitNode.getChildByName("name").getComponent(cc.Label).string = data.nickName;
hitNode.getChildByName("total").getComponent(cc.Label).string = data.score;
cc.fx.GameTool.setPic(hitNode.getChildByName("pic").getChildByName("icon"),data.pic);
}
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "805c69df-dfdf-4759-97ae-5a7341f424c7",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,48 @@
// cc.Class({
// extends: cc.Component,
// properties: {
// localTest: {
// default: false,
// tooltip: '本地测试时勾选避免tz_url和Configure报错提交前勾掉'
// },
// clientTest: {
// default: false,
// tooltip: '客户端测试时勾选,展示版本标记方便测试区分,上线前勾掉'
// },
// clientTestVersion: {
// default: '',
// tooltip: '版本标记'
// },
// testVersion: cc.Label,
// score: cc.Label,
// double_hit: cc.Node,
// add: cc.Node,
// add2: cc.Node,
// double_title: cc.Node,
// count_time: cc.Node,
// beginNode: cc.Node,
// ball_nomal: [cc.SpriteFrame],
// bg_nomal: [cc.SpriteFrame],
// ball_light: [cc.SpriteFrame],
// kuang_Frame: [cc.SpriteFrame],
// daojishi: cc.Label,
// pause_anniu: cc.Sprite,
// mask: cc.Node,
// flashUI: {
// default: null,
// type: cc.SpriteAtlas
// },
// },
// onLoad() {
// },
// update(dt) {
// },
// });

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "e8b23e56-8d10-44ad-a8f0-2e637cc45533",
"importer": "javascript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

101
assets/Script/ItemGuide.ts Normal file
View File

@ -0,0 +1,101 @@
import JiaZai from "./JiaZai";
import MapConroler from "./Map";
const { ccclass, property } = cc._decorator;
@ccclass
export default class ItemGuide extends cc.Component {
static _instance: any;
time: number = 0;
//需要替换的三个道具节点
@property([cc.Node])
itemList: cc.Node[] = [];
@property(cc.Node)
itemGuide: cc.Node = null;
//道具节点的图片
@property([cc.SpriteFrame])
itemSpriteList: cc.SpriteFrame[] = [];
//飞的目标节点
@property([cc.Node])
targetNode: cc.Node[] = [];
onLoad() {
if (cc.fx.GameConfig.GM_INFO.level + 1 == 8) {
this.itemList[0].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[0];
this.itemList[1].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[1];
this.itemList[2].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[2];
this.itemList[3].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[12];
} else if (cc.fx.GameConfig.GM_INFO.level + 1 == 11) {
this.itemList[0].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[3];
this.itemList[1].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[4];
this.itemList[2].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[5];
this.itemList[3].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[12];
} else if (cc.fx.GameConfig.GM_INFO.level + 1 == 16) {
this.itemList[0].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[6];
this.itemList[1].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[7];
this.itemList[2].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[8];
this.itemList[3].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[12];
}
else if (cc.fx.GameConfig.GM_INFO.winStreakFirst == true) {
this.itemList[0].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[9];
this.itemList[1].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[10];
this.itemList[2].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[11];
this.itemList[3].getComponent(cc.Sprite).spriteFrame = this.itemSpriteList[13];
}
}
start() {
}
//关闭引导
closeGuide() {
this.node.children.forEach((item) => {
item.active = false;
})
this.node.children[0].active = true;
this.node.children[0].getComponent(cc.Sprite).spriteFrame = null;
this.itemGuide.active = true;
this.itemGuide.zIndex = 1000;
//获取目标节点的位置并且转换到itemGuide的位置的层级
let index = 0;
if (cc.fx.GameConfig.GM_INFO.level + 1 == 8) {
cc.fx.GameConfig.GM_INFO.hammerFirst = false;
index = 0;
} else if (cc.fx.GameConfig.GM_INFO.level + 1 == 11) {
cc.fx.GameConfig.GM_INFO.freezeFirst = false;
index = 1;
} else if (cc.fx.GameConfig.GM_INFO.level + 1 == 16) {
cc.fx.GameConfig.GM_INFO.magicAFirst = false;
index = 2;
}
else if (cc.fx.GameConfig.GM_INFO.winStreakFirst == true) {
cc.fx.GameConfig.GM_INFO.winStreakFirst = false;
index = 0;
}
let pos = this.targetNode[index].convertToWorldSpaceAR(cc.Vec3.ZERO);
pos = this.node.convertToNodeSpaceAR(pos);
this.itemGuide.zIndex = 1000;
//同时改变大小和位置
MapConroler._instance.setPropNum();
// if (this.itemGuide.active == true) {
cc.tween(this.itemGuide)
.to(0.9, { scale: 0.3, position: pos }) // 同时执行
.call(() => {
MapConroler._instance.setPropNum();
this.node.active = false;
})
.start();
// }
}
//显示引导
showGuide() {
this.node.active = true;
this.node.children[0].active = true;
}
// update (dt) {}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "54996cd2-afca-4734-b3a6-9aa9d34465de",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

1723
assets/Script/JiaZai.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "1dc936f8-7de8-4eae-91a0-4e48a1047e20",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

199
assets/Script/Load.ts Normal file
View File

@ -0,0 +1,199 @@
import ranking from "./ranking";
const { ccclass, property, requireComponent } = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property(cc.Node)
node1: cc.Node = null;
@property(cc.Node)
node2: cc.Node = null;
@property(cc.Node)
node3: cc.Node = null;
@property(false)
localTest: boolean = false;
@property("")
clientTestVersion: string = "1.0.0";
@property(cc.Label)
testVersion: cc.Label = null;
onLoad() {
//@ts-ignore
cc.internal.inputManager._maxTouches = 1
cc.debug.setDisplayStats(false);
let manager = cc.director.getCollisionManager();
manager.enabled = true;
this.setWX();
// let version = cc.fx.GameTool.getWechatGameVersion();
// if (version == "开发版" || version == "体验版") {
// cc.debug.setDisplayStats(true);
// }
// else if (version == "正式版") {
// cc.debug.setDisplayStats(false);
// }
// else {
// cc.debug.setDisplayStats(true);
// }
cc.tween(this.node1)
.delay(0 * 0.3)
.to(0.3, { scale: 1 })
.to(0.3, { scale: 1.3 })
.to(0.3, { scale: 1 })
.union()
.repeatForever()
.start();
cc.tween(this.node2)
.delay(1 * 0.3)
.to(0.3, { scale: 1 })
.to(0.3, { scale: 1.3 })
.to(0.3, { scale: 1 })
.union()
.repeatForever()
.start();
cc.tween(this.node3)
.delay(2 * 0.3)
.to(0.3, { scale: 1 })
.to(0.3, { scale: 1.3 })
.to(0.3, { scale: 1 })
.union()
.repeatForever()
.start();
//this.SubContext();
}
// SubContext() {
// if (typeof wx === 'undefined') {
// return;
// }
// wx.getOpenDataContext().postMessage({
// message: 'show'
// });
// console.log("加载子域");
// }
setWX() {
//@ts-ignore
if (typeof wx !== 'undefined' && wx !== null) { // 判断是否在微信环境
wx.setPreferredFramesPerSecond(60);
// // 设置转发按钮点击后的回调
var img = "https://mmocgame.qpic.cn/wechatgame/OiaWk33I6QjgWiatrb5YVUq2p0QRmQgO6rLUWxEQDZ4ib9Ny4Pr8iaHnHI6WdxibY2nPL/0";
if (Math.random() < 0.5) {
img = "https://mmocgame.qpic.cn/wechatgame/CG5xBibollws251aYD4msEPWCiafrcn4Fgtic4T2wME6sWmdfAUtfibgsWoxm59VadDD/0";
}
// const title =
// 构建分享参数
const shareParams = {
title: '快来一起玩这个超有趣的小游戏吧!', // 修改为默认分享标题
imageUrl: 'https://example.com/default_share_image.jpg' // 修改为默认分享图片
};
// 仅设置分享内容,不主动触发分享
wx.onShareAppMessage(() => shareParams);
// 监听分享到朋友圈事件
//@ts-ignore
wx.onShareTimeline(() => {
return {
title: '你想玩上怎样的游戏?'
};
});
wx.showShareMenu(() => {
return {
title: '你想玩上怎样的游戏?',
imageUrl: img,
query: ''
};
});
setTimeout(() => {
wx.showShareMenu({
menus: ['shareAppMessage', 'shareTimeline']
})
}, 2000);
setTimeout(() => {
wx.showShareMenu({
menus: ['shareAppMessage', 'shareTimeline']
})
}, 4000);
// 设置分享到朋友圈
//@ts-ignore
// wx.updateShareMenu({
// withShareTicket: true,
// success: (data) => {
// console.log('更新分享菜单成功', data);
// },
// fail: (data) => {
// console.log('更新分享菜单失败', data);
// },
// complete: (data) => {
// console.log('更新分享菜单完成', data);
// }
// });
//@ts-ignore
}
}
//判断来源
containsTrain(str) {
return /from=train/i.test(str);
}
//开始游戏,跳转至引导页面
startGame() {
cc.director.loadScene("GameScene");
// cc.director.loadScene("GuideScene");
}
//备用,用来测试跳转 指定关卡
clickBtn(event, data) {
cc.fx.GameConfig.GM_INFO.custom = parseInt(data);
cc.director.loadScene("GameScene");
}
//打开排行榜
openRank() {
cc.director.loadScene("RankScene");
}
protected update(dt: number): void {
}
// 3月17日 - 3月21日 工作完成内容
// 1游戏框架搭建
// 2制作18个基础方块预制体 (方块可编辑颜色与道具和状态)
// 3完成地图的搭建可配置8*8以内任意组合包括可缺口和障碍物配置
// 4完成地图墙面建立根据 ↑3上面构建的地图自动生成墙体。
// 5做完方块的基础移动跟随手指遇到方块或者墙壁或者障碍物阻碍移动。
// 6方块的自动落点做完11个基础方块的未做完还差11个
// 3月24日 - 3月28日 预计完成目标
// 1完成全部方块的落点。
// 2完成门的搭建门可选颜色可选开关或者星星等特殊状态
// 3完成方块通过门的游戏逻辑使游戏可以最基础运行玩起来
// 4出5关版本配合小白备案审核。
// 5根据方块地图以及道具制作地图编辑器 (方块和地图制作的时候都已经考虑到编辑器的需求了)
// 优先制作,后续开发拓展玩法功能时,小白可同步进行制作关卡。
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "454ad829-851a-40ea-8ab9-941e828357ca",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

44
assets/Script/Main.ts Normal file
View File

@ -0,0 +1,44 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const { ccclass, property } = cc._decorator;
@ccclass
export default class Main extends cc.Component {
// LIFE-CYCLE CALLBACKS:
onLoad() {
}
start() {
// console.log("运行LoadScene场景")
cc.assetManager.loadBundle('shop', (err, bundle) => {
if (err) {
console.error('加载 shop 失败:', err);
} else {
// console.log('shop加载成功');
cc.director.loadScene("LoadScene", (loadErr) => {
if (loadErr) {
// 加载场景失败,打印错误信息
console.error('加载 LoadScene 场景失败:', loadErr);
}
});
}
});
// 预加载 LoadScene 场景
// console.log("开始加载LoadScene场景")
}
// update (dt) {}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "ab8c1952-7f8e-479f-a2f8-ad140b75f7e3",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

3816
assets/Script/Map.ts Normal file

File diff suppressed because it is too large Load Diff

10
assets/Script/Map.ts.meta Normal file
View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "2234ab2c-a7b4-48be-90e0-ae7aa58e9d91",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

47
assets/Script/MapBlock.ts Normal file
View File

@ -0,0 +1,47 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const { ccclass, property } = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
@property
block_Id: string = '';
@property(cc.SpriteAtlas)
riseFall: cc.SpriteAtlas = null;
// LIFE-CYCLE CALLBACKS:
posX: number = 0; //地图块的X坐标
posY: number = 0; //地图块的Y坐标
direction: string = ""; //地图块的方向
// onLoad () {}
start() {
this.direction = "";
this.block_Id = "";
// this.node.getChildByName("num").getComponent(cc.Label).string = this.direction;
}
setDiraction(direction) {
this.direction = direction;
// this.node.getChildByName("num").getComponent(cc.Label).string = this.direction;
}
init(posX, posY) {
this.posX = posX;
this.posY = posY;
}
// update (dt) {}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "52958c6c-bab5-40a7-9e16-328fb1143a3a",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

66
assets/Script/NewMode.ts Normal file
View File

@ -0,0 +1,66 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const { ccclass, property } = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
@property
text: string = 'hello';
btnStatic: number = 0;
propName: string = "";
// LIFE-CYCLE CALLBACKS:
// onLoad () {}
start() {
for (let i = 0; i < cc.fx.GameConfig.NEW_LEVEL.length; i++) {
if ((cc.fx.GameConfig.GM_INFO.level + 1) == cc.fx.GameConfig.NEW_LEVEL[i].level) {
this.propName = cc.fx.GameConfig.NEW_LEVEL[i].name;
const path = 'Window_Prop/' + this.propName;
cc.resources.load(path, cc.SpriteFrame, (err, spriteFrame: cc.SpriteFrame) => {
if (err) {
console.error('动态加载背景图失败:', err);
return;
}
this.node.getChildByName("newmode").getChildByName("icon").getComponent(cc.Sprite).spriteFrame = spriteFrame;
})
break;
}
}
}
setMode(mode: number) {
this.btnStatic = mode;
let name = "GameScene";
if (mode == 1) {
name = "HomeScene";
}
cc.director.preloadScene(name, () => {
})
}
clickBtn() {
cc.fx.AudioManager._instance.playEffect("anniu_Big", null);
if (this.btnStatic == 1) {
cc.director.loadScene("HomeScene");
}
else if (this.btnStatic == 2) {
cc.director.loadScene("GameScene");
}
}
// update (dt) {}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "7fe14751-1506-4a48-a280-a049f84bb394",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,297 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const { ccclass, property } = cc._decorator;
@ccclass
export default class NumberToImage extends cc.Component {
@property(cc.SpriteAtlas)
fontUI: cc.SpriteAtlas = null;
@property(cc.SpriteAtlas)
fontUI2: cc.SpriteAtlas = null;
static font: any = null;
static font2: any = null;
static font3: any = null;
// LIFE-CYCLE CALLBACKS:
onLoad() {
if (this.fontUI != null) {
NumberToImage.font = this.fontUI;
NumberToImage.font2 = this.fontUI2;
}
}
//第一个参数 数字, 第二个参数 数字间距 第三个参数 占位宽度 第四个参数 目标节点
static numberToImageNodes(number, width, posX, name, targetNode: cc.Node, middle: boolean = false) {
const numStr = number.toString();
let cha = 0;
if (number > 99) cha = -posX
else if (number < 10) cha = posX
if (targetNode.children.length > 0)
targetNode.removeAllChildren();
const digitNodes: cc.Node[] = [];
for (let i = 0; i < numStr.length; i++) {
const digit = parseInt(numStr[i], 10);
const node = new cc.Node();
const sprite = node.addComponent(cc.Sprite);
sprite.spriteFrame = this.font._spriteFrames[name + digit + ""];
digitNodes.push(node);
}
// 计算总宽度
const totalWidth = (numStr.length - 1) * width + (digitNodes[0]?.width || 0);
if (middle) {
// 计算居中的起始位置
const startX = -totalWidth / 2;
for (let i = 0; i < digitNodes.length; i++) {
const node = digitNodes[i];
node.x = startX + i * width;
if (targetNode) node.parent = targetNode;
}
} else {
for (let i = 0; i < digitNodes.length; i++) {
const node = digitNodes[i];
node.x = i * width + cha;
if (targetNode) node.parent = targetNode;
}
}
}
static numberToImageNodes2(number, width, posX, name, targetNode: cc.Node, right: boolean = false) {
const numStr = number.toString();
let cha = 0;
if (number > 99) cha = -posX
else if (number < 10) cha = posX
if (targetNode.children.length > 0)
targetNode.removeAllChildren();
const digitNodes: cc.Node[] = [];
for (let i = 0; i < numStr.length; i++) {
let digit = parseInt(numStr[i], 10);
const node = new cc.Node();
const sprite = node.addComponent(cc.Sprite);
if (numStr[i] == ":") digit = 10;
sprite.spriteFrame = this.font._spriteFrames[name + digit + ""];
digitNodes.push(node);
}
// 计算总宽度
// const totalWidth = (numStr.length - 1) * width + (digitNodes[0]?.width || 0);
// 计算总宽度,累加每个节点的宽度和间距
let totalWidth = 0;
for (let i = 0; i < digitNodes.length; i++) {
totalWidth += digitNodes[i].width;
if (i < digitNodes.length - 1) {
totalWidth += width;
}
}
if (right) {
// 新右对齐逻辑:从右向左排列
let currentX = 0; // 最右侧起点
for (let i = digitNodes.length - 1; i >= 0; i--) {
const node = digitNodes[i];
node.x = currentX - node.width;
currentX -= (node.width + width); // 向左累加宽度和间距
if (targetNode) node.parent = targetNode;
}
} else {
let currentX = cha;
for (let i = 0; i < digitNodes.length; i++) {
const node = digitNodes[i];
node.x = currentX;
currentX += node.width + width;
if (targetNode) node.parent = targetNode;
}
}
}
static numberToImageNodes3(number, width, posX, name, targetNode: cc.Node, middle: boolean = false) {
const numStr = number.toString();
let cha = 0;
if (number > 99) cha = -posX
else if (number < 10) cha = posX
if (targetNode.children.length > 0)
targetNode.removeAllChildren();
const digitNodes: cc.Node[] = [];
for (let i = 0; i < numStr.length; i++) {
const digit = parseInt(numStr[i], 10);
const node = new cc.Node();
const sprite = node.addComponent(cc.Sprite);
sprite.spriteFrame = this.font2._spriteFrames[name + digit + ""];
digitNodes.push(node);
}
// 计算总宽度
const totalWidth = (numStr.length - 1) * width + (digitNodes[0]?.width || 0);
if (middle) {
// 计算居中的起始位置
const startX = -totalWidth / 2;
for (let i = 0; i < digitNodes.length; i++) {
const node = digitNodes[i];
node.x = startX + i * width;
if (targetNode) node.parent = targetNode;
}
} else {
for (let i = 0; i < digitNodes.length; i++) {
const node = digitNodes[i];
node.x = i * width + cha;
if (targetNode) node.parent = targetNode;
}
}
}
static getTimeMargin(number, width, name, targetNode: cc.Node) {
let timeArr = [];
let total = 0;
total = number;
let hour = 0;
hour = parseInt((total / 3600) + "");//计算整数小时数
let afterHour = total - hour * 60 * 60;//取得算出小时数后剩余的秒数
let min = parseInt((afterHour / 60) + "");//计算整数分
let m = "" + min;
if (min < 10) m = "0" + min;
let afterMin = total - hour * 60 * 60 - min * 60;//取得算出分后剩余的秒数
let miao = afterMin + "";
if (afterMin < 10) miao = "0" + afterMin;
let result = m + miao;
for (let i = 0; i < result.length; i++) {
const digit = parseInt(result[i], 10);
timeArr.push(digit);
}
if (targetNode.children.length > 0) {
for (let i = 0; i < targetNode.children.length; i++) {
targetNode.children[i].getComponent(cc.Sprite).spriteFrame = this.font._spriteFrames[name + timeArr[i] + ""];
}
}
else {
for (let i = 0; i < 4; i++) {
const node = new cc.Node();
const sprite = node.addComponent(cc.Sprite);
const digit = timeArr[i];
// debugger;
sprite.spriteFrame = this.font._spriteFrames[name + digit + ""];
// 将节点添加到目标节点下
node.x = i * width;
if (i > 1) node.x += 35;
if (targetNode) node.parent = targetNode;
}
}
}
static getTimeMargin2(number, width, name, targetNode: cc.Node, middle: boolean = false) {
let timeArr = [];
let total = 0;
total = number;
let hour = 0;
hour = parseInt((total / 3600) + "");//计算整数小时数
let afterHour = total - hour * 60 * 60;//取得算出小时数后剩余的秒数
let min = parseInt((afterHour / 60) + "");//计算整数分
let m = "" + min;
if (min < 10) m = "0" + min;
let afterMin = total - hour * 60 * 60 - min * 60;//取得算出分后剩余的秒数
let miao = afterMin + "";
if (afterMin < 10) miao = "0" + afterMin;
// 将小时部分格式化为两位数
let h = "" + hour;
if (hour < 10) h = "0" + hour;
let result = m + miao;
// 拼接小时、分、秒
if (hour > 0)
result = h + m + miao;
for (let i = 0; i < result.length; i++) {
const digit = parseInt(result[i], 10);
timeArr.push(digit);
}
const digitNodes: cc.Node[] = [];
if (targetNode.children.length > 0) {
for (let i = 0; i < targetNode.children.length; i++) {
const node = targetNode.children[i];
const sprite = node.getComponent(cc.Sprite);
sprite.spriteFrame = this.font._spriteFrames[name + timeArr[i] + ""];
digitNodes.push(node);
}
}
else {
for (let i = 0; i < timeArr.length; i++) {
const node = new cc.Node();
const sprite = node.addComponent(cc.Sprite);
const digit = timeArr[i];
sprite.spriteFrame = this.font._spriteFrames[name + digit + ""];
digitNodes.push(node);
}
}
// 计算总宽度
const totalWidth = (timeArr.length - 1) * width + (digitNodes[0]?.width || 0);
if (middle) {
// 计算居中的起始位置
const startX = -totalWidth / 2;
for (let i = 0; i < digitNodes.length; i++) {
const node = digitNodes[i];
node.x = startX + i * width;
if (i > 1) node.x += 20;
if (i > 3) node.x += 20;
if (targetNode) node.parent = targetNode;
}
} else {
for (let i = 0; i < digitNodes.length; i++) {
const node = digitNodes[i];
node.x = i * width;
if (i > 1) node.x += 20;
if (i > 3) node.x += 20;
if (targetNode) node.parent = targetNode;
}
}
}
// static calculateAndConvert(num1: number, num2: number, operator: '+' | '-' | '*' | '/', spriteFrames: SpriteFrame[]): Node[] {
// let result: number;
// switch (operator) {
// case '+':
// result = num1 + num2;
// break;
// case '-':
// result = num1 - num2;
// break;
// case '*':
// result = num1 * num2;
// break;
// case '/':
// result = num1 / num2;
// break;
// default:
// throw new Error('不支持的运算符');
// }
// // 处理结果为小数的情况,这里简单取整
// result = Math.floor(result);
// return this.numberToImageNodes(result, spriteFrames);
// }
// update (dt) {}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "669f44ae-4a5f-4e46-a6b0-05c6f008da46",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

144
assets/Script/Pause.ts Normal file
View File

@ -0,0 +1,144 @@
// // Learn TypeScript:
// // - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// // Learn Attribute:
// // - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// // Learn life-cycle callbacks:
// // - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
// const {ccclass, property} = cc._decorator;
// @ccclass
// export default class Pause extends cc.Component {
// static _instance: any;
// time: number = 0;
// @property(cc.Node)
// music: cc.Node = null;
// @property(cc.Node)
// effect: cc.Node = null;
// @property(cc.Node)
// vibrate: cc.Node = null;
// @property(cc.SpriteFrame)
// open: cc.SpriteFrame = null;
// @property(cc.SpriteFrame)
// close: cc.SpriteFrame = null;
// // mapInfo: number[][] = [];
// musicState: boolean = true;
// effectState: boolean = true;
// vibrateState: boolean = true;
// onLoad () {
// if(cc.fx.GameConfig.GM_INFO.musicOpen){
// this.music.getComponent(cc.Sprite).spriteFrame = this.open;
// this.music.x = 278;
// }
// else{
// this.music.getComponent(cc.Sprite).spriteFrame = this.close;
// this.music.x = 161;
// }
// if(cc.fx.GameConfig.GM_INFO.effectOpen){
// this.effect.getComponent(cc.Sprite).spriteFrame = this.open;
// this.effect.x = 278;
// }
// else{
// this.effect.getComponent(cc.Sprite).spriteFrame = this.close;
// this.effect.x = 161;
// }
// if(cc.fx.GameConfig.GM_INFO.vibrateOpen){
// this.vibrate.getComponent(cc.Sprite).spriteFrame = this.open;
// this.vibrate.x = 278;
// }
// else{
// this.vibrate.getComponent(cc.Sprite).spriteFrame = this.close;
// this.vibrate.x = 161;
// }
// this.musicState = cc.fx.GameConfig.GM_INFO.musicOpen;
// this.effectState = cc.fx.GameConfig.GM_INFO.effectOpen;
// this.vibrateState = cc.fx.GameConfig.GM_INFO.vibrateOpen;
// }
// start () {
// }
// init(time){
// }
// clickMusic(){
// if(this.musicState){
// this.musicState = false;
// cc.fx.GameConfig.GM_INFO.musicOpen = this.musicState;
// this.setMusicConfig();
// this.music.runAction(cc.sequence(cc.spawn(cc.moveTo(0.05, cc.v2(161,this.music.y)), cc.fadeOut(0.05)),cc.callFunc(()=>{
// this.music.getComponent(cc.Sprite).spriteFrame = this.close;
// }),cc.fadeIn(0.1)))
// cc.fx.AudioManager._instance.stopMusic();
// }
// else{
// this.musicState = true;
// cc.fx.GameConfig.GM_INFO.musicOpen = this.musicState;
// this.setMusicConfig();
// this.music.runAction(cc.sequence(cc.spawn(cc.moveTo(0.05, cc.v2(278,this.music.y)), cc.fadeOut(0.05)),cc.callFunc(()=>{
// this.music.getComponent(cc.Sprite).spriteFrame = this.open;
// }),cc.fadeIn(0.1)))
// cc.fx.AudioManager._instance.playMusicGame();
// }
// }
// setMusicConfig(){
// let audioInfo = {
// "musicOpen": cc.fx.GameConfig.GM_INFO.musicOpen, //音乐
// "effectOpen": cc.fx.GameConfig.GM_INFO.effectOpen, //音效
// "vibrateOpen": cc.fx.GameConfig.GM_INFO.vibrateOpen, //震动
// }
// cc.fx.StorageMessage.setStorage("music",audioInfo);
// }
// clickEffect(){
// if(this.effectState){
// this.effectState = false;
// cc.fx.GameConfig.GM_INFO.effectOpen = this.effectState;
// this.setMusicConfig();
// this.effect.runAction(cc.sequence(cc.spawn(cc.moveTo(0.05, cc.v2(161,this.effect.y)), cc.fadeOut(0.05)),cc.callFunc(()=>{
// this.effect.getComponent(cc.Sprite).spriteFrame = this.close;
// }),cc.fadeIn(0.1)))
// }
// else{
// this.effectState = true;
// cc.fx.GameConfig.GM_INFO.effectOpen = this.effectState;
// this.setMusicConfig();
// this.effect.runAction(cc.sequence(cc.spawn(cc.moveTo(0.05, cc.v2(278,this.effect.y)), cc.fadeOut(0.05)),cc.callFunc(()=>{
// this.effect.getComponent(cc.Sprite).spriteFrame = this.open;
// }),cc.fadeIn(0.1)))
// }
// }
// clickVibrate(){
// if(this.vibrateState){
// this.vibrateState = false;
// cc.fx.GameConfig.GM_INFO.vibrateOpen = this.vibrateState;
// this.setMusicConfig();
// this.vibrate.runAction(cc.sequence(cc.spawn(cc.moveTo(0.05, cc.v2(161,this.vibrate.y)), cc.fadeOut(0.05)),cc.callFunc(()=>{
// this.vibrate.getComponent(cc.Sprite).spriteFrame = this.close;
// }),cc.fadeIn(0.1)))
// }
// else{
// this.vibrateState = true;
// cc.fx.GameConfig.GM_INFO.vibrateOpen = this.vibrateState;
// this.setMusicConfig();
// this.vibrate.runAction(cc.sequence(cc.spawn(cc.moveTo(0.05, cc.v2(278,this.vibrate.y)), cc.fadeOut(0.05)),cc.callFunc(()=>{
// this.vibrate.getComponent(cc.Sprite).spriteFrame = this.open;
// }),cc.fadeIn(0.1)))
// }
// }
// // update (dt) {}
// }

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "aca4abad-df73-42bc-80b4-ca0dc9998d21",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

34
assets/Script/Reduce.ts Normal file
View File

@ -0,0 +1,34 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const {ccclass, property} = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property({type: [cc.SpriteFrame], tooltip:"方块颜色图片"})
Block_Color : Array<cc.SpriteFrame> = [];
@property(cc.Label)
level: cc.Label = null;
// LIFE-CYCLE CALLBACKS:
onLoad () {
}
start () {
}
// update (dt) {}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "ca599214-e611-4461-8af3-a0de7d60ea53",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

404
assets/Script/Revive.ts Normal file
View File

@ -0,0 +1,404 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html
import JiaZai from "./JiaZai";
import MapConroler from "./Map";
import Utils from "./module/Pay/Utils";
import NumberToImage from "./NumberToImage";
import SceneManager from "./SceneManager";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";
const { ccclass, property } = cc._decorator;
@ccclass
export default class Revive extends cc.Component {
@property(cc.Node)
btn_Touch: boolean = false;
// LIFE-CYCLE CALLBACKS:
private onShowListener: () => void;
private iosPrice: number = 0;
private iosProductId: string = "";
private iosCount: number = 1;
public home: number = 0;
onLoad() {
this.btn_Touch = true;
// 检测微信小游戏切到后台
}
onShow() {
if (cc.sys.platform === cc.sys.WECHAT_GAME) {
console.log("从后台进入前台订单号:", cc.fx.GameConfig.GM_INFO.iosReviveOrder);
if (cc.fx.GameConfig.GM_INFO.iosReviveOrder != null && cc.fx.GameConfig.GM_INFO.iosReviveOrder != "") {
console.log("有苹果订单号,开始轮训");
const iosReviveOrder = cc.fx.GameConfig.GM_INFO.iosReviveOrder;
this.openLoad();
this.btn_Touch = true;
Utils.getIosPayInfo(iosReviveOrder,
(data) => {
console.log("获得轮训结果:", data);
const iosID = data.data?.payment_name || this.iosProductId;
let iosAmount = data.data?.goodsPrice || this.iosPrice;
iosAmount = parseInt(iosAmount);
if (data.code == 1) {
console.log("购买成功");
let name = "购买金币道具:" + iosID;
console.log("引力付费透传", iosAmount, iosReviveOrder, name);
MiniGameSdk.API.yinli_Pay(iosAmount, iosReviveOrder, name)
this.closeLoad();
this.btn_Touch = true;
console.log("_________正式发货");
MiniGameSdk.API.showToast("充值成功");
cc.fx.GameTool.shopBuy(iosID, false);
this.revivew()
if (iosID == "reborn_Gift") {
this.buyGift();
}
cc.fx.GameConfig.GM_INFO.iosReviveOrder = null;
//console.log("充值成功获得金币");
if (this.node.parent.parent.parent.parent.parent.getComponent("SceneManager")) {
this.node.parent.parent.parent.parent.parent.getComponent("SceneManager").updateCoin();
}
}
else if (data.code == 0) {
console.log("用户自己取消充值");
MiniGameSdk.API.showToast("充值失败");
this.closeLoad();
this.btn_Touch = true;
const dataFail = {
outTradeNo: iosReviveOrder,
pay_amount: iosAmount,
payment_name: iosID,
payment_num: this.iosCount,
type: "ios",
fail_reason: "用户取消充值",
}
cc.fx.GameTool.shushu_Track("payment_fail", dataFail);
cc.fx.GameConfig.GM_INFO.iosReviveOrder = null;
}
else if (data.code == 2) {
this.closeLoad();
this.btn_Touch = true;
console.log("轮训超时");
MiniGameSdk.API.showToast("请检查网络,如充值成功,请重新登录领取", 4);
const dataFail = {
outTradeNo: iosReviveOrder,
pay_amount: iosAmount,
payment_name: iosID,
payment_num: this.iosCount,
type: "ios",
fail_reason: "用户充值后,轮训结果超时",
}
cc.fx.GameTool.shushu_Track("payment_fail", dataFail);
this.openConfirmBox();
}
this.btn_Touch = true;
})
}
}
}
start() {
if (cc.fx.GameConfig.GM_INFO.revive == 1) {
this.node.active = false;
}
}
init() {
this.addListener();
this.btn_Touch = true;
if (cc.fx.GameConfig.GM_INFO.revive == 1) {
this.node.active = false;
}
}
addListener() {
if (cc.sys.platform === cc.sys.WECHAT_GAME) {
// 定义监听函数
this.onShowListener = () => {
this.onShow();
};
//@ts-ignore
wx.onShow(this.onShowListener);
}
}
//购买
buyGift() {
Utils.rebornGift(1, (data) => {
console.log("购买'✅ ", data.code);
if (data.code == 1) {
}
})
// update (dt) {}
}
//发奖励
revivew() {
cc.fx.GameConfig.GM_INFO.revive = 1;
MapConroler._instance.setPropNum();
const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
const jiazaiComp = jiazaiNode.getComponent(JiaZai);
if (jiazaiComp) {
setTimeout(() => {
jiazaiComp.updateCoin();
}, 300);
} else {
console.log("无法获取JiaZai组件");
}
let shop = cc.find("Canvas/shop");
if (shop) {
let shopComp = shop.getComponent("shop");
if (shopComp) {
shopComp.openShop();
}
}
setTimeout(() => {
this.node.active = false;
}, 200);
MapConroler._instance.runRewiveCopy();
}
buyProduct(customData) {
// cc.fx.GameTool.shopBuy("revive", false);
// MapConroler._instance.setPropNum();
if (!this.btn_Touch) {
return;
}
this.btn_Touch = false;
const productId = "reborn_Gift";
let id = "10011";
let price = 100;
let count = 1;
id = productId;
switch (productId) {
case "reborn_Gift":
price = 600;
break;
}
console.log("获得商品id:", id, count, price);
// 判断设备系统
let systemType = "Android";
try {
//@ts-ignore
const systemInfo = wx.getSystemInfoSync();
if (systemInfo.platform === 'ios') {
systemType = "ios";
}
} catch (e) {
console.error('获取系统信息失败', e);
}
// Utils.GoKEFu();
if (systemType == "ios") {
// MiniGameSdk.API.showToast("IOS系统暂不支持支付");
// this.btn_Touch = true;
this.openLoad();
this.btn_Touch = true;
let iosPayInfo = {
price: price,
payment_name: productId,
payment_count: 1,
}
this.iosPrice = price;
this.iosProductId = productId;
this.iosCount = 1;
Utils.GoKEFu(iosPayInfo, (res) => {
if (res == "success") {
console.log("客服回话成功");
}
else {
console.log("客服回话失败");
this.closeLoad();
}
});
}
else {
// MiniGameSdk.API.showToast("充值成功");
// cc.fx.GameTool.shopBuy(productId, false);
// setTimeout(() => {
// if (productId == "unlimited_health_bundle_1" ||
// productId == "unlimited_health_bundle_2" ||
// productId == "unlimited_health_bundle_3"
// ) {
// console.log("触发————————updatePower");
// this.updatePower();
// }
// }, 500);
this.openLoad();
this.btn_Touch = true;
console.log("7.14_____________________", "调用充值接口");
Utils.buyProp(id, count, price, systemType, productId, (res) => {
console.log("获得充值结果", res);
if (res == null) {
MiniGameSdk.API.showToast("充值失败");
this.btn_Touch = true;
const dataFail = {
outTradeNo: Utils.outTradeNo,
pay_amount: price,
payment_name: productId,
payment_num: 1,
type: systemType,
fail_reason: "网络异常,没有拉起支付",
}
cc.fx.GameTool.shushu_Track("payment_fail", dataFail);
this.closeLoad();
return;
}
else if (res.err) {
MiniGameSdk.API.showToast("充值失败");
//console.log(res);
this.btn_Touch = true;
let name = "支付拉起失败";
if (res.errCode == -2) {
name = "用户取消充值";
}
const dataFail = {
outTradeNo: Utils.outTradeNo,
pay_amount: price,
payment_name: productId,
payment_num: 1,
type: systemType,
fail_reason: name,
}
cc.fx.GameTool.shushu_Track("payment_fail", dataFail);
this.closeLoad();
return;
}
else {
Utils.getPayInfo((data) => {
console.log("7.14_______________充值成功,准备轮训");
console.log("获得轮训结果:", data);
this.closeLoad();
if (data.data.pay_state == 1) {
this.btn_Touch = true;
MiniGameSdk.API.showToast("取消充值");
const dataFail2 = {
outTradeNo: Utils.outTradeNo,
pay_amount: price,
payment_name: productId,
payment_num: 1,
type: systemType,
fail_reason: "用户取消支付",
}
cc.fx.GameTool.shushu_Track("payment_fail", dataFail2);
}
else if (data.data.pay_state == 2) {
this.btn_Touch = true;
// const dataSuccess = {
// outTradeNo: Utils.outTradeNo,
// pay_amount: price,
// payment_name: productId,
// payment_num: 1,
// type: systemType,
// }
// cc.fx.GameTool.shushu_Track("payment", dataSuccess);
let name = "购买金币道具:" + productId;
console.log("引力付费透传", price, Utils.outTradeNo, name);
MiniGameSdk.API.yinli_Pay(price, Utils.outTradeNo, name)
console.log("7.14_______________充值成功,轮训成功,准备发货");
Utils.setPayInfo(
(res) => {
console.log("设置轮训结果:", res);
if (res.code === 1) {
console.log("7.14_________正式发货");
MiniGameSdk.API.showToast("充值成功");
cc.fx.GameTool.shopBuy(productId, false);
this.revivew();
if (productId == "reborn_Gift") {
this.buyGift();
}
//console.log("充值成功获得金币");
}
else {
MiniGameSdk.API.showToast("网络异常,充值奖励将在登录后再次发放");
const dataFail4 = {
outTradeNo: Utils.outTradeNo,
pay_amount: price,
payment_name: productId,
payment_num: 1,
type: systemType,
fail_reason: "成功付款,但是发货时请求服务器失败,充值成功未发货",
}
cc.fx.GameTool.shushu_Track("payment_fail", dataFail4);
}
if (this.node.parent.parent.parent.parent.parent.getComponent("SceneManager")) {
this.node.parent.parent.parent.parent.parent.getComponent("SceneManager").updateCoin();
}
}, Utils.outTradeNo)
}
else {
const dataFail3 = {
outTradeNo: Utils.outTradeNo,
pay_amount: price,
payment_name: productId,
payment_num: 1,
type: systemType,
fail_reason: "拉起支付后,付款时网络异常付款失败",
}
cc.fx.GameTool.shushu_Track("payment_fail", dataFail3);
this.btn_Touch = true;
if (this.node.parent.parent.parent.parent.parent.getComponent("SceneManager")) {
this.node.parent.parent.parent.parent.parent.getComponent("SceneManager").updateCoin();
}
}
})
}
});
}
}
openLoad() {
this.node.parent.parent.parent.parent.parent.getChildByName("Loading").active = true;
this.node.parent.parent.parent.parent.parent.getChildByName("Loading").getChildByName("load").stopAllActions();
this.node.parent.parent.parent.parent.parent.getChildByName("Loading").getChildByName("load").runAction(cc.rotateTo(2, 1080).repeatForever());
}
closeLoad() {
this.node.parent.parent.parent.parent.parent.getChildByName("Loading").active = false;
}
offShow() {
if (cc.fx.GameConfig.GM_INFO.revive == 0) {
return;
}
// 移除 wx.onShow 监听器
if (cc.sys.platform === cc.sys.WECHAT_GAME && this.onShowListener) {
console.log("复活移除监听");
//@ts-ignore
wx.offShow(this.onShowListener);
console.log("🔥🔥🔥🔥🔥🔥🔥🔥");
}
}
openConfirmBox() {
let ConfirmBox = this.node.parent.getChildByName("ConfirmBox");
ConfirmBox.active = true;
this.closeLoad();
}
closeConfirmBox() {
let ConfirmBox = this.node.parent.getChildByName("ConfirmBox");
ConfirmBox.active = false;
}
//再次领取奖励
againGet() {
this.closeConfirmBox();
this.onShow();
}
onDestroy() {
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "cf2259fd-d55a-47c1-9f75-fef608a12261",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

193
assets/Script/Reward.ts Normal file
View File

@ -0,0 +1,193 @@
import NumberToImage from "./NumberToImage";
const { ccclass, property, requireComponent } = cc._decorator;
@ccclass
export default class Reward extends cc.Component {
@property(cc.Prefab)
rewardNode: cc.Prefab = null;
actionOver: boolean;
speedTime: number = 50;
private originalTimeScale: number = 1; // 记录原始时间缩放比例
callBack: Function;
onLoad() {
// 为节点添加点击事件监听器
this.speedTime = 50;
}
start() {
// ... 已有代码 ...
this.node.on(cc.Node.EventType.TOUCH_END, this.onNodeClick, this);
}
/**
*
*/
onNodeClick() {
// console.log('Reward 节点被点击了', this.actionOver);
// 这里可以添加点击后的具体逻辑
if (this.actionOver == true) {
if (this.callBack != null) {
this.callBack();
}
this.node.destroy();
}
else {
// 游戏整体加速
// this.speedUpGame();
}
}
speedUpGame() {
this.speedTime = 0;
this.originalTimeScale = cc.director.getScheduler().getTimeScale(); // 记录原始时间缩放比例
cc.director.getScheduler().setTimeScale(10); // 加速到 2 倍速
// 在奖励节点创建完成后恢复正常速度
const checkCompletion = () => {
if (this.actionOver) {
cc.director.getScheduler().setTimeScale(this.originalTimeScale); // 恢复原始时间缩放比例
} else {
setTimeout(checkCompletion, 50); // 每隔 100 毫秒检查一次
}
};
checkCompletion();
}
/**
*
* @param data
*/
init(data, callBack?: Function) {
this.actionOver = false;
if (callBack) this.callBack = callBack;
else this.callBack = null;
if (!data) {
this.actionOver = true;
this.node.destroy();
return;
}
const num = Math.min(data.length, 9); // 确保 num 不超过 9
const spacing = 10; // 间隔,默认 10
if (this.rewardNode && num > 0) {
// 获取单个 rewardNode 的宽度和高度
const tempNode = cc.instantiate(this.rewardNode);
const nodeWidth = tempNode.width;
const nodeHeight = tempNode.height;
tempNode.destroy();
// 定义每一行的节点数量
const rowCounts: number[] = [];
if (num <= 3) {
rowCounts.push(num);
} else if (num === 4) {
rowCounts.push(2, 2);
} else if (num === 5) {
rowCounts.push(3, 2);
} else if (num === 6) {
rowCounts.push(3, 3);
} else if (num === 7) {
rowCounts.push(3, 3, 1);
} else if (num === 8) {
rowCounts.push(3, 3, 2);
} else if (num === 9) {
rowCounts.push(3, 3, 3);
}
// 计算总高度
const rows = rowCounts.length;
const totalHeight = (nodeHeight * rows) + (spacing * (rows - 1));
// 计算起始位置的 y 坐标
const startY = totalHeight / 2 - nodeHeight / 2;
let index = 0;
const createNodeWithDelay = (row: number, col: number) => {
setTimeout(() => {
const rewardNode = cc.instantiate(this.rewardNode);
if (this.node) rewardNode.parent = this.node;
// 计算当前行的总宽度
// let startX = 0;
// if (row === 0) {
// const totalWidth = (nodeWidth * rowCounts[row]) + (spacing * (rowCounts[row] - 1));
// startX = -totalWidth / 2 + nodeWidth / 2;
// } else {
// startX = -((nodeWidth * 3) + (spacing * 2)) / 2 + nodeWidth / 2;
// }
// 修复:统一使用当前行的节点数量计算起始位置
const totalWidth = (nodeWidth * rowCounts[row]) + (spacing * (rowCounts[row] - 1));
const startX = -totalWidth / 2 + nodeWidth / 2;
// 计算每个节点的 x 和 y 位置
const xPos = startX + (col * (nodeWidth + spacing));
const yPos = startY - (row * (nodeHeight + spacing));
rewardNode.setPosition(xPos, yPos);
// 查找 rewardNode 的子节点 icon
const iconNode = rewardNode.getChildByName('icon');
iconNode.getChildByName(data[index].type).active = true;
let label = rewardNode.getChildByName('label')
if (data[index].type == 'coin')
NumberToImage.numberToImageNodes(data[index].count, 45, 5, "coins", label, true);
else if (data[index].type == 'infinite_health') {
NumberToImage.getTimeMargin2(data[index].count, 45, "coins", label, true);
if (data[index].count > 3600) label.x -= 10;
rewardNode.getChildByName('xnode').opacity = 1;
}
else {
NumberToImage.numberToImageNodes(data[index].count, 50, 15, "coins", label, true);
rewardNode.getChildByName('xnode').opacity = 0;
label.x += 20;
}
rewardNode.getChildByName('label').active = false;
if (iconNode) {
cc.tween(iconNode)
.to(0.2, { scale: 1.1 })
.to(0.1, { scale: 0.9 })
.to(0.05, { scale: 1 })
.delay(0.1)
.call(() => {
rewardNode.getChildByName('label').active = true;
if (rewardNode.getChildByName('xnode').opacity == 1) {
rewardNode.getChildByName('xnode').opacity = 0;
let name = "icon1";
if (rewardNode.getChildByName('label').children.length > 4) name = "icon2";
iconNode.getChildByName('infinite_health').getChildByName(name).active = true;
}
else if (rewardNode.getChildByName('xnode').opacity != 255) {
rewardNode.getChildByName('xnode').active = true;
rewardNode.getChildByName('xnode').opacity = 255;
}
})
.start();
}
index++;
if (index == data.length) {
setTimeout(() => {
this.actionOver = true;
}, 500);
}
if (index < data.length) {
const nextCol = col + 1;
if (nextCol < rowCounts[row]) {
createNodeWithDelay(row, nextCol);
} else {
createNodeWithDelay(row + 1, 0);
}
}
}, index * this.speedTime); // 每个节点间隔 0.1 秒
};
createNodeWithDelay(0, 0);
}
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "f30d38a9-33b7-4fe8-9b9b-4ed6fd2f6c99",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,502 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
import MapConroler from "./Map";
import NumberToImage from "./NumberToImage";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";
const { ccclass, property } = cc._decorator;
@ccclass
export default class SceneManager extends cc.Component {
// 缓存 shop 预制体
private static cachedShopPrefab: cc.Prefab | null = null;
// 缓存 shop 节点
private shopNode: cc.Node | null = null;
// 缓存 reward 预制体
private static cachedRewardPrefab: cc.Prefab | null = null;
// 缓存 reward 奖励窗口 节点
private RewardNode: cc.Node | null = null;
//缓存月卡
private static cachedMonthlyCardPrefab: cc.Prefab | null = null;
// 缓存月卡节点
private monthlyCardNode: cc.Node | null = null;
@property(cc.Label)
label: cc.Label = null;
@property
text: string = 'hello';
@property(cc.Node)
freeze: cc.Node = null;
@property(cc.Node)
hammer: cc.Node = null;
@property(cc.Node)
magic_wand: cc.Node = null;
@property(cc.Node)
pause: cc.Node = null;
@property(cc.Node)
level: cc.Node = null;
//time 弹窗的金币数
@property(cc.Node)
timeCoin: cc.Node = null;
//赢了win金币数
@property(cc.Node)
winCoin: cc.Node = null;
@property({ type: [cc.Prefab], tooltip: "方块数组" })
Block_Array: Array<cc.Prefab> = [];
@property({ type: [cc.Prefab], tooltip: "墙壁数组" })
Wall_Prefab: Array<cc.Prefab> = [];
particleEffects: cc.ParticleAsset[];
// @property({type: [cc.ParticleSystem], tooltip:"粒子数组"})
// particleEffects : Array<cc.ParticleSystem> = [];
load1: boolean = false;
load2: boolean = false;
load3: boolean = false;
btnName: string = '';
callBack: any;
share_time: boolean = true;
// LIFE-CYCLE CALLBACKS:
onLoad() {
cc.game.setFrameRate(63);
this.changeBg();
// 预加载 shop 预制体
if (!SceneManager.cachedShopPrefab) {
cc.assetManager.loadBundle('shop', (err: Error, bundle: cc.AssetManager.Bundle) => {
if (err) {
cc.error(err.message || err);
return;
}
bundle.load('prefab/shop', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
if (err) {
cc.error(err.message || err);
return;
}
SceneManager.cachedShopPrefab = prefab;
});
bundle.load('prefab/RewardWindow', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
if (err) {
cc.error(err.message || err);
return;
}
SceneManager.cachedRewardPrefab = prefab;
});
bundle.load('prefab/monthlyCard', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
if (err) {
cc.error(err.message || err);
return;
}
SceneManager.cachedMonthlyCardPrefab = prefab;
});
});
}
setTimeout(() => {
cc.director.preloadScene("HomeScene", (err) => {
if (err) {
// console.error('预加载 HomeScene 场景失败:', err);
return;
}
// console.log('成功预加载 HomeScene 场景');
});
}, 1000);
}
//更新关卡获得金币
updateWinCoin() {
console.log("更新关卡获得金币");
let winCoin = 40;
winCoin = winCoin * cc.fx.GameConfig.GM_INFO.doubleCoin;
if (winCoin > 0) {
NumberToImage.numberToImageNodes(winCoin, 50, 8, "time_", this.winCoin, false);
} else {
this.winCoin.active = false;
}
}
changeBg() {
let number = Math.floor(Math.random() * 8) + 1;
const path = 'bg/bg' + number;
cc.resources.load(path, cc.SpriteFrame, (err, spriteFrame: cc.SpriteFrame) => {
if (err) {
console.error('动态加载背景图失败:', err);
return;
}
this.node.getChildByName("Game").getChildByName("bg").getComponent(cc.Sprite).spriteFrame = spriteFrame;
})
let levelName = (cc.fx.GameConfig.GM_INFO.level + 1);
if (cc.fx.GameConfig.GM_INFO.otherLevel > 0) {
levelName = cc.fx.GameConfig.GM_INFO.otherLevel;
}
NumberToImage.numberToImageNodes(levelName, 43, 15, "level_", this.level, true);
//time金币数量
NumberToImage.numberToImageNodes(1000, 25, 15, "button_", this.timeCoin, false);
}
loadParticleEffects() {
const path = 'Particle';
cc.resources.loadDir(path, cc.ParticleAsset, (err, assets: cc.ParticleAsset[]) => {
if (err) {
console.error('动态加载粒子特效失败:', err);
return;
}
this.particleEffects = assets;
this.setParticleSort();
this.load3 = true;
//console.log('粒子特效加载成功,共加载了', this.particleEffects.length, '个粒子特效');
});
}
setWallPrefabSort() {
const order = ['down', 'downLeft', 'downRight', 'left', 'right', 'up', 'upLeft', 'upRight'];
this.Wall_Prefab.sort((a, b) => {
const indexA = order.indexOf(a.name);
const indexB = order.indexOf(b.name);
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
}
setParticleSort() {
const order = ['top', 'bot', 'rig', 'lef'];
this.particleEffects.sort((a, b) => {
// console.log(a.name.substr(0,3),b.name.substr(0,3));
const indexA = order.indexOf(a.name.substr(0, 3));
const indexB = order.indexOf(b.name.substr(0, 3));
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
}
setSort() {
this.Block_Array.sort((a, b) => {
// 从名称中提取数字部分
const numberA = parseInt(a.name.match(/\d+/)?.[0] || '0', 10);
const numberB = parseInt(b.name.match(/\d+/)?.[0] || '0', 10);
return numberA - numberB;
});
}
start() {
this.share_time = true;
}
startGame() {
cc.director.loadScene("HomeScene", (err) => {
if (err) {
console.error('加载 HomeScene 场景失败:', err);
} else {
// console.log('成功切换到 HomeScene 场景');
cc.director.loadScene("HomeScene");
}
});
}
returnHome() {
if (this.node.getChildByName("Pause").getChildByName("btn").getComponent("btnControl")._touch) {
this.closePause();
if (MapConroler._instance.gameStart == true) {
// MiniGameSdk.API.showToast("体力值减少");
if (MapConroler._instance.count_Time) {
let overTime = Date.now();
let count_Time = overTime - MapConroler._instance.count_Time;
let add_Time = MapConroler._instance.add_Time;
let data = {
time: count_Time,
add_Time: add_Time,
is_frenzy: MapConroler._instance.is_frenzy,
result: "give_up"
}
cc.fx.GameTool.shushu_Track("finish_stage", data);
let data2 = {
is_frenzy: MapConroler._instance.is_frenzy,
count: cc.fx.GameConfig.GM_INFO.winStreak
}
cc.fx.GameTool.shushu_Track("hammer_frenzy", data2);
}
}
this.node.getChildByName("Pause").getChildByName("btn").getComponent("btnControl").setTouch(false);
cc.fx.AudioManager._instance.playEffect("zhuan1", null);
this.node.getChildByName("zhuanchang").active = true;
this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "up", false);
cc.director.preloadScene("HomeScene", (err, asset) => {
if (err) {
console.error('动态加载 Prefab 失败:', err);
return;
}
});
setTimeout(() => {
cc.director.loadScene("HomeScene");
}, 1200);
}
}
destroyNodesInFrames(nodes: cc.Node[], callback: () => void) {
const BATCH_SIZE = 10; // 每帧销毁的节点数量
let index = 0;
const destroyBatch = () => {
let count = 0;
while (index < nodes.length && count < BATCH_SIZE) {
const node = nodes[index];
if (node) {
node.active = false;
}
index++;
count++;
}
if (index < nodes.length) {
this.scheduleOnce(destroyBatch, 6);
} else {
callback();
}
};
destroyBatch();
}
// 改进后的切换场景方法
switchToEmptyScene() {
const allNodes = cc.director.getScene().children;
this.destroyNodesInFrames(allNodes, () => {
cc.director.loadScene("HomeScene");
});
}
openPause() {
cc.fx.AudioManager._instance.playEffect("anniu_little", null);
if (this.pause.getComponent("btnControl")._touch) {
this.pause.getComponent("btnControl").setTouch(false);
this.node.getChildByName("Pause").active = true;
let pauseNode = this.node.getChildByName("Pause").getChildByName("pause");
pauseNode.scale = 0.3;
cc.tween(pauseNode)
.to(0.2, { scale: 1.05 }, { easing: 'backOut' })
.to(0.15, { scale: 1.0 }, { easing: 'sineOut' })
.start();
MapConroler._instance.pause = true;
MapConroler._instance.stopBoom();
}
}
closeShop() {
if (this.shopNode) {
this.shopNode.active = false;
var pause = MapConroler._instance.iceTrue();
if (pause == false) {
MapConroler._instance.pause = false;
if (MapConroler._instance.gameStart == true) MapConroler._instance.startBoom();
}
}
}
closePause() {
cc.fx.AudioManager._instance.playEffect("anniu_little", null);
this.pause.getComponent("btnControl").setTouch(true);
this.node.getChildByName("Pause").active = false;
var pause = MapConroler._instance.iceTrue();
if (pause == false) {
MapConroler._instance.pause = false;
if (MapConroler._instance.gameStart == true) MapConroler._instance.startBoom();
}
}
openPropBuy(name) {
MapConroler._instance.pause = true;
MapConroler._instance.stopBoom();
this.btnName = name;
cc.fx.AudioManager._instance.playEffect("tanchuang", null);
let propWindow = this.node.getChildByName("Game").getChildByName("propWindow");
propWindow.active = true;
propWindow = propWindow.getChildByName("prop");
cc.fx.AudioManager._instance.playEffect("tanchuang", null);
let pauseNode = propWindow;
pauseNode.scale = 0.3;
cc.tween(pauseNode)
.to(0.2, { scale: 1.05 }, { easing: 'backOut' })
.to(0.15, { scale: 1.0 }, { easing: 'sineOut' })
.start();
propWindow.getChildByName("freeze").active = false;
propWindow.getChildByName("hammer").active = false;
propWindow.getChildByName("magic").active = false;
propWindow.getChildByName("buy_Btn").getComponent("btnControl").setTouch(true);
propWindow.getChildByName(name).active = true;
// if(name == "hammer"){
// propWindow.getChildByName("buy_Btn").getChildByName("hammer").active = true;
// propWindow.getChildByName("buy_Btn").getChildByName("nomal").active = false;
// }
// else{
// propWindow.getChildByName("buy_Btn").getChildByName("hammer").active = false;
// propWindow.getChildByName("buy_Btn").getChildByName("nomal").active = true;
// }
}
clickBtn() {
cc.fx.AudioManager._instance.playEffect("anniu_Big", null);
let propWindow = this.node.getChildByName("Game").getChildByName("propWindow").getChildByName("prop");
if (propWindow.getChildByName("buy_Btn").getComponent("btnControl")._touch) {
propWindow.getChildByName("buy_Btn").getComponent("btnControl").setTouch(false);
if (this.btnName == "freeze")
MapConroler._instance.buyFreeze();
else if (this.btnName == "hammer")
MapConroler._instance.buyHammer();
else if (this.btnName == "magic")
MapConroler._instance.buyMagic();
}
}
resetBtn() {
let propWindow = this.node.getChildByName("Game").getChildByName("propWindow").getChildByName("prop");
propWindow.getChildByName("buy_Btn").getComponent("btnControl").setTouch(true);
}
//打开商店
openShop() {
console.log("进入sceneManager openShop");
if (!SceneManager.cachedShopPrefab) {
cc.error('Shop prefab is not loaded yet.');
return;
}
MapConroler._instance.pause = true;
MapConroler._instance.stopBoom();
if (!this.shopNode) {
// 第一次使用,创建节点
this.shopNode = cc.instantiate(SceneManager.cachedShopPrefab);
this.node.addChild(this.shopNode);
this.shopNode.getComponent("shop").init();
} else {
// 非第一次使用,直接激活节点
this.shopNode.active = true;
this.shopNode.getComponent("shop").init();
}
// console.log("shopNode parent:", this.shopNode.parent);
}
//打开月卡
openMonthlyCard() {
if (!SceneManager.cachedMonthlyCardPrefab) {
cc.error('MonthlyCard prefab is not loaded yet.');
return;
}
if (!this.monthlyCardNode) {
// 第一次使用,创建节点
this.monthlyCardNode = cc.instantiate(SceneManager.cachedMonthlyCardPrefab);
this.node.addChild(this.monthlyCardNode);
this.monthlyCardNode.getComponent("monthlyCard").init();
this.monthlyCardNode.getComponent("monthlyCard").juwai = false;
} else {
// 非第一次使用,直接激活节点
this.monthlyCardNode.active = true;
this.monthlyCardNode.getComponent("monthlyCard").init();
this.monthlyCardNode.getComponent("monthlyCard").juwai = false;
}
}
updateCoin() {
MapConroler._instance.updateCoin();
}
closePropBuy(type) {
if (type == true) {
}
else {
var pause = MapConroler._instance.iceTrue();
if (pause == false) {
MapConroler._instance.pause = false;
if (MapConroler._instance.gameStart == true) MapConroler._instance.startBoom();
}
}
let freezeBtn = MapConroler._instance.node.parent.getChildByName("Bottom").getChildByName("timeBtn");
let hammerBtn = MapConroler._instance.node.parent.getChildByName("Bottom").getChildByName("destroyBtn");
let magicBtn = MapConroler._instance.node.parent.getChildByName("Bottom").getChildByName("magicBtn");
if (this.btnName == "freeze") freezeBtn.getComponent("btnControl").setTouch(true);
else if (this.btnName == "hammer") hammerBtn.getComponent("btnControl").setTouch(true);
else if (this.btnName == "magic") magicBtn.getComponent("btnControl").setTouch(true);
this.node.getChildByName("Game").getChildByName("propWindow").active = false;
}
openRewardWindow(data, callBack) {
console.log("_____________________打开奖励弹窗", data);
if (!SceneManager.cachedRewardPrefab) {
cc.error('Reward prefab is not loaded yet.');
return;
}
if (!this.RewardNode) {
// 第一次使用,创建节点
this.RewardNode = cc.instantiate(SceneManager.cachedRewardPrefab);
this.node.addChild(this.RewardNode);
this.RewardNode.zIndex = 99;
this.RewardNode.getComponent("Reward").init(data, callBack);
}
else {
this.RewardNode.destroy();
this.RewardNode = null;
this.RewardNode = cc.instantiate(SceneManager.cachedRewardPrefab);
this.node.addChild(this.RewardNode);
this.RewardNode.zIndex = 99;
this.RewardNode.getComponent("Reward").init(data, callBack);
}
this.RewardNode.zIndex = 1001;
}
shareFriend() {
if (this.share_time) {
this.share_time = false;
console.log("设置分享链接");
let timeStamp = Date.now();
let otherInfo = {
timeStamp: timeStamp,
otherLevel: (cc.fx.GameConfig.GM_INFO.level + 1),
}
cc.fx.StorageMessage.setStorage("otherLevel", otherInfo);
MiniGameSdk.API.shareGame();
setTimeout(() => {
this.share_time = true;
}, 5000);
}
}
update(dt) {
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "809984f5-0183-4d45-9751-c6c56f5d1eb9",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

13
assets/Script/Sdk.meta Normal file
View File

@ -0,0 +1,13 @@
{
"ver": "1.1.3",
"uuid": "93c9bdf3-8205-46e5-a8f1-3576b0dbc836",
"importer": "folder",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}

View File

@ -0,0 +1,29 @@
import { MiniGameSdk } from "./MiniGameSdk";
const { ccclass, property } = cc._decorator;
@ccclass
export class DouyinEntranceView extends cc.Component {
start() {
}
update(deltaTime: number) {
}
onCloseClick() {
this.node.active = false;
}
onNavigateToDouyinClick() {
MiniGameSdk.BytedanceSidebar.navigateToSidebar((success: boolean) => { // 跳转到抖音侧边栏
if (success) {
console.log('跳转成功');
} else {
console.log('跳转失败');
}
});
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "8a024faa-e4af-4cae-9c5c-693bee7120c1",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,338 @@
import { MiniGameSdk } from "./MiniGameSdk";
const { ccclass, property } = cc._decorator;
enum EWechatAD {
CUMSTOM_01 = 'adunit-f7c2417eb2c2e473'
}
@ccclass
export class MiniGameManager extends cc.Component {
@property(cc.Node)
entranceView: cc.Node = null;
/**
*
*
*
* @remarks
*
*
*
*
*/
private _id: any;
private _userData: any;
private static _instance: MiniGameManager;
static get instance(): MiniGameManager {
if (!MiniGameManager._instance) {
MiniGameManager._instance = new MiniGameManager();
}
return MiniGameManager._instance;
}
start() {
// 禁用游戏入口视图
// this.entranceView.active = false;
this.onGetLoginCode();
// 尝试获取游戏入口按钮,如果存在则直接返回,不进行后续操作
// let buttonEntrance = this.node.getChildByName('Btns')?.getChildByName('Button_EntranceView');
// if (buttonEntrance) {
// return;
// }
// 如果是字节跳动小游戏环境,检查侧边栏是否存在
if (MiniGameSdk.isBytedance()) {
//抖音环境,检测侧边栏存在
MiniGameSdk.BytedanceSidebar.checkSideBar((success: boolean) => {
// 根据侧边栏存在性激活或禁用游戏入口按钮
// buttonEntrance.active = success;
});
} else {
// 非抖音小游戏环境,直接激活游戏入口按钮
// 非抖音环境,正常显示按钮
// buttonEntrance.active = true;
}
// 设置监听器,以处理来自侧边栏的交互事件
MiniGameSdk.BytedanceSidebar.listenFromSidebar((success: boolean) => {
// 如果交互成功,显示奖励提示
if (success) {
MiniGameSdk.API.showToast('侧边栏奖励', 5);
}
});
}
update(deltaTime: number) {
}
/**
* 广
* 广广广广
* 广广MiniGameSdk.AdvertManager的实例方法来实现的
*
* @remarks
* 广
* 1. showBanner方法显示广告
* 2. 广
*
* 广使
*/
onShowBanner() {
// 加载指定广告位的横幅广告。
MiniGameSdk.AdvertManager.instance.loadBanner('adunit-4e7ef467e3eaab51');
// 默认方式显示横幅广告。
// 方法1默认调用
MiniGameSdk.AdvertManager.instance.showBanner();
// 示例:指定屏幕底部正中显示横幅广告。
// 方法2指定屏幕顶部或底部正中
// MiniGameSdk.AdvertManager.instance.showBanner('adunit-4e7ef467e3eaab51', MiniGameSdk.EAdBannerLocation.BOTTOM);
// 示例:通过坐标指定位置显示横幅广告。
// 方法2指定坐标
// MiniGameSdk.AdvertManager.instance.showBanner('adunit-4e7ef467e3eaab51', { top: 10, left: 10 });
}
/**
* 广
*
* MiniGameSdk.AdvertManager实例的方法广
* 广广
*
* @remarks
*
* 广AdvertManager的实现
*/
onHideBanner() {
MiniGameSdk.AdvertManager.instance.hideBanner();
}
/**
* 广
*
* MiniGameSdk.AdvertManager实例的方法广
* 使广广
* 广
*/
onShowInterstitial() {
MiniGameSdk.AdvertManager.instance.showInterstitial('adunit-eadd67851d3050ad');
}
/**
* 广广
* 广广广
* 广广
* 广
*/
onShowCustom() {
// 加载指定的自定义广告单元。
MiniGameSdk.AdvertManager.instance.loadCustom(EWechatAD.CUMSTOM_01);
// 展示已加载的自定义广告。
MiniGameSdk.AdvertManager.instance.showCustom(EWechatAD.CUMSTOM_01);
}
/**
* 广
*
* MiniGameSdk.AdvertManager.instance.hideCustom()广
* 广广
* 广
*/
onHideCustom() {
MiniGameSdk.AdvertManager.instance.hideCustom(EWechatAD.CUMSTOM_01);
}
/**
* 广
* MiniGameSdk.AdvertManager.instance.showVideo方法广广
*
* @remarks
* 广ID广广
* 广广
*/
onShowVideo() {
// 广告单元ID用于标识要显示的视频广告
// 广告单元ID的样例
//抖音形如: 1re3nfqkmy81m4m8ge
//微信形如: adunit-a7718f6e195e42fe
MiniGameSdk.AdvertManager.instance.showVideo('1re3nfqkmy81m4m8ge', (res: MiniGameSdk.EAdVideoResult, count: number) => {
// 输出用户观看的广告数量
console.log('用户看的视频广告个数是:', count);
// 根据用户观看广告的结果,执行不同的逻辑
switch (res) {
case MiniGameSdk.EAdVideoResult.ACCEPT:
// 用户完成了广告观看,显示奖励提示
MiniGameSdk.API.showToast('用户看完广告,可以奖励');
break;
case MiniGameSdk.EAdVideoResult.REJECT:
// 用户拒绝了广告观看,显示不奖励提示
MiniGameSdk.API.showToast('用户拒绝掉广告,不奖励');
break;
case MiniGameSdk.EAdVideoResult.ERROR:
// 广告播放发生错误,显示错误提示
MiniGameSdk.API.showToast('播放广告发生错误,不奖励');
break;
default:
// 其他情况,不作处理
break;
}
});
}
/**
*
*
* MiniGameSdk的API分享功能
* 广
*
* @remarks
* API依赖于特定的小游戏平台
*/
onShare() {
MiniGameSdk.API.shareAppToFriends('来玩游戏吧');
}
/**
* toast提示
*
* MiniGameSdk的API方法来显示一个简短的提示信息toast是一种轻量级的提示方式
* 使 '这是一个toast'
*/
onShowToast() {
MiniGameSdk.API.showToast('这是一个toast');
}
/**
*
*
* MiniGameSdk提供的API
*
*
* @remarks
*
*/
onVirbrate() {
MiniGameSdk.API.vibrate();
}
/**
*
*
* MiniGameSdk中的API重新启动游戏
*
*
* @remarks
*
*
* @returns
*/
onReboot() {
MiniGameSdk.API.reboot();
}
/**
* 退
* MiniGameSdk提供的API方法来触发退出操作
*
*/
onExit() {
MiniGameSdk.API.exit();
}
/**
*
*
* MiniGameSdk的API方法
* 便SDK接口交互
*
* @remarks
*
*/
onShowShareMenu() {
MiniGameSdk.API.showShareMenu();
}
/**
*
*
* ID
* 便
*
* 'xxx'使ID
*/
onNavigate() {
MiniGameSdk.API.navigateTo('xxx'); // xxx替换为你的小游戏id
}
/**
*
*
*
* 使
*/
onBytedanceEntranceView() {
// this.entranceView.active = true;
}
/**
*
*
*
*
*/
onGetLoginCode() {
// 调用MiniGameSdk的API登录方法传入一个回调函数处理登录结果
MiniGameSdk.API.login((code: string, anonymousCode: string) => {
// 打印微信或头条的登录代码
console.log('Wechat Or Bytedance Code:', code);
// 打印头条的匿名登录代码
// console.log('Bytedance Anonymous Code:', anonymousCode);
if (code) {
// cc.fx.GameTool.getUserId(code, data => this.setUserId(data));
}
});
}
// setUserId(data){
// cc.fx.GameConfig.GM_INFO.userId = data.data.userId;
// MiniGameSdk.API.getUserInfo(this.setUserInfo);
// }
// setUserInfo(data){
// console.log("获取到的用户信息",data.userInfo);
// var useData = {
// "gameId": cc.fx.GameConfig.GM_INFO.gameId,
// "userId": cc.fx.GameConfig.GM_INFO.userId,
// "nickName":data.userInfo.nickName,
// "pic": data.userInfo.avatarUrl
// }
// console.log("即将上传的用户信息:",cc.fx.GameConfig.GM_INFO.userId,data.userInfo.nickName,data.userInfo.avatarUrl);
// console.log("Post数据:",useData);
// cc.fx.GameTool.setUserInfo(useData,(res)=>{
// console.log("上传成功:",res);
// });
// }
/**
*
*
* MiniGameSdk的GameClub实例方法
*
*
*/
onCreateClub() {
// 配置俱乐部图标为绿色设置图标的位置为顶部200像素左侧0像素
MiniGameSdk.GameClub.instance.create(
MiniGameSdk.EGameClubIcon.GREEN,
{ top: 200, left: 0 },
{ width: 50, height: 50 });
// 显示游戏俱乐部图标
MiniGameSdk.GameClub.instance.show();
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "0d272a57-5428-450e-a8b9-1574c3d89951",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "c1af99dd-ee03-40f7-9609-d3887d0dd357",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "ff9bbc79-743c-47c9-8e26-683c1472454c",
"importer": "javascript",
"isPlugin": true,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

31
assets/Script/Uid.ts Normal file
View File

@ -0,0 +1,31 @@
const { ccclass, property, requireComponent } = cc._decorator;
@ccclass
export default class Uid extends cc.Component {
static _instance: any;
@property(cc.Label)
uid_Number: cc.Label = null;
onLoad() {
// 为节点添加点击事件监听器
if (Uid._instance == null) {
Uid._instance = this;
cc.game.addPersistRootNode(this.node);
}
else {
return;
}
if (cc.fx.GameConfig.GM_INFO.userId > 0) {
this.uid_Number.string = cc.fx.GameConfig.GM_INFO.userId + "";
}
}
start() {
// ... 已有代码 ...
}
}

10
assets/Script/Uid.ts.meta Normal file
View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "7ec7c31d-8d85-4008-9668-9a349e3fac1a",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

380
assets/Script/Wall.ts Normal file
View File

@ -0,0 +1,380 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
import MapConroler from "./Map";
import NumberToImage from "./NumberToImage";
const { ccclass, property } = cc._decorator;
export enum WallSpecial {
/*普通门*/
"普通门" = 0,
/*星星门*/
"星星门" = 1,
/*开关门*/
"开关门" = 2,
/*冻结门 */
"冻结门" = 3,
/*冻结门 */
"旋转门顺时针" = 4,
/*旋转门逆时针*/
"旋转门逆时针" = 5,
}
export enum WallType {
/*普通地块 */
"门横向下" = 0,
/*起点地块 */
"门横向上" = 1,
/*湿地 */
"门竖向右" = 2,
/*山峰 */
"门竖向左" = 3,
/*终点地块 */
"墙横向下" = 4,
/*息壤 */
"墙横向上" = 5,
/*加固 */
"墙竖向右" = 6,
/*加固 */
"墙竖向左" = 7,
}
export enum WallColor {
/*普通地块 */
"紫色" = 0,
/*湿地 */
"黄色" = 1,
/*山峰 */
"绿色" = 2,
/*终点地块 */
"蓝色" = 3,
/*息壤 */
"粉色" = 4,
/*加固 */
"橘黄色" = 5,
/*加固 */
"青色" = 6,
/*加固 */
"白色" = 7,
/*普通地块 */
"红色" = 8,
/*普通地块 */
"灰色" = 9,
}
@ccclass
export default class Wall extends cc.Component {
@property(cc.Label)
number: cc.Label = null;
@property({
tooltip: '墙或者门的方向',
type: cc.Enum(WallType),
})
type: WallType = WallType.;
@property({
tooltip: '墙或者门的方向',
type: cc.Enum(WallSpecial),
})
special: WallSpecial = WallSpecial.;
@property({
tooltip: '门的颜色',
type: cc.Enum(WallColor),
})
color: WallColor = WallColor.;
@property(cc.SpriteAtlas)
wall_SpriteFrames: cc.SpriteAtlas = null;
@property(cc.SpriteAtlas)
down_SpriteFrames: cc.SpriteAtlas = null;
@property(cc.Prefab)
freezeSpine: cc.Prefab = null;
posX: number;
posY: number;
direction: any;
wall_Info: any;
openNode: cc.Node;
revolvingNode: cc.Node;
freezeNode: cc.Node;
open: boolean;
freezeNumber: number;
num: number;
// LIFE-CYCLE CALLBACKS:
// onLoad () {}
start() {
// console.log(this.type);
}
jsonDeepClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj));
}
init(wall_Info, posX: number, posY: number, direction: any) {
this.wall_Info = this.jsonDeepClone(wall_Info);
// this.open = true;
if (wall_Info == null) {
this.posX = posX;
this.posY = posY;
if (direction) this.direction = direction;
// console.log("门方向赋值",direction);
if (direction == "up") {
this.node.parent.zIndex = 100 + this.posX - this.posY * 3;
}
else if (direction == "down" || direction == "right") {
this.node.parent.zIndex = 20 + this.posX - this.posY * 3;
}
else if (direction == "downleft" || direction == "downright" || direction == "rightup"
|| direction == "rightdown") {
this.node.parent.zIndex = 20 + this.posX - this.posY * 3;
}
else if (direction == "left" || direction == "leftup" || direction == "upleft") {
this.node.parent.zIndex = 70 + this.posX - this.posY * 3;
}
else if (direction == "leftdown" || direction == "upright") {
this.node.parent.zIndex = 100 + this.posX - this.posY * 3;
}
else this.node.parent.zIndex = 70 + this.posX - this.posY * 3;
MapConroler._instance.mapBlocksWall[this.posX][this.posY].getComponent("MapBlock").block_Id = "Wall";
//console.log(this.posX,this.posY,MapConroler._instance.mapBlocksWall[this.posX][this.posY].getComponent("MapBlock").block_Id);
// console.log(this.posX,this.posY,this.node.zIndex);
//this.node.getChildByName("num").getComponent(cc.Label).string = direction;
//this.node.getChildByName("num").getComponent(cc.Label).string = ":" + this.node.parent.zIndex;
}
if (wall_Info != null) {
this.color = this.wall_Info.color;
this.special = this.wall_Info.special;
this.num = this.wall_Info.num;
let name2 = "rotate" + this.wall_Info.length;
this.revolvingNode = this.node.parent.getChildByName("revolving").getChildByName(name2);
if (this.revolvingNode) {
this.revolvingNode.parent.zIndex = 999;
this.revolvingNode.active = false;
}
this.initType();
if (this.wall_Info.length > 0) {
this.initColor(this.wall_Info.length);
MapConroler._instance.wall_Pass.push(this);
}
else this.node.removeComponent("cc.Sprite");
if (this.posX != null) {
MapConroler._instance.mapBlocksWall[this.posX][this.posY].getComponent("MapBlock").block_Id = "Wall";
//console.log(this.posX,this.posY,MapConroler._instance.mapBlocksWall[this.posX][this.posY].getComponent("MapBlock").block_Id);
}
}
// setTimeout(() => {
// this.node.getChildByName("num").getComponent(cc.Label).string = ":" + this.node.parent.zIndex;
// }, 1000);
}
//创建门的颜色
initColor(length: number) {
let direction = this.node.parent.name;
let double = 0;
if (direction == "left" || direction == "right") {
double = 3;
}
// debugger;
if (this.wall_SpriteFrames) {
let name = this.color + "color" + (length + double);
var spriteFrame = this.wall_SpriteFrames._spriteFrames[name];
if (this.node.getComponent(cc.Sprite)) this.node.getComponent(cc.Sprite).spriteFrame = spriteFrame;
if (this.node.getChildByName("icon")) this.node.getChildByName("icon").getComponent(cc.Sprite).spriteFrame = spriteFrame;
}
if (this.down_SpriteFrames) {
let name2 = this.color + "down" + (length + double);
var downFrame = this.down_SpriteFrames._spriteFrames[name2];
this.node.parent.getChildByName("down").getComponent(cc.Sprite).spriteFrame = downFrame;
}
}
//创建特殊类型门
initType() {
switch (this.special) {
case WallSpecial.:
let star = cc.instantiate(MapConroler._instance.Block_Prop[this.special]);
star.parent = this.node.parent;
// console.log("门的方向",this.direction,"长度",this.wall_Info.length);
// star.scaleX = star.scaleY = 0.5;
if (this.wall_Info.length > 0) {
if (this.direction == "right" || this.direction == "left") {
star.children[this.wall_Info.length + 2].active = true;
}
else if (this.direction == "up" || this.direction == "down") {
star.children[this.wall_Info.length - 1].active = true;
}
}
star.setPosition(this.node.width / 2 + this.node.x, this.node.height / 2 + this.node.y);
break;
case WallSpecial.:
let name = "open" + this.wall_Info.length;
this.openNode = this.node.parent.getChildByName("open").getChildByName(name);
this.openNode.active = true;
if (this.wall_Info.lock == false) {
this.open = true;
this.openNode.children[0].scaleX *= 0.01;
this.openNode.children[1].scaleX *= 0.01;
}
else {
this.open = false;
}
break;
case WallSpecial.:
let freeze = "freeze" + this.wall_Info.length;
this.freezeNode = this.node.parent.getChildByName("freeze").getChildByName(freeze);
this.freezeNode.active = true;
if (this.wall_Info.freeze) {
this.freezeNumber = this.wall_Info.freeze;
NumberToImage.numberToImageNodes(this.freezeNumber, 20, 8, "lock_", this.freezeNode.getChildByName("num"), false);
}
break;
case WallSpecial.旋转门顺时针: case WallSpecial.:
if (this.wall_Info.length > 0) {
// let name2 = "rotate" + this.wall_Info.length;
// this.revolvingNode = this.node.parent.getChildByName("revolving").getChildByName(name2);
this.revolvingNode.active = true;
// if (this.special == WallSpecial.旋转门逆时针) {
// this.revolvingNode.children[0].scaleX = -this.revolvingNode.children[0].scaleX;
// }
}
break;
}
}
//播放星星门通过
playStarDoor() {
if (this.node.parent.getChildByName("star")) {
let star = this.node.parent.getChildByName("star");
for (let i = 0; i < star.children.length; i++) {
if (star.children[i].active == true) {
let starChild = star.children[i];
for (let j = 0; j < starChild.children.length; j++) {
starChild.children[j].active = true
starChild.children[j].getComponent(sp.Skeleton).setAnimation(1, "taopao1", false);
}
}
}
}
}
//改变开关门状态
changeLock() {
this.open = !this.open;
console.log("开关门状态改变", this.open);
if (!this.openNode.active) {
this.openNode.active = true;
}
let fill = this.openNode.children[0].scaleX == 1 ? 0.01 : 1;
if (this.openNode.children[0].scaleX < 0) fill = -fill;
// console.log("目标",fill);
cc.tween(this.openNode.children[0])
.to(0.3, { scaleX: this.openNode.children[0].scaleX < 0 ? -fill : fill })
.call(() => {
// console.log("左边完成");
})
.start();
cc.tween(this.openNode.children[1])
.to(0.3, { scaleX: this.openNode.children[1].scaleX < 0 ? -fill : fill })
.call(() => {
// console.log("右边完成");
})
.start();
}
changeFreeze() {
this.freezeNumber -= 1;
if (this.freezeNumber == 0) {
console.log(this.node.uuid);
// this.freezeNode.parent.active = false;
this.resetFreeze();
}
else {
NumberToImage.numberToImageNodes(this.freezeNumber, 20, 8, "lock_", this.freezeNode.getChildByName("num"), false);
}
}
downDoor() {
if (this.openNode) {
if (this.openNode.children[0].scaleX == 1)
return;
}
if (this.freezeNode) {
if (this.freezeNode.active == true)
return;
}
if (this.special == 4 || this.special == 5) {
return;
}
this.node.opacity = 0;
if (this.special == WallSpecial.) {
this.node.parent.getChildByName("star").y -= 10;
}
this.node.parent.getChildByName("down").active = true;
}
upDoor() {
if (this.special == WallSpecial.) {
this.node.parent.getChildByName("star").y += 10;
}
this.node.parent.getChildByName("down").active = false;
this.node.opacity = 250;
}
resetFreeze() {
this.special = 0;
if (this.freezeNode) {
this.freezeNode.active = false;
}
// if (this.wall_Info.length != 0) {
// let spine = cc.instantiate(this.freezeSpine);
// spine.parent = this.node.parent;
// spine.setPosition(this.node.width / 2 + this.node.x + 60 / 2 * (this.wall_Info.length - 1), this.node.height / 2 + this.node.y);
// spine.getComponent(sp.Skeleton).setAnimation(1, "bingkuai", false);
// console.log("添加一个动画", spine.getPosition());
// }
}
changeRevolvingWall() {
if (this.revolvingNode) {
// console.log("自身编号", this.wall_Info.num, this.special);
if (this.special == WallSpecial. || this.special == WallSpecial.) {
this.revolvingNode.active = true;
}
else {
this.revolvingNode.active = false;
}
}
}
// update (dt) {}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "87a449b9-7ffa-4f00-a22b-b3202b4abfd5",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

86
assets/Script/Window.ts Normal file
View File

@ -0,0 +1,86 @@
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const {ccclass, property} = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
can_Touch: boolean;
// LIFE-CYCLE CALLBACKS:
onLoad () {
this.can_Touch = false;
}
start () {
}
init(data){
this.can_Touch = false;
this.node.getChildByName("win").active = false;
this.node.getChildByName("lose").active = false;
this.node.getChildByName("finishi").active = false;
this.node.getChildByName(data.result).active = true;
if(data.result == "lose"){
this.setErrLabel(data.code);
}
var target = this.node.getChildByName(data.result);
target.getChildByName("btn").active = false;
target.opacity = 0; target.scale = 2;target.getChildByName("tip").opacity = 0;
if(data.result == "win"){
var lianXi = false;
if(cc.fx.GameConfig.GM_INFO.level == 2) lianXi = true;
target.getChildByName("yes").active = !lianXi;
target.getChildByName("start").active = lianXi;
}
cc.tween(target)
.delay(0.1)
.to(0.25,{opacity:255,scale:1})
.delay(0.3)
.call(()=>{
if(target.name == "lose"){
cc.tween(target.getChildByName("tip"))
.to(0.5,{opacity:255})
.delay(0.5)
.call(() =>{
this.can_Touch = true;
target.getChildByName("btn").active = true;
})
.start();
}
else{
this.can_Touch = true;
target.getChildByName("btn").active = true;
}
})
.start();
}
setErrLabel(code){
var tip = this.node.getChildByName("lose").getChildByName("tip").getComponent(cc.Label);
tip.string = cc.fx.GameConfig.TIP_ERR[code];
}
click_Next(){
if(!this.can_Touch){
return;
}
this.can_Touch = false;
cc.tween(this.node)
.to(0.3,{opacity:0})
.call(() =>{
this.node.active = false;
cc.director.loadScene("GameScene");
})
.start();
}
// update (dt) {}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "3bad2bb2-3b0e-4ccc-bab7-6f983d6879f6",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,26 @@
const {ccclass, property} = cc._decorator;
@ccclass
export default class btnControl extends cc.Component {
static _instance: any;
_touch: boolean;
onLoad () {
this._touch = true;
}
start () {
}
setTouch(type){
this._touch = type;
}
update (dt) {
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "6ee6ccc9-e1e5-4d6f-815e-8aaa6ce5221a",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

146
assets/Script/heathnum.ts Normal file
View File

@ -0,0 +1,146 @@
import NumberToImage from "./NumberToImage";
import JiaZai from "./JiaZai";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";
const { ccclass, property } = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
//商店界面
@property(cc.Node)
heath: cc.Node = null;
//体力数量
@property(cc.Node)
heatht: cc.Node = null;
//切换的节点
@property([cc.Node])
switchNode: cc.Node[] = [];
//倒计时健康回复
@property(cc.Node)
timeNode: cc.Node = null;
//切换的按钮数组
@property([cc.Node])
switchButtons: cc.Node[] = [];
//金币花费数
@property(cc.Node)
coin: cc.Node = null;
btn_Touch: boolean = true;
onLoad() {
this.btn_Touch = true;
}
start() {
this.btn_Touch = true;
this.openPop();
}
//打开商店界面
openPop() {
// console.log("打开heath弹窗", cc.fx.GameConfig.GM_INFO.hp);
//NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 30, 15, "time_", this.coin, true);
}
startGame() {
// 获取场景中的 JiaZai 组件
const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
if (jiazaiNode) {
const jiazaiComp = jiazaiNode.getComponent(JiaZai);
if (jiazaiComp) {
jiazaiComp.startGame();
} else {
console.warn("JiaZai 组件未找到");
}
} else {
console.warn("JiaZai 节点未找到");
}
this.closePop();
}
//购买体力
buyHeath() {
if (!this.btn_Touch) {
return;
}
this.btn_Touch = false;
//获取当前体力
let curHeath = cc.fx.GameConfig.GM_INFO.hp;
//获取当前金币
let curCoin = cc.fx.GameConfig.GM_INFO.coin;
if (curCoin >= 1000) {
this.switchButtons[1].active = false;
cc.fx.GameTool.changeCoin(-1000);
const data = {
change_reason: "首页购买体力",
id: (1001 + ""),
num: -1000
}
cc.fx.GameTool.shushu_Track("resource_cost", data);
cc.fx.GameConfig.GM_INFO.hp = cc.fx.GameConfig.GM_INFO.hp_Max;
cc.fx.GameConfig.GM_INFO.min_Time = 0;
const parentNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
if (parentNode) {
const jiazaiComp = parentNode.getComponent(JiaZai);
if (jiazaiComp) {
jiazaiComp.setHealthInfo(false);
jiazaiComp.updateCoin();
}
}
this.switchButtons[0].active = true;
cc.fx.GameTool.setUserHealth(0, (data) => {
cc.fx.GameTool.getHealth(null);
})
const buyData = {
item_id: "refill_health",
item_num: 3,
item_price: 1000,
cost_type: "gold"
}
// console.log("____________即将上传Shop_buy", buyData);
cc.fx.GameTool.shushu_Track("shop_buy", buyData);
}
else {
MiniGameSdk.API.showToast("金币不足,无法购买体力");
setTimeout(() => {
this.btn_Touch = true;
this.openShop();
}, 500);
}
}
//金币不够购买金币
openShop() {
//获取场景中的 JiaZai 组件
const parentNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
if (parentNode) {
const jiazaiComp = parentNode.getComponent(JiaZai);
if (jiazaiComp) {
jiazaiComp.openShop();
}
}
}
//关闭弹窗
closePop() {
this.btn_Touch = true;
//销毁预制体
// console.log("关闭heath弹窗");
//关闭计时器
// 获取场景中的 JiaZai 组件
const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
if (jiazaiNode) {
const jiazaiComp = jiazaiNode.getComponent(JiaZai);
if (jiazaiComp) {
jiazaiComp.stopHeathTimeCutDown();
} else {
console.warn("JiaZai 组件未找到");
}
} else {
console.warn("JiaZai 节点未找到");
}
this.heath.destroy();
}
// update (dt) {}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "6624f85c-b85e-4317-aee0-cd25625a1455",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,13 @@
{
"ver": "1.1.3",
"uuid": "b6fd3869-f3bc-4fcb-9660-e4cbe0824ad3",
"importer": "folder",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}

View File

@ -0,0 +1,13 @@
{
"ver": "1.1.3",
"uuid": "6413d7ad-bfc3-4b8c-bc1c-c1d819e9d892",
"importer": "folder",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}

View File

@ -0,0 +1,71 @@
import Vec2 = cc.Vec2;
export enum LQRecordStatus {
Idle, Start, Pause
}
export enum LQBulletEmitterStatus {
Idle, Start, End
}
export enum LQCollideShape {
Rect = 1, Circle, Polygon
}
export enum LQFollowTargetMode {
Always, Once, Pass
}
export enum LQCollideStatus {
Idle, Live
}
export enum LQEasing {
BackIn = 'backIn', BackOut = 'backOut', quadIn = 'quadIn',
quadOut = 'quadOut', quadInOut = 'quadInOut', cubicIn = 'cubicIn', expoOut = 'expoOut'
}
export enum LQHttpRequestType {
Get = 'get', Post = 'post'
}
export enum LQHttpDataType {
Text, Binary
}
export enum LQPlatformType {
unknown = '未知平台', all = '全平台', wx = '微信', tt = '字节跳动', oppo = 'oppo', vivo = 'vivo', qq = 'qq', baidu = '百度', kwaigame = '快手', android = '安卓', ios = '苹果', browser = '浏览器'
}
export enum LQByteDanceType {
tt = '头条', tt_lite = '头条极速版', douyin = '抖音', douyin_lite = '抖音极速版', ppx = '皮皮虾', devtools = '字节开发工具'
}
export enum LQAnalysisTag {
VideoComplete = 'video_complete', VideoBegin = 'video_begin', VideoInterrupt = 'video_interrupt', InterstitialShow = 'interstitial_show', BannerShow = 'banner_show', ExportShow = 'export_show', NativeShow = 'native_show', NativeClick = 'native_show'
}
export enum LQCallBase {
InitSdk, KeepScreenOn, Vibrate, GetVersionCode, GetVersionName, OpenUrl, DeleteDir, DeleteFile
}
export enum LQCallAd {
ShowBanner, HideBanner, ShowVideo, ShowInterstitial, ShowNative, CacheAd
}
export enum LQAdErrStr {
Unsupported = '不支持', NoParameters = '没有配置参数', NoAD = '暂无广告', VersionOld = '版本过低', VideoInterrupt = '中断播放', InstanceErr = '实例为空', AlreadyExist = '已经存在', IntervalTooShort = '间隔太短'
}
export enum LQLevelStatus {
Begin, Failed, Complete
}
export enum LQOperateType {
ClickNode, ClickScreen, Move, Null
}
export class LQConst {
public static VEC_ZERO = Vec2.ZERO;
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "9830980f-5d4c-4417-acc1-7bd7bbe4a9db",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,118 @@
import {IPos, IRect} from "./lq_interface";
import Vec2 = cc.Vec2;
import Rect = cc.Rect;
import Sprite = cc.Sprite;
import Label = cc.Label;
import Node = cc.Node;
export class LQRect implements IRect {
public x: number;
public y: number;
public width: number;
public height: number;
public half_width: number;
public half_height: number;
constructor(x: number, y: number, width: number, height: number) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.half_width = width * 0.5;
this.half_height = height * 0.5;
}
public top_left(): Vec2 {
return new Vec2(this.x - this.half_width, this.y + this.half_height);
}
public top_right(): Vec2 {
return new Vec2(this.x + this.half_width, this.y + this.half_height);
}
public bottom_left(): Vec2 {
return new Vec2(this.x - this.half_width, this.y - this.half_height);
}
public bottom_right(): Vec2 {
return new Vec2(this.x + this.half_width, this.y - this.half_height);
}
public pos(): cc.Vec2 {
return new Vec2(this.x, this.y);
}
public sub(pos: IPos): Vec2 {
return new Vec2(pos.x - this.x, pos.y - this.y);
}
public add(pos: IPos): Vec2 {
return new Vec2(pos.x + this.x, pos.y + this.y);
}
public to_cocos_rect() {
return new Rect(this.x - this.half_width, this.y - this.half_height, this.width, this.height);
}
}
export class LQNativeComponent {
public node_btn_arr: Node[] = [];
public sprite_logo!: Sprite;
public sprite_img!: Sprite;
public sprite_ad_tip!: Sprite;
public label_title!: Label;
public label_desc!: Label;
}
export class LQShareData {
public title!: string;
public remote_url!: string;
public url_id!: string;
public query!: string;
public content!: string;
public extra!: any;
public type!: string;
constructor(obj?: { title?: string, remote_url?: string, url_id?: string, query?: string, content?: string, extra?: any, type?: string }) {
if (obj.title) {
this.title = obj.title;
}
if (obj.remote_url) {
this.remote_url = obj.remote_url;
}
if (obj.url_id) {
this.url_id = obj.url_id;
}
if (obj.query) {
this.query = obj.query;
}
if (obj.content) {
this.content = obj.content;
}
if (obj.extra) {
this.extra = obj.extra;
}
if (obj.type) {
this.type = obj.type;
}
}
}
export class LQPlatformData {
public app_id!: string;
public print_log!: boolean;
public show_share_menu!: boolean;
public keep_screen_on!: boolean;
public banner_id!: string;
public banner_width!: number;
public interstitial_id!: string;
public native_id!: string;
public video_id!: string;
public is_video_free!: boolean;
public is_cache_video!: boolean;
public ad_type!: string;
public ad_id!: string;
public ad_key!: string;
public switch_ad!: boolean;
public share_data_arr!: LQShareData[];
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "a5470d94-355f-4d03-ba58-81077a780e7f",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,23 @@
import Vec2 = cc.Vec2;
export interface IPos {
x: number;
y: number;
sub(pos: IPos): Vec2;
add(pos: IPos): Vec2;
}
export interface IRect {
x: number;
y: number;
width: number;
height: number;
half_width: number;
half_height: number;
sub(pos: IPos): Vec2;
add(pos: IPos): Vec2;
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "41e4557a-fef0-4dcf-97ed-8070a81667a2",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,13 @@
{
"ver": "1.1.3",
"uuid": "0432403f-8c23-4a3e-813a-1a9a1d88aeed",
"importer": "folder",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}

View File

@ -0,0 +1,162 @@
import {LQPlatformUtil} from "./lq_platform_util";
import {LQPlatformType} from "../data/lq_const";
import view = cc.view;
import Vec2 = cc.Vec2;
export class LQBaseUtil {
// public static readonly unit_arr = ['K', 'M', 'B', 'T'];
public static has_value<T>(arr: T[], v: T): boolean {
let has = false;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === v) {
has = true;
break;
}
}
return has;
}
public static get_value_by_duration(percent: number, timeline: Vec2[]): number {
if (timeline.length === 0) {
return 1;
}
let end_index = -1;
for (let i = 1; i < timeline.length; i++) {
if (timeline[i].x > percent) {
end_index = i;
break;
}
}
if (end_index === -1) {
return timeline[timeline.length - 1].y;
}
const start_index = end_index - 1;
return timeline[start_index].y + (timeline[end_index].y - timeline[start_index].y) * ((percent - timeline[start_index].x) / (timeline[end_index].x - timeline[start_index].x));
}
public static number_to_counting(num: number): string {
if (num < 1000) {
return num + '';
} else if (num < 1000000) {
return Math.floor(num / 1000) + 'K';
} else if (num < 1000000000) {
return Math.floor(num / 1000000) + 'M';
} else if (num < 1000000000000) {
return Math.floor(num / 1000000000) + 'B';
} else if (num < 1000000000000000) {
return Math.floor(num / 1000000000000) + 'T';
}
return Math.floor(num / 1000000000000) + 'T';
}
public static number_to_time(time: number): [string, string, string] {
const t = Math.floor(time / (60 * 60));
time = time - t * 60 * 60;
let hour = t.toString();
let min = Math.floor(time / 60).toString();
let sec = (time % 60).toString();
if (hour.length === 1) {
hour = '0' + hour;
}
if (min.length === 1) {
min = '0' + min;
}
if (sec.length === 1) {
sec = '0' + sec;
}
return [hour, min, sec];
}
public static set_normal_angle(angle: number) {
while (angle > 360) {
angle -= 360;
}
while (angle < 0) {
angle += 360;
}
return angle;
}
public static compare_version(v1: string, v2: string): number {
let v1_arr = v1.split('.');
let v2_arr = v2.split('.');
const len = Math.max(v1_arr.length, v2_arr.length);
while (v1_arr.length < len) {
v1_arr.push('0');
}
while (v2_arr.length < len) {
v2_arr.push('0');
}
for (let i = 0; i < len; i++) {
const num1 = parseInt(v1_arr[i]);
const num2 = parseInt(v2_arr[i]);
if (num1 > num2) {
return 1;
} else if (num1 < num2) {
return -1;
}
}
return 0;
}
public static is_today(date: string): boolean {
const d1 = new Date();
let d2;
if (date && date !== '') {
d2 = new Date(date);
} else {
d2 = new Date();
d2.setDate(d2.getDate() - 1);
}
return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate();
}
public static is_safe_area(): boolean {
const cb = (width: number, height: number) => {
return (width === 2280 && height === 1080) || (width === 1792 && height === 828) || (width === 2436 && height === 1125) || (width === 2688 && height === 1242);
};
switch (LQPlatformUtil.get_platform()) {
case LQPlatformType.baidu:
const sys_info_swan = swan.getSystemInfoSync();
return cb(sys_info_swan.pixelRatio * sys_info_swan.screenWidth, sys_info_swan.pixelRatio * sys_info_swan.screenHeight);
case LQPlatformType.qq:
const sys_info_qq = qq.getSystemInfoSync();
return cb(sys_info_qq.pixelRatio * sys_info_qq.screenWidth, sys_info_qq.pixelRatio * sys_info_qq.screenHeight);
case LQPlatformType.tt:
const sys_info_tt = tt.getSystemInfoSync();
return cb(sys_info_tt.pixelRatio * sys_info_tt.screenWidth, sys_info_tt.pixelRatio * sys_info_tt.screenHeight);
case LQPlatformType.oppo:
case LQPlatformType.vivo:
const sys_info_vivo = qg.getSystemInfoSync();
return cb(sys_info_vivo.pixelRatio * sys_info_vivo.screenWidth, sys_info_vivo.pixelRatio * sys_info_vivo.screenHeight);
case LQPlatformType.wx:
const sys_info_wx = wx.getSystemInfoSync();
return cb(sys_info_wx.pixelRatio * sys_info_wx.screenWidth, sys_info_wx.pixelRatio * sys_info_wx.screenHeight);
case LQPlatformType.android:
break;
case LQPlatformType.ios:
let size = view.getFrameSize();
return cb(size.width, size.height);
}
return false;
}
public static deep_clone(obj: any) {
if (typeof obj !== 'object') {
return obj;
}
let new_obj = (obj instanceof Array ? [] : {}) as any;
for (let key in obj) {
if (typeof obj[key] === 'object') {
new_obj[key] = this.deep_clone(obj[key]);
} else {
new_obj[key] = obj[key];
}
}
return new_obj;
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "cd21fb93-658e-4b3a-8897-b4deba47bc31",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

View File

@ -0,0 +1,147 @@
import SpriteFrame = cc.SpriteFrame;
import director = cc.director;
import tween = cc.tween;
import Texture2D = cc.Texture2D;
import Canvas = cc.Canvas;
import visibleRect = cc.visibleRect;
import find = cc.find;
import Node = cc.Node;
export class LQGameUtil {
private static image_cache: { [key: string]: SpriteFrame } = {};
public static get_image(url: string, callback: (success: boolean, sf: SpriteFrame | undefined) => void, cache = true) {
if (!url || url === '') {
callback(false, undefined);
return;
}
if (this.image_cache[url]) {
callback(true, this.image_cache[url]);
return;
}
// cc.loader.load(
// {url: url, type: 'png'},
// (err: string, texture: Texture2D | undefined) => {
// if (err) {
// // console.error('err:' + err);
// callback(false, undefined);
// return;
// }
// const frame = new SpriteFrame(texture);
// callback(true, frame);
// if (cache) {
// this.image_cache[url] = frame;
// }
// });
}
public static canvas_policy(c: Canvas, width: number, height: number): boolean {
// @ts-ignore
const ratio = visibleRect.height / visibleRect.width;
if (ratio > height / width) {
c.fitHeight = false;
c.fitWidth = true;
} else {
c.fitHeight = true;
c.fitWidth = false;
}
return c.fitHeight;
}
public static recursion_node_property(node: Node, p: { key: string, value: number }) {
if (node.parent) {
// @ts-ignore
p.value *= node.parent[p.key];
this.recursion_node_property(node.parent, p);
}
}
/**
*
* @param path
* eg.'Canvas>node_main>btn_start'
*/
public static find_node(path: string): Node | undefined {
if (!path || path.length <= 0) {
console.warn('路径不正确');
return undefined;
}
const arr = path.split('/');
const root = find(arr[0]);
if (!root) {
console.warn('没找到节点:' + arr[0]);
return undefined;
}
let node = root;
for (let i = 1; i < arr.length; i++) {
const temp = node.getChildByName(arr[i]);
if (!temp) {
console.warn('没找到节点:' + arr[i]);
return undefined;
}
node = temp;
}
return node;
}
public static wait(time: number) {
return new Promise((resolve) => {
tween(director.getScene()).delay(time).call(() => {
resolve();
}).start();
});
}
public static set_clip(clip: cc.AnimationClip, off: cc.Vec2, flip_x: boolean, flip_y: boolean) {
let s = (arr: number[]) => {
for (let i = 0; i < arr.length; i++) {
if (i % 2 === 0) {
if (flip_x) {
arr[i] = -arr[i];
}
arr[i] += off.x;
} else {
if (flip_y) {
arr[i] = -arr[i];
}
arr[i] += off.y;
}
}
};
const pos_arr = clip.curveData.props.position;
for (let i = 0; i < pos_arr.length; i++) {
const motionPath = pos_arr[i].motionPath;
const value = pos_arr[i].value;
if (motionPath) {
for (let i = 0; i < motionPath.length; i++) {
s(motionPath[i]);
}
}
s(value);
}
}
public static scroll_layout(layout: cc.Layout, speed: number = 50) {
layout.updateLayout();
const len = layout.type === cc.Layout.Type.HORIZONTAL ? layout.node.width : layout.node.height;
const time = len / speed;
if (layout.type === cc.Layout.Type.HORIZONTAL) {
let offset = layout.node.anchorX === 1 ? layout.node.width * 0.5 : -layout.node.width * 0.5;
layout.node.runAction(cc.repeatForever(cc.sequence(
cc.moveBy(time, cc.v2(offset, 0)),
cc.callFunc(() => {
layout.node.x -= offset;
})
)));
} else if (layout.type === cc.Layout.Type.VERTICAL || layout.type === cc.Layout.Type.GRID) {
let offset = layout.node.anchorY === 1 ? layout.node.height * 0.5 : -layout.node.height * 0.5;
layout.node.runAction(cc.repeatForever(cc.sequence(
cc.moveBy(time, cc.v2(0, offset)),
cc.callFunc(() => {
layout.node.y -= offset;
})
)));
}
}
}

View File

@ -0,0 +1,10 @@
{
"ver": "1.1.0",
"uuid": "63c53081-f5d8-4bfe-9845-38fb537ae17b",
"importer": "typescript",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}

Some files were not shown because too many files have changed in this diff Show More