Here's the converted script from Unity C# to Phaser 3 TypeScript. I've made assumptions about how your baseObject, gameState, and other objects are defined, so you might need to adjust some details depending on their actual implementations.
typescript
// Import required Phaser modules
import Phaser from 'phaser';
import BaseObject from './baseObject'; // Assuming you have a baseObject class defined somewhere
import GameState from './gameState'; // Assuming you have a gameState class defined somewhere
export default class AntidotScript extends BaseObject {
private isClicked: boolean = false;
constructor(scene: Phaser.Scene, x: number, y: number, texture: string) {
super(scene, x, y, texture);
this.scene.add.existing(this);
this.init();
}
private init(): void {
this.on(Phaser.GameObjects.Events.ENABLE, this.onEnable, this);
}
private onEnable(): void {
this.animHandle();
}
public async clicked(): Promise<void> {
if (!this.isClicked) {
this.isClicked = true;
GameState.Instance.looterNum++;
await this.animClickGlow();
this.AddToInventory();
this.parentTile._contains = 'nothing';
this.parentTile.filled = false;
this.parentTile.consumable = false;
playerManager.use.openTilesList.push(this.parentTile);
this.destroy();
}
}
private async animHandle(): Promise<void> {
// Animation handle logic
}
private async animClickGlow(): Promise<void> {
return new Promise((resolve) => {
// Animation click glow logic
resolve();
});
}
private AddToInventory(): void {
guiController.use.antidotPotions.val++;
}
}
Explanation:
Constructor: Initializes the object and calls init for further setup.
Enable Event: Registers a listener for the ENABLE event to call onEnable method.
onEnable Method: Starts the animation handling.
clicked Method: Checks if the object has been clicked or not. If not, it:
Increments the looterNum.
Waits for the animClickGlow to complete (await keyword).
Adds the item to inventory.
Updates the parentTile properties.
Destroy the game object.
AddToInventory Method: Increments the antidot potions value in the inventory.
Make sure you integrate this with your actual game state management and other systems in Phaser. You might need to change the method logic to fit into Phaser's style and architecture better.
}
// anvil_tip
using System.Collections;
using UnityEngine;
public class anvil_tip : MonoBehaviour
{
[SerializeField]
private GameObject menu;
Here are the three classes converted from Unity C# to Phaser 3 TypeScript code. I'll assume you have the requisite type and framework extensions in place for things like baseObject, playerManager, Messenger, and other supporting classes.
anvil.ts
typescript
import Phaser from 'phaser';
import BaseObject from './baseObject'; // Assuming you have a BaseObject class defined
import {Messenger} from './messenger'; // Assuming you have a Messenger class
import {PlayerManager} from './playerManager'; // Assuming you have a PlayerManager class
import {GameObjects, Scene} from "phaser";
export default class Anvil extends BaseObject {
private isPressed: boolean = false;
constructor(scene: Phaser.Scene, x: number, y: number, texture: string) {
super(scene, x, y, texture);
this.scene.add.existing(this);
}
public async clicked(): Promise<void> {
if (!this.isPressed) {
this.isPressed = true;
this.blackSmithMiniGame();
}
}
private async blackSmithMiniGame(): Promise<void> {
// Pause the game and start the mini-game
Messenger.Broadcast('gamePaused', true);
const miniGame = this.scene.add.image(0, 0, 'miniGame_anvil');
miniGame.setPosition(0, 0).setDepth(2);
// Update the parentTile properties
this.parentTile.filled = false;
this.parentTile._contains = 'nothing';
PlayerManager.use.openTilesList.add(this.parentTile);
// Destroy the anvil object
this.destroy();
}
}
anvil_tip.ts
typescript
import Phaser from 'phaser';
import {Messenger} from './messenger'; // Placeholder for actual import
export default class AnvilTip extends Phaser.GameObjects.Container {
private menu: Phaser.GameObjects.GameObject;
constructor(scene: Phaser.Scene, menu: Phaser.GameObjects.GameObject) {
super(scene);
this.menu = menu;
this.init();
}
private async init(): Promise<void> {
this.scene.add.existing(this);
await this.Start();
this.menu.setName('anvil_tip');
Messenger.CoAddListener('anvilTip_close', this.closeMenu.bind(this));
}
private async Start(): Promise<void> {
// Initial position setup
this.menu.setPosition(this.menu.x, this.menu.y, this.menu.z);
}
public OnEnable(): void {
Messenger.CoAddListener('anvilTip_close', this.closeMenu.bind(this));
}
public OnDisable(): void {
Messenger.CoRemoveListener('anvilTip_close', this.closeMenu.bind(this));
}
private async closeMenu(): Promise<void> {
// Handle the closing of the menu with tween animation
const {x, y} = this.menu.getCenter();
// Assume you are using a tween utility for animations
await tween.use.Slide(this.menu, y, y + 1200, 0.05, tween.SIDE.VERT);
// Update game state after closing the menu
PlayerPrefs.setInt('anvilTutorFlash', 0);
// Assuming anvil_miniGame has been declared and defined somewhere
AnvilMiniGame.use.btn.additionalBlock = false;
AnvilMiniGame.use.paused = false;
// Destroy this container
this.destroy();
}
}
Assumptions and Additional Implementations
Messenger Class: The event handling with Messenger.Broadcast, Messenger.CoAddListener, and Messenger.CoRemoveListener needs to be implemented in your Phaser project similar to Unity's messaging system.
PlayerManager and PlayerPrefs: You need to implement a version of playerManager and a storage utility like PlayerPrefs for managing player preferences.
Tween Utility: The tween utility tween.use.Slide should exist to handle animations. You can create it using Phaser's built-in tween functionalities.
The specific imports and framework adapters like BaseObject, Messenger, PlayerManager, AnvilMiniGame, and so forth should be put together in your project to complete the functional equivalence.
Example of Tween Utility using Phaser
This can be done using the built-in tweens of Phaser 3. Here is an example of how to implement the sliding animation:
Anvil.ts: Converts the anvil class, including handling the click event that starts the blacksmith minigame.
AnvilTip.ts: Converts the anvil_tip class, including event listeners for opening and closing the menu.
AnvilMiniGame.ts: Converts the anvil_miniGame class, including all game logic, using Phaser's methods to replace Unity methods.
Assumptions and Additions:
Messenger: Assumes you have a Messenger class for broadcasting and listening to events.
TweenUtil: Assumes a tween utility (can be created using Phaser's tween functionality).
PlayerPrefs: Assumes a simple preference system.
GUI Elements and Sounds: Ensure all game-specific elements and sounds are correctly added and accessible.
These classes are adapted to run using Phaser and TypeScript, making sure to port the logic, properties, and behaviors while conforming to Phaser's own systems and methods.
what do you think, if i have messenger object in unity, should i convert it to typescript class, or i could use embed phaser 3 event system?
here is the code:
// Messenger
using System;
using System.Collections.Generic;
using UnityEngine;
internal static class Messenger
{
public class BroadcastException : Exception
{
public BroadcastException(string msg)
: base(msg)
{
}
}
code
public class ListenerException : Exception
{
public ListenerException(string msg)
: base(msg)
{
}
}
private static MessengerHelper messengerHelper = new GameObject("MessengerHelper").AddComponent<MessengerHelper>();
public static Dictionary<string, Delegate> eventTable = new Dictionary<string, Delegate>();
public static List<string> permanentMessages = new List<string>();
public static void MarkAsPermanent(string eventType)
{
permanentMessages.Add(eventType);
}
public static void Cleanup()
{
List<string> list = new List<string>();
foreach (KeyValuePair<string, Delegate> item in eventTable)
{
bool flag = false;
foreach (string permanentMessage in permanentMessages)
{
if (item.Key == permanentMessage)
{
flag = true;
break;
}
}
if (!flag)
{
list.Add(item.Key);
}
}
foreach (string item2 in list)
{
eventTable.Remove(item2);
}
}
public static void PrintEventTable()
{
Debug.Log("\t\t\t=== MESSENGER PrintEventTable ===");
foreach (KeyValuePair<string, Delegate> item in eventTable)
{
Debug.Log("\t\t\t" + item.Key + "\t\t" + item.Value);
}
Debug.Log("\n");
}
public static void OnListenerAdding(string eventType, Delegate listenerBeingAdded)
{
if (!eventTable.ContainsKey(eventType))
{
eventTable.Add(eventType, null);
}
Delegate @delegate = eventTable[eventType];
if ((object)@delegate != null && @delegate.GetType() != listenerBeingAdded.GetType())
{
throw new ListenerException($"Attempting to add listener with inconsistent signature for event type {eventType}. Current listeners have type {@delegate.GetType().Name} and listener being added has type {listenerBeingAdded.GetType().Name}");
}
}
public static void OnListenerRemoving(string eventType, Delegate listenerBeingRemoved)
{
if (eventTable.ContainsKey(eventType))
{
Delegate @delegate = eventTable[eventType];
if ((object)@delegate == null)
{
throw new ListenerException($"Attempting to remove listener with for event type \"{eventType}\" but current listener is null.");
}
if (@delegate.GetType() != listenerBeingRemoved.GetType())
{
throw new ListenerException($"Attempting to remove listener with inconsistent signature for event type {eventType}. Current listeners have type {@delegate.GetType().Name} and listener being removed has type {listenerBeingRemoved.GetType().Name}");
}
return;
}
throw new ListenerException($"Attempting to remove listener for type \"{eventType}\" but Messenger doesn't know about this event type.");
}
public static void OnListenerRemoved(string eventType)
{
if ((object)eventTable[eventType] == null)
{
eventTable.Remove(eventType);
}
}
public static void OnBroadcasting(string eventType)
{
if (!eventTable.ContainsKey(eventType))
{
throw new BroadcastException($"Broadcasting message \"{eventType}\" but no listener found. Try marking the message with Messenger.MarkAsPermanent.");
}
}
public static BroadcastException CreateBroadcastSignatureException(string eventType)
{
return new BroadcastException($"Broadcasting message \"{eventType}\" but listeners have a different signature than the broadcaster.");
}
public static void AddListener(string eventType, Callback handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (Callback)Delegate.Combine((Callback)eventTable[eventType], handler);
}
public static void AddListenerINT(string eventType, CallbackINT handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (CallbackINT)Delegate.Combine((CallbackINT)eventTable[eventType], handler);
}
public static void AddListenerSTRING(string eventType, CallbackSTRING handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (CallbackSTRING)Delegate.Combine((CallbackSTRING)eventTable[eventType], handler);
}
public static void CoAddListener(string eventType, CoCallback handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (CoCallback)Delegate.Combine((CoCallback)eventTable[eventType], handler);
}
public static void AddListener<T>(string eventType, Callback<T> handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (Callback<T>)Delegate.Combine((Callback<T>)eventTable[eventType], handler);
}
public static void CoAddListener<T>(string eventType, CoCallback<T> handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (CoCallback<T>)Delegate.Combine((CoCallback<T>)eventTable[eventType], handler);
}
public static void AddListenerINT<T>(string eventType, CallbackINT<T> handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (CallbackINT<T>)Delegate.Combine((CallbackINT<T>)eventTable[eventType], handler);
}
public static void AddListener<T, U>(string eventType, Callback<T, U> handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (Callback<T, U>)Delegate.Combine((Callback<T, U>)eventTable[eventType], handler);
}
public static void CoAddListener<T, U>(string eventType, CoCallback<T, U> handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (CoCallback<T, U>)Delegate.Combine((CoCallback<T, U>)eventTable[eventType], handler);
}
public static void AddListener<T, U, V>(string eventType, Callback<T, U, V> handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (Callback<T, U, V>)Delegate.Combine((Callback<T, U, V>)eventTable[eventType], handler);
}
public static void AddListener<T, U, V, S>(string eventType, Callback<T, U, V, S> handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (Callback<T, U, V, S>)Delegate.Combine((Callback<T, U, V, S>)eventTable[eventType], handler);
}
public static void CoAddListener<T, U, V>(string eventType, CoCallback<T, U, V> handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (CoCallback<T, U, V>)Delegate.Combine((CoCallback<T, U, V>)eventTable[eventType], handler);
}
public static void RemoveListener(string eventType, Callback handler)
{
OnListenerRemoving(eventType, handler);
eventTable[eventType] = (Callback)Delegate.Remove((Callback)eventTable[eventType], handler);
OnListenerRemoved(eventType);
}
public static void RemoveListenerINT(string eventType, CallbackINT handler)
{
OnListenerRemoving(eventType, handler);
eventTable[eventType] = (CallbackINT)Delegate.Remove((CallbackINT)eventTable[eventType], handler);
OnListenerRemoved(eventType);
}
public static void RemoveListenerSTRING(string eventType, CallbackSTRING handler)
{
OnListenerRemoving(eventType, handler);
eventTable[eventType] = (CallbackSTRING)Delegate.Remove((CallbackSTRING)eventTable[eventType], handler);
OnListenerRemoved(eventType);
}
public static void CoRemoveListener(string eventType, CoCallback handler)
{
OnListenerRemoving(eventType, handler);
eventTable[eventType] = (CoCallback)Delegate.Remove((CoCallback)eventTable[eventType], handler);
OnListenerRemoved(eventType);
}
public static void RemoveListener<T>(string eventType, Callback<T> handler)
{
OnListenerRemoving(eventType, handler);
eventTable[eventType] = (Callback<T>)Delegate.Remove((Callback<T>)eventTable[eventType], handler);
OnListenerRemoved(eventType);
}
public static void CoRemoveListener<T>(string eventType, CoCallback<T> handler)
{
OnListenerRemoving(eventType, handler);
eventTable[eventType] = (CoCallback<T>)Delegate.Remove((CoCallback<T>)eventTable[eventType], handler);
OnListenerRemoved(eventType);
}
public static void RemoveListener<T, U>(string eventType, Callback<T, U> handler)
{
OnListenerRemoving(eventType, handler);
eventTable[eventType] = (Callback<T, U>)Delegate.Remove((Callback<T, U>)eventTable[eventType], handler);
OnListenerRemoved(eventType);
}
public static void CoRemoveListener<T, U>(string eventType, CoCallback<T, U> handler)
{
OnListenerRemoving(eventType, handler);
eventTable[eventType] = (CoCallback<T, U>)Delegate.Remove((CoCallback<T, U>)eventTable[eventType], handler);
OnListenerRemoved(eventType);
}
public static void RemoveListener<T, U, V>(string eventType, Callback<T, U, V> handler)
{
OnListenerRemoving(eventType, handler);
eventTable[eventType] = (Callback<T, U, V>)Delegate.Remove((Callback<T, U, V>)eventTable[eventType], handler);
OnListenerRemoved(eventType);
}
public static void CoRemoveListener<T, U, V>(string eventType, CoCallback<T, U, V> handler)
{
OnListenerRemoving(eventType, handler);
eventTable[eventType] = (CoCallback<T, U, V>)Delegate.Remove((CoCallback<T, U, V>)eventTable[eventType], handler);
OnListenerRemoved(eventType);
}
public static void RemoveListener<T, U, V, S>(string eventType, Callback<T, U, V, S> handler)
{
OnListenerAdding(eventType, handler);
eventTable[eventType] = (Callback<T, U, V, S>)Delegate.Combine((Callback<T, U, V, S>)eventTable[eventType], handler);
}
public static void Broadcast(string eventType)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (!(value is Callback callback))
{
throw CreateBroadcastSignatureException(eventType);
}
callback();
}
}
public static int BroadcastINT(string eventType)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (value is CallbackINT callbackINT)
{
return callbackINT();
}
throw CreateBroadcastSignatureException(eventType);
}
return -1;
}
public static string BroadcastSTRING(string eventType)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (value is CallbackSTRING callbackSTRING)
{
return callbackSTRING();
}
throw CreateBroadcastSignatureException(eventType);
}
return null;
}
public static void CoBroadcast(string eventType)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (!(value is CoCallback coCallback))
{
throw CreateBroadcastSignatureException(eventType);
}
messengerCoHandler.use.StartCoroutine(coCallback());
}
}
public static void Broadcast<T>(string eventType, T arg1)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (!(value is Callback<T> callback))
{
throw CreateBroadcastSignatureException(eventType);
}
callback(arg1);
}
}
public static void BroadcastINT<T>(string eventType, T arg1)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (!(value is CallbackINT<T> callbackINT))
{
throw CreateBroadcastSignatureException(eventType);
}
callbackINT(arg1);
}
}
public static void CoBroadcast<T>(string eventType, T arg1)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (!(value is CoCallback<T> coCallback))
{
throw CreateBroadcastSignatureException(eventType);
}
messengerCoHandler.use.StartCoroutine(coCallback(arg1));
}
}
public static void Broadcast<T, U>(string eventType, T arg1, U arg2)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (!(value is Callback<T, U> callback))
{
throw CreateBroadcastSignatureException(eventType);
}
callback(arg1, arg2);
}
}
public static void CoBroadcast<T, U>(string eventType, T arg1, U arg2)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (!(value is CoCallback<T, U> coCallback))
{
throw CreateBroadcastSignatureException(eventType);
}
messengerCoHandler.use.StartCoroutine(coCallback(arg1, arg2));
}
}
public static void Broadcast<T, U, V>(string eventType, T arg1, U arg2, V arg3)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (!(value is Callback<T, U, V> callback))
{
throw CreateBroadcastSignatureException(eventType);
}
callback(arg1, arg2, arg3);
}
}
public static void CoBroadcast<T, U, V>(string eventType, T arg1, U arg2, V arg3)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (!(value is CoCallback<T, U, V> coCallback))
{
throw CreateBroadcastSignatureException(eventType);
}
messengerCoHandler.use.StartCoroutine(coCallback(arg1, arg2, arg3));
}
}
public static void Broadcast<T, U, V, S>(string eventType, T arg1, U arg2, V arg3, S arg4)
{
OnBroadcasting(eventType);
if (eventTable.TryGetValue(eventType, out var value))
{
if (!(value is Callback<T, U, V, S> callback))
{
throw CreateBroadcastSignatureException(eventType);
}
callback(arg1, arg2, arg3, arg4);
}
}
}
Using Phaser 3's Event System vs. Custom Messenger
Phaser 3 has a built-in event system that is powerful and flexible, so I would suggest using Phaser's event system rather than converting the Unity Messenger class. This will integrate better with the rest of your Phaser game and avoid redundancy.
Here’s how you can use Phaser 3's event system to replace the functionality provided by the Messenger class in Unity.
Basic Implementation Using Phaser.Events.EventEmitter
Phaser’s EventEmitter class can be used to create a central event hub for your game.
Creating the Event Manager
You can create a simple event manager by extending Phaser’s EventEmitter:
typescript
import Phaser from 'phaser';
class EventManager extends Phaser.Events.EventEmitter {
constructor() {
super();
}
// Singleton pattern to ensure only one instance
private static instance: EventManager;
public static getInstance(): EventManager {
if (!this.instance) {
this.instance = new EventManager();
}
return this.instance;
}
}
export default EventManager;
Using the Event Manager
With the EventManager, you can broadcast and listen for events.
typescript
import EventManager from './EventManager';
// Adding an event listener
EventManager.getInstance().on('gamePaused', (paused) => {
console.log(`Game paused: ${paused}`);
});
// Dispatching an event
EventManager.getInstance().emit('gamePaused', true);
Converting the Messenger Class Using Phaser’s Event System
You will be using the EventManager instead of Messenger. Here’s how the classes you previously converted can use Phaser’s event system:
Anvil Class
typescript
import Phaser from 'phaser';
import BaseObject from './baseObject';
import EventManager from './EventManager';
import { PlayerManager } from './playerManager';
export default class Anvil extends BaseObject {
private isPressed = false;
constructor(scene: Phaser.Scene, x: number, y: number, texture: string) {
super(scene, x, y, texture);
this.scene.add.existing(this);
}
public async clicked(): Promise<void> {
if (!this.isPressed) {
this.isPressed = true;
await this.blackSmithMiniGame();
}
}
private async blackSmithMiniGame(): Promise<void> {
await new Promise(resolve => setTimeout(resolve, 0));
EventManager.getInstance().emit('gamePaused', true);
const miniGame = this.scene.add.image(0, 0, 'miniGame_anvil').setDepth(2);
this.parentTile.filled = false;
this.parentTile._contains = 'nothing';
PlayerManager.use.openTilesList.add(this.parentTile);
this.destroy();
}
}
import Phaser from 'phaser';
import EventManager from './EventManager';
import { PlayerPrefs } from './playerPrefs';
import { TweenUtil } from './tweenUtil';
interface ProgressStruct {
sprite: Phaser.GameObjects.Sprite;
spriteBonus: Phaser.GameObjects.Sprite;
selfTransform: Phaser.GameObjects.Container;
selfTransformBonus: Phaser.GameObjects.Container;
}
export default class AnvilMiniGame extends Phaser.Scene {
// ... other properties and constructor
private async create(): Promise<void> {
EventManager.getInstance().on('showAnvilTip', this.showAnvilTip.bind(this));
await this.handleGame();
}
private async showAnvilTip(): Promise<void> {
this.paused = true;
this.btn.additionalBlock = true;
this.add.image(0, 0, 'tip_anvil').setDepth(-8);
await new Promise(resolve => setTimeout(resolve, 0));
return;
}
private async handleGame(): Promise<void> {
await this.coMoveCursor();
this.input.on('pointerdown', async () => {
if (!this.paused) {
await new Promise(resolve => setTimeout(resolve, 10));
this.pressed = true;
}
});
while (true) {
if (this.pressed) {
break;
}
await new Promise(resolve => setTimeout(resolve, 0));
}
}
// ... other methods
}
Summary
You can replace the Messenger class with a custom event manager leveraging Phaser's built-in EventEmitter. This approach ensures you’re using a framework-native solution, making the integration smoother and more maintainable. The newly created EventManager helps in creating and managing events in a centralized way, covering the same use cases as the Unity’s Messenger.
Make sure that all classes that depend on Messenger now utilize EventManager. This should simplify handling events across your Phaser game.
Dataset releases
Not yet included in a published release.
public tk2dSlicedSprite spriteBonus;
public Transform selfTransform;
public Transform selfTransformBonus;
public progress_Struct(int val)
{
selfTransform = use.transform.Find("progress").transform;
sprite = use.transform.Find("progress").GetComponent<tk2dSlicedSprite>();
spriteBonus = use.transform.Find("progress2").GetComponent<tk2dSlicedSprite>();
selfTransformBonus = use.transform.Find("progress2").transform;
}
}
private const int MAXLEVEL_CONSTANT = 10;
private bool pressed;
[SerializeField]
private tk2dTextMesh chainText;
[SerializeField]
private tk2dTextMesh maxChainText;
[SerializeField]
private tk2dTextMesh LevelText;
public baseButton btn;
public static anvil_miniGame use;
[SerializeField]
private Transform cursor;
public bool paused;
private progress_Struct progressBar;
private float halfDimensionVal;
private Dictionary<int, float[]> levels = new Dictionary<int, float[]>();
private int _chainNum;
private int maxChain;
private int _levelNum = 1;
private int cash;
public bool tutorEnabled;
private int attemps;
private int levelNum
{
get
{
return _levelNum;
}
set
{
_levelNum = value;
LevelText.text = "Level\n-" + _levelNum + "-";
LevelText.Commit();
}
}
private int chainNum
{
get
{
return _chainNum;
}
set
{
_chainNum = value;
chainText.text = "chain: " + _chainNum;
chainText.Commit();
}
}
private void Awake()
{
use = this;
levels.Add(1, new float[4] { 1.2f, 5f, 3f, 1f });
levels.Add(2, new float[4] { 1f, 4.5f, 5f, 2f });
levels.Add(3, new float[4] { 0.9f, 4f, 7f, 3f });
levels.Add(4, new float[4] { 0.85f, 3.75f, 10f, 4f });
levels.Add(5, new float[4] { 0.7f, 3.5f, 10f, 5f });
levels.Add(6, new float[4] { 0.7f, 3f, 10f, 6f });
levels.Add(7, new float[4] { 0.7f, 2.75f, 12f, 7f });
levels.Add(8, new float[4] { 0.65f, 2.5f, 14f, 12f });
levels.Add(9, new float[4] { 0.5f, 2.25f, 15f, 15f });
levels.Add(10, new float[4] { 0.5f, 2f, 3f, 20f });
tutorEnabled = Convert.ToBoolean(PlayerPrefs.GetInt("anvilTutorFlash", 1));
}
private void Start()
{
foreach (monster value in dungeonManager.use.activeMobs.Values)
{
value.mStats.position = new Vector3(value.mStats.position.x, value.mStats.position.y, 6f);
}
progressBar = new progress_Struct(0);
Messenger.CoAddListener("showAnvilTip", showAnvilTip);
StartCoroutine(handleGame());
maxChain = PlayerPrefs.GetInt("blackSmith_maxChain", 0);
maxChainText.text = "best: " + maxChain;
maxChainText.Commit();
btn.isTipActive = tutorEnabled;
}
private IEnumerator showAnvilTip()
{
paused = true;
btn.additionalBlock = true;
UnityEngine.Object.Instantiate(res.menus["tip_anvil"], new Vector3(0f, 0f, -8f), Quaternion.identity);
yield return true;
}
private IEnumerator handleGame()
{
StartCoroutine(coMoveCursor());
while (true)
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hit, float.PositiveInfinity))
{
if (!(hit.collider.name == "button") && !paused)
{
yield return new WaitForSeconds(0.01f);
pressed = true;
}
}
else if (!paused)
{
yield return new WaitForSeconds(0.01f);
pressed = true;
}
}
yield return 0;
}
}
private IEnumerator coMoveCursor()
{
float speed = levels[levelNum][0];
float sideSize = levels[levelNum][1];
int side = UnityEngine.Random.Range(0, 2);
if (side == 0)
{
cursor.localPosition = new Vector3(75f, cursor.localPosition.y, cursor.localPosition.z);
}
else
{
cursor.localPosition = new Vector3(565f, cursor.localPosition.y, cursor.localPosition.z);
}
halfDimensionVal = sideSize * 10f;
progressBar.sprite.dimensions = new Vector2(halfDimensionVal * 2f, 50f);
progressBar.spriteBonus.dimensions = new Vector2(halfDimensionVal / 3f * 2f, 50f);
float posX = UnityEngine.Random.Range(75f, 565f);
progressBar.selfTransform.localPosition = new Vector3(Mathf.Clamp(posX, 75f + halfDimensionVal, 575f - halfDimensionVal), progressBar.selfTransform.localPosition.y, progressBar.selfTransform.localPosition.z);
progressBar.selfTransformBonus.localPosition = progressBar.selfTransform.localPosition - new Vector3(0f, 0f, 0.1f);
StartCoroutine(tween.use.alpha(progressBar.spriteBonus, 1f, 0.15f));
yield return StartCoroutine(tween.use.alpha(progressBar.sprite, 1f, 0.15f));
while (!pressed)
{
if (side == 0)
{
yield return StartCoroutine(SlideOffSet(cursor, 490f, speed));
yield return StartCoroutine(SlideOffSet(cursor, -490f, speed));
}
else
{
yield return StartCoroutine(SlideOffSet(cursor, -490f, speed));
yield return StartCoroutine(SlideOffSet(cursor, 490f, speed));
}
yield return 0;
}
if (checkCursorPos(cursor.position.x))
{
pressed = false;
StartCoroutine(tween.use.colorChange(progressBar.spriteBonus, new Color(0.5882353f, 0.5882353f, 0.5882353f, 1f), 0.1f));
yield return StartCoroutine(tween.use.colorChange(progressBar.sprite, new Color(0.5882353f, 0.5882353f, 0.5882353f, 1f), 0.1f));
StartCoroutine(tween.use.colorChange(progressBar.sprite, new Color(0f, 0f, 0f, 1f), 0.09f));
StartCoroutine(tween.use.colorChange(progressBar.spriteBonus, new Color(0f, 0f, 0f, 1f), 0.09f));
StartCoroutine(tween.use.alpha(progressBar.spriteBonus, 0f, 0.1f));
yield return StartCoroutine(tween.use.alpha(progressBar.sprite, 0f, 0.1f));
chainNum++;
attemps++;
if (attemps >= (int)levels[levelNum][2] && levelNum < 10)
{
attemps = 0;
levelNum++;
}
StartCoroutine(coMoveCursor());
}
else
{
if (chainNum > maxChain)
{
PlayerPrefs.SetInt("blackSmith_maxChain", chainNum);
}
GameObject o = UnityEngine.Object.Instantiate(res.menus["noteMenu_message"], new Vector3(320f, 480f, -5f), Quaternion.identity) as GameObject;
o.GetComponent<notifyMenu_message>().SetMessage("You've earned " + cash + " coins");
UnityEngine.Object.Destroy(base.gameObject);
}
}
private bool checkCursorPos(float posX)
{
string[] array = new string[2] { "anvil1", "anvil2" };
int num = 1;
if (posX >= progressBar.selfTransform.position.x - halfDimensionVal - 5f && posX <= progressBar.selfTransform.position.x + halfDimensionVal + 5f)
{
if (posX >= progressBar.selfTransformBonus.position.x - halfDimensionVal / 3f && posX <= progressBar.selfTransformBonus.position.x + halfDimensionVal / 3f)
{
num = 2;
}
if (UnityEngine.Random.Range(0f, 101f) > 0.5f)
{
int num2 = (int)levels[levelNum][3] * num;
cash += num2;
guiController.use.createCurrencyInformer(num2, "coins");
guiController.use.createLootInfo(num2, "coins", new Vector3(320f, 525f, -5f), "+ ");
dungeonGenerator.use.StartCoroutine(soundManager.Instance.playSound(res.music[array[UnityEngine.Random.Range(0, array.Length)]]));
dungeonGenerator.use.StartCoroutine(soundManager.Instance.playSound(res.music["coins_1"]));
}
else
{
dungeonGenerator.use.StartCoroutine(soundManager.Instance.playSound(res.music[array[UnityEngine.Random.Range(0, array.Length)]]));
dungeonGenerator.use.StartCoroutine(soundManager.Instance.playSound(res.music["sword-unsheathe"]));
dungeonManager.use.swordAmount++;
guiController.use.createLootInfo(1, "swords", new Vector3(320f, 525f, -5f), "+ ");
}
return true;
}
return false;
}
public IEnumerator SlideOffSet(Transform obTransform, float end, float timer)
{
if (obTransform == null)
{
yield break;
}
float t = 0f;
Vector3 start = obTransform.position;
while (t < 1f && !(obTransform == null) && !pressed)
{
if (!paused)
{
t += Time.deltaTime * (1f / timer);
obTransform.position = new Vector3(Mathf.Lerp(start.x, start.x + end, 1f - Mathf.Cos(t * (float)Math.PI * 0.5f)), obTransform.position.y, obTransform.position.z);
}
yield return true;
}
}