Fhub link

This commit is contained in:
2023-05-20 13:49:50 +05:30
parent 3db7622e7b
commit 6b9a2e7b80
56 changed files with 31288 additions and 30182 deletions

View File

@@ -1,158 +1,158 @@
using System;
using System.Collections;
using System.Collections.Generic;
using GoogleMobileAds.Api;
using UnityEngine;
public class AdsManager : MonoBehaviour
{
// Start is called before the first frame update
public static AdsManager instance;
void Awake(){
if(instance!= null){Destroy(gameObject);}
instance = this;
}
const string intAdId = "ca-app-pub-3966734202864173/1197808629";
const string rewardedAdId = "ca-app-pub-3966734202864173/3725853326";
void Start()
{
DontDestroyOnLoad(gameObject);
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(initStatus => { Debug.Log("admob Init status : " + initStatus.ToString());});
StartCoroutine(ReloadAds(true));
}
private InterstitialAd interstitialAd;
/// <summary>
/// Loads the interstitial ad.
/// </summary>
public void LoadInterstitialAd()
{
// Clean up the old ad before loading a new one.
if (interstitialAd != null)
{
interstitialAd.Destroy();
interstitialAd = null;
}
Debug.Log("Loading the interstitial ad.");
// create our request used to load the ad.
var adRequest = new AdRequest.Builder()
.AddKeyword("unity-admob-sample")
.Build();
// send the request to load the ad.
InterstitialAd.Load(intAdId, adRequest,
(InterstitialAd ad, LoadAdError error) =>
{
// if error is not null, the load request failed.
if (error != null || ad == null)
{
Debug.LogError("interstitial ad failed to load an ad " +
"with error : " + error);
return;
}
Debug.Log("Interstitial ad loaded with response : "
+ ad.GetResponseInfo());
interstitialAd = ad;
});
}
public void ShowIntAd()
{
if (interstitialAd != null && interstitialAd.CanShowAd())
{
Debug.Log("Showing interstitial ad.");
interstitialAd.Show();
}
else
{
Debug.LogError("Interstitial ad is not ready yet.");
}
StartCoroutine(ReloadAds(false));
}
private RewardedAd rewardedAd;
/// <summary>
/// Loads the rewarded ad.
/// </summary>
public void LoadRewardedAd()
{
// Clean up the old ad before loading a new one.
if (rewardedAd != null)
{
rewardedAd.Destroy();
rewardedAd = null;
}
Debug.Log("Loading the rewarded ad.");
// create our request used to load the ad.
var adRequest = new AdRequest.Builder().Build();
// send the request to load the ad.
RewardedAd.Load(rewardedAdId, adRequest,
(RewardedAd ad, LoadAdError error) =>
{
// if error is not null, the load request failed.
if (error != null || ad == null)
{
Debug.LogError("Rewarded ad failed to load an ad " +
"with error : " + error);
return;
}
Debug.Log("Rewarded ad loaded with response : "
+ ad.GetResponseInfo());
rewardedAd = ad;
rewardedAd.OnAdPaid += OnRewardSuccess;
});
}
private void OnRewardSuccess(AdValue obj)
{
GameManager.AdWatched();
}
public void ShowRewardedAd()
{
const string rewardMsg =
"Rewarded ad rewarded the user. Type: {0}, amount: {1}.";
if (rewardedAd != null && rewardedAd.CanShowAd())
{
rewardedAd.Show((Reward reward) =>
{
// TODO: Reward the user.
Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
});
}
StartCoroutine(ReloadAds(true));
}
IEnumerator ReloadAds(bool rewarded){
yield return new WaitForSeconds(2);
LoadInterstitialAd();
if(rewarded){
LoadRewardedAd();
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using GoogleMobileAds.Api;
using UnityEngine;
public class AdsManager : MonoBehaviour
{
// Start is called before the first frame update
public static AdsManager instance;
void Awake(){
if(instance!= null){Destroy(gameObject);}
instance = this;
}
const string intAdId = "ca-app-pub-3966734202864173/1197808629";
const string rewardedAdId = "ca-app-pub-3966734202864173/3725853326";
void Start()
{
DontDestroyOnLoad(gameObject);
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(initStatus => { Debug.Log("admob Init status : " + initStatus.ToString());});
StartCoroutine(ReloadAds(true));
}
private InterstitialAd interstitialAd;
/// <summary>
/// Loads the interstitial ad.
/// </summary>
public void LoadInterstitialAd()
{
// Clean up the old ad before loading a new one.
if (interstitialAd != null)
{
interstitialAd.Destroy();
interstitialAd = null;
}
Debug.Log("Loading the interstitial ad.");
// create our request used to load the ad.
var adRequest = new AdRequest.Builder()
.AddKeyword("unity-admob-sample")
.Build();
// send the request to load the ad.
InterstitialAd.Load(intAdId, adRequest,
(InterstitialAd ad, LoadAdError error) =>
{
// if error is not null, the load request failed.
if (error != null || ad == null)
{
Debug.LogError("interstitial ad failed to load an ad " +
"with error : " + error);
return;
}
Debug.Log("Interstitial ad loaded with response : "
+ ad.GetResponseInfo());
interstitialAd = ad;
});
}
public void ShowIntAd()
{
if (interstitialAd != null && interstitialAd.CanShowAd())
{
Debug.Log("Showing interstitial ad.");
interstitialAd.Show();
}
else
{
Debug.LogError("Interstitial ad is not ready yet.");
}
StartCoroutine(ReloadAds(false));
}
private RewardedAd rewardedAd;
/// <summary>
/// Loads the rewarded ad.
/// </summary>
public void LoadRewardedAd()
{
// Clean up the old ad before loading a new one.
if (rewardedAd != null)
{
rewardedAd.Destroy();
rewardedAd = null;
}
Debug.Log("Loading the rewarded ad.");
// create our request used to load the ad.
var adRequest = new AdRequest.Builder().Build();
// send the request to load the ad.
RewardedAd.Load(rewardedAdId, adRequest,
(RewardedAd ad, LoadAdError error) =>
{
// if error is not null, the load request failed.
if (error != null || ad == null)
{
Debug.LogError("Rewarded ad failed to load an ad " +
"with error : " + error);
return;
}
Debug.Log("Rewarded ad loaded with response : "
+ ad.GetResponseInfo());
rewardedAd = ad;
rewardedAd.OnAdPaid += OnRewardSuccess;
});
}
private void OnRewardSuccess(AdValue obj)
{
GameManager.AdWatched();
}
public void ShowRewardedAd()
{
const string rewardMsg =
"Rewarded ad rewarded the user. Type: {0}, amount: {1}.";
if (rewardedAd != null && rewardedAd.CanShowAd())
{
rewardedAd.Show((Reward reward) =>
{
// TODO: Reward the user.
Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
});
}
StartCoroutine(ReloadAds(true));
}
IEnumerator ReloadAds(bool rewarded){
yield return new WaitForSeconds(2);
LoadInterstitialAd();
if(rewarded){
LoadRewardedAd();
}
}
}

View File

@@ -1,79 +1,79 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public static AudioManager instance { get; private set;}
public static bool isMute {get; private set;}
void Awake(){
if(instance != null){Destroy(gameObject);return;}
instance =this;
if(PlayerPrefs.HasKey("mute")){
isMute = PlayerPrefs.GetInt("mute") == 1;
}else{
isMute=false;
}
Refresh();
}
[SerializeField]private AudioSource sfxSource;
[SerializeField]private AudioSource dropSfxSource;
[SerializeField]private AudioClip[] lowHits, midHits, hardHits;
[SerializeField]private AudioClip[] drop;
[SerializeField]private float dropMinPitch = 0.5f;
[SerializeField]private float dropMaxPitch = 1.5f;
public void PlaySFX(AudioClip clip){
sfxSource.PlayOneShot(clip);
}
public static void PlaySfx(AudioClip clip){
instance.PlaySFX(clip);
}
public static void HitSfx(float magnitude){
instance.hitSfx(magnitude);
}
public static void DropSfx(float magnitude){
instance.dropSfx(magnitude);
}
public static bool ToggleMute(){
isMute = !isMute;
Refresh();
PlayerPrefs.SetInt("mute", isMute ? 1 : 0);
PlayerPrefs.Save();
return isMute;
}
public static void Refresh(){
if(instance!=null){
instance.sfxSource.volume = isMute ? 0 : 1;
instance.dropSfxSource.volume = isMute ? 0 : 1;
}
}
void hitSfx(float magnitude){
AudioClip selectedClip;
if(magnitude < 0.5f){
selectedClip = lowHits[Random.Range(0,lowHits.Length)];
}else if(magnitude < 1){
selectedClip = midHits[Random.Range(0,midHits.Length)];
}else{
selectedClip = hardHits[Random.Range(0,hardHits.Length)];
}
Debug.Log("Playing hit sfx for " + magnitude);
sfxSource.PlayOneShot(selectedClip);
}
void dropSfx(float magnitude){
float diff = dropMaxPitch - dropMinPitch;
float mult = magnitude / 10f;
dropSfxSource.pitch = dropMinPitch + (diff * mult);
dropSfxSource.volume = mult;
Debug.Log($"Playing drop sfx for { magnitude } : {mult}, pitch: {dropSfxSource.pitch}, volume: {dropSfxSource.volume}");
dropSfxSource.Play();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public static AudioManager instance { get; private set;}
public static bool isMute {get; private set;}
void Awake(){
if(instance != null){Destroy(gameObject);return;}
instance =this;
if(PlayerPrefs.HasKey("mute")){
isMute = PlayerPrefs.GetInt("mute") == 1;
}else{
isMute=false;
}
Refresh();
}
[SerializeField]private AudioSource sfxSource;
[SerializeField]private AudioSource dropSfxSource;
[SerializeField]private AudioClip[] lowHits, midHits, hardHits;
[SerializeField]private AudioClip[] drop;
[SerializeField]private float dropMinPitch = 0.5f;
[SerializeField]private float dropMaxPitch = 1.5f;
public void PlaySFX(AudioClip clip){
sfxSource.PlayOneShot(clip);
}
public static void PlaySfx(AudioClip clip){
instance.PlaySFX(clip);
}
public static void HitSfx(float magnitude){
instance.hitSfx(magnitude);
}
public static void DropSfx(float magnitude){
instance.dropSfx(magnitude);
}
public static bool ToggleMute(){
isMute = !isMute;
Refresh();
PlayerPrefs.SetInt("mute", isMute ? 1 : 0);
PlayerPrefs.Save();
return isMute;
}
public static void Refresh(){
if(instance!=null){
instance.sfxSource.volume = isMute ? 0 : 1;
instance.dropSfxSource.volume = isMute ? 0 : 1;
}
}
void hitSfx(float magnitude){
AudioClip selectedClip;
if(magnitude < 0.5f){
selectedClip = lowHits[Random.Range(0,lowHits.Length)];
}else if(magnitude < 1){
selectedClip = midHits[Random.Range(0,midHits.Length)];
}else{
selectedClip = hardHits[Random.Range(0,hardHits.Length)];
}
Debug.Log("Playing hit sfx for " + magnitude);
sfxSource.PlayOneShot(selectedClip);
}
void dropSfx(float magnitude){
float diff = dropMaxPitch - dropMinPitch;
float mult = magnitude / 10f;
dropSfxSource.pitch = dropMinPitch + (diff * mult);
dropSfxSource.volume = mult;
Debug.Log($"Playing drop sfx for { magnitude } : {mult}, pitch: {dropSfxSource.pitch}, volume: {dropSfxSource.volume}");
dropSfxSource.Play();
}
}

View File

@@ -1,265 +1,284 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;
public static class DataManager{
public const string API_ENDPOINT = "http://vps.playpoolstudios.com/faucet/golf/api/";
public const string key = "#2CuV1Bit^S!sW1ZcgRv8BhrO";
public static UserData userData{get; private set;}
public static List<LeaderboardItemData> Leaderboard{get; private set;}
public static bool isLogged{ get{return userData != null;}}
public static void Signout(){
GoogleSignIn.DefaultInstance.SignOut();
PlayerPrefs.DeleteAll();
PlayerPrefs.Save();
userData = null;
}
public static async Task<int> Login(string username,string password){
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("password", password);
form.AddField("key", key);
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "login.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("login response: " +request.downloadHandler.text);
if(request.downloadHandler.text.Contains("{")){
try{
userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
Debug.Log("Success parsing userdata");
PlayerPrefs.SetString("username", username);
PlayerPrefs.SetString("password", password);
PlayerPrefs.Save();
}catch(Exception e){
Debug.Log("Error parsing userdata");
}
}else{
if(request.downloadHandler.text == "0"){
userData = new UserData(){username = username};
Debug.Log("Created local account");
}else{
MessageBox.ShowMessage("Error logging in, Server said\n" +request.downloadHandler.text);
return 1;
}
}
}
LoadingScreen.LoadLevel("MainMenu");
return 0;
}
public static async Task<int> LinkFH(string fhid){
WWWForm form = new WWWForm();
form.AddField("username", userData.username);
form.AddField("fhid", fhid);
form.AddField("key", key);
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "link_fh.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("fh link response: " +request.downloadHandler.text);
if(request.downloadHandler.text== "0"){
userData.faucetId = int.Parse(fhid);
Debug.Log("FH Link success");
}
}
return 0;
}
public static async void GoogleLogin(string username){
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("key", key);
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "google_login.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("glogin response: " +request.downloadHandler.text);
// MessageBox.ShowMessage(request.downloadHandler.text);
if(request.downloadHandler.text.Contains("{")){
try{
userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
if(userData == null){
throw new NullReferenceException();
}
if(userData.username.Length < 3){
throw new IndexOutOfRangeException();
}
Debug.Log("Success parsing userdata");
PlayerPrefs.SetString("username", username);
PlayerPrefs.SetString("password", username);
PlayerPrefs.Save();
}catch(Exception e){
Debug.Log("Error parsing userdata");
}
}else{
if(request.downloadHandler.text == "0"){
userData = new UserData(){username = username};
}else{
MessageBox.ShowMessage("Error logging in, Server said\n" +request.downloadHandler.text);
return;
}
}
}
LoadingScreen.LoadLevel("MainMenu");
}
public static async void AddScores(int amount){
WWWForm form = new WWWForm();
Debug.Log(userData.ToString());
form.AddField("username", userData.username);
form.AddField("password", userData.password);
form.AddField("amount", amount);
form.AddField("key", key);
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "add_scores.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("add scores response: " +request.downloadHandler.text);
if(request.downloadHandler.text.Contains("{")){
try{
userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
if(userData == null){
throw new NullReferenceException();
}
if(userData.username.Length < 3){
throw new IndexOutOfRangeException();
}
Debug.Log("Success parsing userdata");
}catch(Exception e){
Debug.Log("Error parsing userdata");
}
}else{
MessageBox.ShowMessage("Error Updating scores, Server said\n" +request.downloadHandler.text);
}
}
LoadingScreen.LoadLevel("MainMenu");
}
public static async Task RefreshLeaderboard(){
WWWForm form = new WWWForm();
Debug.Log(userData.ToString());
form.AddField("username", userData.username);
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "get_leaderboard.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("add scores response: " +request.downloadHandler.text);
if(request.downloadHandler.text.Contains("{")){
try{
string[] items = request.downloadHandler.text.Split("<td>");
Leaderboard = new List<LeaderboardItemData>();
foreach(string item in items){
LeaderboardItemData newItem = JsonConvert.DeserializeObject<LeaderboardItemData>(item);
Leaderboard.Add(newItem);
}
Debug.Log("Success parsing userdata");
}catch(Exception e){
Debug.Log("Error parsing leaderboard");
}
}else{
MessageBox.ShowMessage("Error getting leaderboard, Server said\n" +request.downloadHandler.text);
}
}
}
}
[System.Serializable]
public class UserData{
public int id;
public string username;
public string password;
public int score;
public int TopScore;
public int faucetId;
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
[System.Serializable]
public class LeaderboardItemData{
public int position;
public string name;
public int topScore;
public string DisplayName{get{
string _name= name;
if(name.Contains("#0")){
_name = _name.Substring(0,name.IndexOf("@gmail"));
}
return _name;
}}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;
public static class DataManager{
public const string API_ENDPOINT = "http://vps.playpoolstudios.com/faucet/golf/api/";
public const string key = "#2CuV1Bit^S!sW1ZcgRv8BhrO";
public static UserData userData{get; private set;}
public static List<LeaderboardItemData> Leaderboard{get; private set;}
public static bool isLogged{ get{return userData != null;}}
public static void Signout(){
GoogleSignIn.DefaultInstance.SignOut();
PlayerPrefs.DeleteAll();
PlayerPrefs.Save();
userData = null;
}
public static async Task<int> Login(string username,string password){
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("password", password);
form.AddField("key", key);
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "login.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("login response: " +request.downloadHandler.text);
if(request.downloadHandler.text.Contains("{")){
try{
userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
Debug.Log("Success parsing userdata");
PlayerPrefs.SetString("username", username);
PlayerPrefs.SetString("password", password);
PlayerPrefs.Save();
}catch(Exception e){
Debug.Log("Error parsing userdata");
}
}else{
if(request.downloadHandler.text == "0"){
userData = new UserData(){username = username};
Debug.Log("Created local account");
}else{
MessageBox.ShowMessage("Error logging in, Server said\n" +request.downloadHandler.text);
return 1;
}
}
}
LoadingScreen.LoadLevel("MainMenu");
return 0;
}
public static async Task<int> LinkFH(string fhid){
WWWForm form = new WWWForm();
form.AddField("username", userData.username);
form.AddField("fhid", fhid);
form.AddField("key", key);
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "link_fh.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("fh link response: " +request.downloadHandler.text);
if(request.downloadHandler.text== "0"){
userData.faucetId = int.Parse(fhid);
Debug.Log("FH Link success");
}
}
return 0;
}
public static async void GoogleLogin(string username){
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("key", key);
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "google_login.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("glogin response: " +request.downloadHandler.text);
// MessageBox.ShowMessage(request.downloadHandler.text);
if(request.downloadHandler.text.Contains("{")){
try{
userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
if(userData == null){
throw new NullReferenceException();
}
if(userData.username.Length < 3){
throw new IndexOutOfRangeException();
}
Debug.Log("Success parsing userdata");
PlayerPrefs.SetString("username", username);
PlayerPrefs.SetString("password", username);
PlayerPrefs.Save();
}catch(Exception e){
Debug.Log("Error parsing userdata");
}
}else{
if(request.downloadHandler.text == "0"){
userData = new UserData(){username = username};
}else{
MessageBox.ShowMessage("Error logging in, Server said\n" +request.downloadHandler.text);
return;
}
}
}
LoadingScreen.LoadLevel("MainMenu");
}
public static async void AddScores(int amount){
WWWForm form = new WWWForm();
Debug.Log(userData.ToString());
form.AddField("username", userData.username);
form.AddField("password", userData.password);
form.AddField("amount", amount);
form.AddField("key", key);
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "add_scores.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("add scores response: " +request.downloadHandler.text);
if(request.downloadHandler.text.Contains("{")){
try{
userData = JsonConvert.DeserializeObject<UserData>(request.downloadHandler.text);
if(userData == null){
throw new NullReferenceException();
}
if(userData.username.Length < 3){
throw new IndexOutOfRangeException();
}
Debug.Log("Success parsing userdata");
}catch(Exception e){
Debug.Log("Error parsing userdata");
}
}else{
MessageBox.ShowMessage("Error Updating scores, Server said\n" +request.downloadHandler.text);
}
}
LoadingScreen.LoadLevel("MainMenu");
}
public static async Task RefreshLeaderboard(bool total = false){
WWWForm form = new WWWForm();
Debug.Log(userData.ToString());
form.AddField("username", userData.username);
if(total){
form.AddField("total", "1");
}
bool foundMe = false;
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "get_leaderboard.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("leaderboard response: " +request.downloadHandler.text);
if(request.downloadHandler.text.Contains("{")){
try{
string[] items = request.downloadHandler.text.Split("<td>");
Leaderboard = new List<LeaderboardItemData>();
foreach(string item in items){
if(item == DataManager.userData.username){
foundMe=true;
}
LeaderboardItemData newItem = JsonConvert.DeserializeObject<LeaderboardItemData>(item);
Leaderboard.Add(newItem);
}
Debug.Log("Success parsing userdata");
}catch(Exception e){
Debug.Log("Error parsing leaderboard");
}
}else{
MessageBox.ShowMessage("Error getting leaderboard, Server said\n" +request.downloadHandler.text);
}
}
if(!foundMe){
form.AddField("id",DataManager.userData.id);
form.AddField("topScore","1");
using (UnityWebRequest request = UnityWebRequest.Post(API_ENDPOINT + "get_player_position.php", form))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
Debug.Log("my position: " +request.downloadHandler.text);
LeaderboardItemData newItem = new LeaderboardItemData(){position=int.Parse(request.downloadHandler.text), name= DataManager.userData.username, topScore = DataManager.userData.TopScore};
Leaderboard.Add(newItem);
}
}
}
}
[System.Serializable]
public class UserData{
public int id;
public string username;
public string password;
public int score;
public int TopScore;
public int faucetId;
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
[System.Serializable]
public class LeaderboardItemData{
public int position;
public string name;
public int topScore;
public int Score;
public string DisplayName{get{
string _name= name;
if(name.Contains("#0")){
_name = _name.Substring(0,name.IndexOf("@gmail"));
}
return _name;
}}
}

View File

@@ -1,36 +1,36 @@
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class EncryptionTester : MonoBehaviour
{
public PaddingMode paddingMode;
public CipherMode cipherMode;
[Header("Encryption")]
public string textToEncrypt;
public string encryptedText;
[Header("Decryption")]
public string textToDecrypt;
public string decryptedText;
[Header("Numbers")]
[Header("Encryption")]
public int numberToEncrypt;
public string encryptedNumber;
[Header("Encryption")]
public string numTextToDecrypt;
public int decryptedNumber;
void OnDrawGizmos(){
Encryptor.cipherMode = cipherMode;
Encryptor.paddingMode = paddingMode;
encryptedText = Encryptor.encrypt(textToEncrypt);
decryptedText = Encryptor.decrypt(textToDecrypt);
encryptedNumber = Encryptor.intToString(numberToEncrypt);
decryptedNumber = Encryptor.stringToInt(numTextToDecrypt);
}
}
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class EncryptionTester : MonoBehaviour
{
public PaddingMode paddingMode;
public CipherMode cipherMode;
[Header("Encryption")]
public string textToEncrypt;
public string encryptedText;
[Header("Decryption")]
public string textToDecrypt;
public string decryptedText;
[Header("Numbers")]
[Header("Encryption")]
public int numberToEncrypt;
public string encryptedNumber;
[Header("Encryption")]
public string numTextToDecrypt;
public int decryptedNumber;
void OnDrawGizmos(){
Encryptor.cipherMode = cipherMode;
Encryptor.paddingMode = paddingMode;
encryptedText = Encryptor.encrypt(textToEncrypt);
decryptedText = Encryptor.decrypt(textToDecrypt);
encryptedNumber = Encryptor.intToString(numberToEncrypt);
decryptedNumber = Encryptor.stringToInt(numTextToDecrypt);
}
}

View File

@@ -1,102 +1,102 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System;
public static class Encryptor
{
private static string hash = "@419$";
public static PaddingMode paddingMode = PaddingMode.PKCS7;
public static CipherMode cipherMode = CipherMode.ECB;
private static string charPool = "AKFLDJAHSPIWUROCNMZX";
public static string encrypt(string input)
{
byte[] data = UTF8Encoding.UTF8.GetBytes(input);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider() { Key=key, Mode = cipherMode, Padding = paddingMode })
{
ICryptoTransform ict = tds.CreateEncryptor();
byte[] results = ict.TransformFinalBlock(data, 0, data.Length);
return Convert.ToBase64String(results, 0, results.Length);
}
}
}
public static string decrypt(string input)
{
byte[] data = Convert.FromBase64String(input);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider() { Key = key, Mode = cipherMode, Padding = paddingMode })
{
ICryptoTransform ict = tds.CreateDecryptor();
byte[] results = ict.TransformFinalBlock(data, 0, data.Length);
return UTF8Encoding.UTF8.GetString(results);
}
}
}
public static string intToString(int input){
char[] inputBytes = input.ToString().ToCharArray();
string output = "";
foreach(char c in inputBytes){
output += charPool[int.Parse(c.ToString())];
}
int luckyNumber = GetLuckyNumber(input);
string lastLetter = charPool.ToCharArray()[luckyNumber].ToString();
return output+lastLetter;
}
public static int stringToInt(string input){
char[] inputBytes = input.Remove(input.Length-1).ToCharArray();
string output = "";
foreach(char c in inputBytes){
for(int i=0; i < charPool.Length; i++){
if(charPool.ToCharArray()[i] == c){
output += i.ToString();
break;
}
}
}
char lastchar = input.ToCharArray()[input.Length-1];
int outputInt = int.Parse(output);
char luckyChar = charPool.ToCharArray()[GetLuckyNumber(outputInt)];
bool validated = luckyChar == lastchar;
if(validated){
return outputInt;
}else{
return -1;
}
}
public static int GetLuckyNumber(int input){
int luckyNumber=input;
while(luckyNumber >= 10){
int val = 0;
for(int i=0; i < luckyNumber.ToString().Length; i++){
val += int.Parse(luckyNumber.ToString().ToCharArray()[i].ToString());
}
luckyNumber = val;
}
return luckyNumber;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System;
public static class Encryptor
{
private static string hash = "@419$";
public static PaddingMode paddingMode = PaddingMode.PKCS7;
public static CipherMode cipherMode = CipherMode.ECB;
private static string charPool = "AKFLDJAHSPIWUROCNMZX";
public static string encrypt(string input)
{
byte[] data = UTF8Encoding.UTF8.GetBytes(input);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider() { Key=key, Mode = cipherMode, Padding = paddingMode })
{
ICryptoTransform ict = tds.CreateEncryptor();
byte[] results = ict.TransformFinalBlock(data, 0, data.Length);
return Convert.ToBase64String(results, 0, results.Length);
}
}
}
public static string decrypt(string input)
{
byte[] data = Convert.FromBase64String(input);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider() { Key = key, Mode = cipherMode, Padding = paddingMode })
{
ICryptoTransform ict = tds.CreateDecryptor();
byte[] results = ict.TransformFinalBlock(data, 0, data.Length);
return UTF8Encoding.UTF8.GetString(results);
}
}
}
public static string intToString(int input){
char[] inputBytes = input.ToString().ToCharArray();
string output = "";
foreach(char c in inputBytes){
output += charPool[int.Parse(c.ToString())];
}
int luckyNumber = GetLuckyNumber(input);
string lastLetter = charPool.ToCharArray()[luckyNumber].ToString();
return output+lastLetter;
}
public static int stringToInt(string input){
char[] inputBytes = input.Remove(input.Length-1).ToCharArray();
string output = "";
foreach(char c in inputBytes){
for(int i=0; i < charPool.Length; i++){
if(charPool.ToCharArray()[i] == c){
output += i.ToString();
break;
}
}
}
char lastchar = input.ToCharArray()[input.Length-1];
int outputInt = int.Parse(output);
char luckyChar = charPool.ToCharArray()[GetLuckyNumber(outputInt)];
bool validated = luckyChar == lastchar;
if(validated){
return outputInt;
}else{
return -1;
}
}
public static int GetLuckyNumber(int input){
int luckyNumber=input;
while(luckyNumber >= 10){
int val = 0;
for(int i=0; i < luckyNumber.ToString().Length; i++){
val += int.Parse(luckyNumber.ToString().ToCharArray()[i].ToString());
}
luckyNumber = val;
}
return luckyNumber;
}
}

View File

@@ -1,290 +1,290 @@
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public static GameManager instance{get; private set;}
void Awake(){
instance=this;
}
public Rigidbody2D ball;
public float holeCheckRadius =1;
public Transform cam;
public Vector3 camTargetPos;
public float cameraSmoothness = 0.1f;
public Vector3 cameraOffset ;
public float inputSensitivity = 100f;
public float BallFriction = 0.1f;
public float BallFrictionStop = 0.1f;
public float StopVelocity = 0.01f;
public float SlowVelocity = 1f;
public float StopTime = 0.1f;
public float curVelocity;
public float forceMultiplier;
public Transform ballProjection;
public float ballProjectionScaleMin, ballProjectionScaleMax;
[Header("Game")]
public int MaxStrokes;
[SerializeField]private int m_curStrokes;
public int CurStrokes{get{return m_curStrokes;} set{ m_curStrokes=value; UpdateUI();}}
private int m_curScore;
public int Score{get {return m_curScore;} set{ m_curScore = value; UpdateUI(); }}
public Text StrokesTxt;
public Text ScoreTxt;
public Text gameOverBestScoreTxt, gameOverTotalScoreTxt;
public GameObject GameOverUI;
public GameObject PauseMenuUI;
public Button muteBtn;
public Sprite muteIcon, unmuteIcon;
public Animator HoleInOne;
public int curHoleIndex;
private static int adCounter = 0;
void Start()
{
muteBtn.onClick.AddListener(OnMute);
strokesTxtDefaultSize = StrokesTxt.transform.localScale;
scoreTxtDefaultSize = ScoreTxt.transform.localScale;
camTargetPos = ball.transform.position;
CurStrokes =1;
lastPosition = ball.transform.position;
ball.transform.position = LevelGenerator.holes[3].transform.position;
Debug.Log("Moving ball to " + LevelGenerator.holes[3].transform.position);
curHoleIndex = 2;
}
float stopCooldown = 0;
public bool isGrounded;
public static Vector3 lastPosition;
void Update(){
float distToFirst = ball.transform.position.x - LevelGenerator.holes[curHoleIndex].transform.position.x;
float distToLast = LevelGenerator.holes[curHoleIndex+1].transform.position.x - ball.transform.position.x;
if(distToFirst < -11 || distToLast < -11){
//Out of bounds, return to safe
ball.transform.position = lastPosition;
ball.velocity=Vector2.zero;
ball.simulated=false;
}
}
void FixedUpdate(){
Collider2D[] cols = Physics2D.OverlapCircleAll(ball.transform.position, holeCheckRadius);
isGrounded=false;
foreach(Collider2D col in cols){
if(col.tag == "Ground"){
isGrounded=true;
}
}
curVelocity = ball.velocity.magnitude;
ball.velocity = Vector2.Lerp(ball.velocity, new Vector2(0, ball.velocity.y), BallFriction);
if(isGrounded){ ball.velocity = Vector2.Lerp(ball.velocity, new Vector2(0, ball.velocity.y), ball.velocity.y > 0 ? BallFrictionStop : BallFrictionStop/10f);}
if(Mathf.Abs(ball.velocity.magnitude) < StopVelocity){
if(stopCooldown > StopTime){
ball.simulated=false;
CheckHole();
lastPosition=ball.transform.position;
}else{
stopCooldown+=Time.deltaTime;
}
}else{
stopCooldown=0;
}
}
void LateUpdate()
{
cam.position = Vector3.Lerp(cam.position, new Vector3(camTargetPos.x, cam.position.y,cam.position.z) + cameraOffset, cameraSmoothness);
}
private static bool cancelledHole = false;
public static void CancelHole(){
cancelledHole = true;
}
void CheckHole(){
Collider2D[] cols = Physics2D.OverlapCircleAll(ball.transform.position, holeCheckRadius);
foreach(Collider2D col in cols){
if(col.tag == "Hole"){
Hole(col.transform.position);
curHoleIndex++;
camTargetPos = (Vector2)col.transform.position;
Destroy(col.gameObject);
break;
}
}
//No hole found
if(CurStrokes <=0){
GameOver();
}
}
public void GameOver(){
if(GameOverUI.active){return;}
gameOverBestScoreTxt.text = DataManager.userData.TopScore.ToString();
gameOverTotalScoreTxt.text = DataManager.userData.score.ToString();
GameOverUI.SetActive(true);
adCounter++;
if(adCounter > 1){
adCounter=0;
AdsManager.instance.ShowIntAd();
}
}
public static async void Hole(Vector2 position){
while(instance.ball.simulated){
await Task.Delay(100);
if(cancelledHole){return;}
}
instance.ball.transform.position = position + new Vector2(0.6f, 0.75f);
instance.Score++;
if(instance.CurStrokes >= instance.MaxStrokes-1){
instance.HoleInOne.CrossFadeInFixedTime("Play",0.01f);
instance.Score++;
}
instance.CurStrokes = instance.MaxStrokes;
}
bool dragging = false;
Vector2 startPos;
public void OnMouseDown(BaseEventData e){
if(CurStrokes <= 0){return;}
if(ball.simulated){return;}
PointerEventData ped = (PointerEventData) e as PointerEventData;
startPos = ped.position;
dragging = true;
}
public void OnMouseUp(BaseEventData e){
if(CurStrokes <= 0){return;}
PointerEventData ped = (PointerEventData) e as PointerEventData;
if(dragging){
Vector2 v = ((ped.position-startPos)/inputSensitivity);
Shoot(v);
}
dragging = false;
ballProjection.position = Vector3.zero;
}
void Shoot(Vector2 v){
if(v.magnitude > 1){v = v.normalized;}
stopCooldown=0;
ball.simulated=true;
ball.AddForce(-v * forceMultiplier);
CurStrokes--;
AudioManager.HitSfx(v.magnitude);
}
public void OnMouseDrag(BaseEventData e){
if(CurStrokes <= 0){return;}
if(ball.simulated){return;}
ballProjection.position = ball.position;
PointerEventData ped = (PointerEventData) e as PointerEventData;
Vector2 v = ((ped.position-startPos)/inputSensitivity);
// Debug.Log(v.magnitude);
if(v.magnitude > 1){v = v.normalized;}
Vector3 direction = (ped.position - startPos).normalized;
float rot_z = Mathf.Atan2(direction.y,direction.x) * Mathf.Rad2Deg;
ballProjection.rotation = Quaternion.Euler(0,0,rot_z+180);
float scaleDiff = ballProjectionScaleMax - ballProjectionScaleMin;
ballProjection.GetChild(0).localScale = new Vector3(ballProjection.GetChild(0).localScale.x,ballProjectionScaleMin + (scaleDiff*v.magnitude));
}
int _tempScore;
int _tempStrokes;
Vector3 scoreTxtDefaultSize, strokesTxtDefaultSize;
public void UpdateUI(){
if(Score != _tempScore){
_tempScore = Score;
ScoreTxt.transform.localScale = scoreTxtDefaultSize;
LeanTween.scale(ScoreTxt.gameObject, scoreTxtDefaultSize * 2f , 0.5f).setEasePunch();
}
if(CurStrokes != _tempStrokes){
_tempStrokes = CurStrokes;
LeanTween.scale(StrokesTxt.gameObject, strokesTxtDefaultSize * 1.5f, 0.5f).setEasePunch();
}
ScoreTxt.text = Score.ToString();
StrokesTxt.text = CurStrokes.ToString();
muteBtn.transform.GetChild(0).GetComponent<Image>().sprite = AudioManager.isMute ? muteIcon : unmuteIcon;
}
void OnMute(){
AudioManager.ToggleMute();
UpdateUI();
}
void OnDrawGizmos(){
Gizmos.DrawWireSphere(ball.transform.position, holeCheckRadius);
}
public void WatchAd(){
AdsManager.instance.ShowRewardedAd();
}
public static void AdWatched(){
try{
instance.GameOverUI.SetActive(false);
instance.CurStrokes= (int)((float)instance.MaxStrokes/2f);
}catch{
}
}
public void Restrt(){
LoadingScreen.LoadLevel(SceneManager.GetActiveScene().name);
DataManager.AddScores(Score);
}
public void MainMenu(){
LoadingScreen.LoadLevel("MainMenu");
DataManager.AddScores(Score);
}
public void PauseMenu(bool value){
if(value){
LeanTween.scale(PauseMenuUI, Vector3.one, 0.15f).setEaseInCirc();
}else{
LeanTween.scale(PauseMenuUI, Vector3.zero, 0.15f).setEaseOutCirc();
}
UpdateUI();
}
}
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public static GameManager instance{get; private set;}
void Awake(){
instance=this;
}
public Rigidbody2D ball;
public float holeCheckRadius =1;
public Transform cam;
public Vector3 camTargetPos;
public float cameraSmoothness = 0.1f;
public Vector3 cameraOffset ;
public float inputSensitivity = 100f;
public float BallFriction = 0.1f;
public float BallFrictionStop = 0.1f;
public float StopVelocity = 0.01f;
public float SlowVelocity = 1f;
public float StopTime = 0.1f;
public float curVelocity;
public float forceMultiplier;
public Transform ballProjection;
public float ballProjectionScaleMin, ballProjectionScaleMax;
[Header("Game")]
public int MaxStrokes;
[SerializeField]private int m_curStrokes;
public int CurStrokes{get{return m_curStrokes;} set{ m_curStrokes=value; UpdateUI();}}
private int m_curScore;
public int Score{get {return m_curScore;} set{ m_curScore = value; UpdateUI(); }}
public Text StrokesTxt;
public Text ScoreTxt;
public Text gameOverBestScoreTxt, gameOverTotalScoreTxt;
public GameObject GameOverUI;
public GameObject PauseMenuUI;
public Button muteBtn;
public Sprite muteIcon, unmuteIcon;
public Animator HoleInOne;
public int curHoleIndex;
private static int adCounter = 0;
void Start()
{
muteBtn.onClick.AddListener(OnMute);
strokesTxtDefaultSize = StrokesTxt.transform.localScale;
scoreTxtDefaultSize = ScoreTxt.transform.localScale;
camTargetPos = ball.transform.position;
CurStrokes =1;
lastPosition = ball.transform.position;
ball.transform.position = LevelGenerator.holes[3].transform.position;
Debug.Log("Moving ball to " + LevelGenerator.holes[3].transform.position);
curHoleIndex = 2;
}
float stopCooldown = 0;
public bool isGrounded;
public static Vector3 lastPosition;
void Update(){
float distToFirst = ball.transform.position.x - LevelGenerator.holes[curHoleIndex].transform.position.x;
float distToLast = LevelGenerator.holes[curHoleIndex+1].transform.position.x - ball.transform.position.x;
if(distToFirst < -11 || distToLast < -11){
//Out of bounds, return to safe
ball.transform.position = lastPosition;
ball.velocity=Vector2.zero;
ball.simulated=false;
}
}
void FixedUpdate(){
Collider2D[] cols = Physics2D.OverlapCircleAll(ball.transform.position, holeCheckRadius);
isGrounded=false;
foreach(Collider2D col in cols){
if(col.tag == "Ground"){
isGrounded=true;
}
}
curVelocity = ball.velocity.magnitude;
ball.velocity = Vector2.Lerp(ball.velocity, new Vector2(0, ball.velocity.y), BallFriction);
if(isGrounded){ ball.velocity = Vector2.Lerp(ball.velocity, new Vector2(0, ball.velocity.y), ball.velocity.y > 0 ? BallFrictionStop : BallFrictionStop/10f);}
if(Mathf.Abs(ball.velocity.magnitude) < StopVelocity){
if(stopCooldown > StopTime){
ball.simulated=false;
CheckHole();
lastPosition=ball.transform.position;
}else{
stopCooldown+=Time.deltaTime;
}
}else{
stopCooldown=0;
}
}
void LateUpdate()
{
cam.position = Vector3.Lerp(cam.position, new Vector3(camTargetPos.x, cam.position.y,cam.position.z) + cameraOffset, cameraSmoothness);
}
private static bool cancelledHole = false;
public static void CancelHole(){
cancelledHole = true;
}
void CheckHole(){
Collider2D[] cols = Physics2D.OverlapCircleAll(ball.transform.position, holeCheckRadius);
foreach(Collider2D col in cols){
if(col.tag == "Hole"){
Hole(col.transform.position);
curHoleIndex++;
camTargetPos = (Vector2)col.transform.position;
Destroy(col.gameObject);
break;
}
}
//No hole found
if(CurStrokes <=0){
GameOver();
}
}
public void GameOver(){
if(GameOverUI.active){return;}
gameOverBestScoreTxt.text = DataManager.userData.TopScore.ToString();
gameOverTotalScoreTxt.text = DataManager.userData.score.ToString();
GameOverUI.SetActive(true);
adCounter++;
if(adCounter > 1){
adCounter=0;
AdsManager.instance.ShowIntAd();
}
}
public static async void Hole(Vector2 position){
while(instance.ball.simulated){
await Task.Delay(100);
if(cancelledHole){return;}
}
instance.ball.transform.position = position + new Vector2(0.6f, 0.75f);
instance.Score++;
if(instance.CurStrokes >= instance.MaxStrokes-1){
instance.HoleInOne.CrossFadeInFixedTime("Play",0.01f);
instance.Score++;
}
instance.CurStrokes = instance.MaxStrokes;
}
bool dragging = false;
Vector2 startPos;
public void OnMouseDown(BaseEventData e){
if(CurStrokes <= 0){return;}
if(ball.simulated){return;}
PointerEventData ped = (PointerEventData) e as PointerEventData;
startPos = ped.position;
dragging = true;
}
public void OnMouseUp(BaseEventData e){
if(CurStrokes <= 0){return;}
PointerEventData ped = (PointerEventData) e as PointerEventData;
if(dragging){
Vector2 v = ((ped.position-startPos)/inputSensitivity);
Shoot(v);
}
dragging = false;
ballProjection.position = Vector3.zero;
}
void Shoot(Vector2 v){
if(v.magnitude > 1){v = v.normalized;}
stopCooldown=0;
ball.simulated=true;
ball.AddForce(-v * forceMultiplier);
CurStrokes--;
AudioManager.HitSfx(v.magnitude);
}
public void OnMouseDrag(BaseEventData e){
if(CurStrokes <= 0){return;}
if(ball.simulated){return;}
ballProjection.position = ball.position;
PointerEventData ped = (PointerEventData) e as PointerEventData;
Vector2 v = ((ped.position-startPos)/inputSensitivity);
// Debug.Log(v.magnitude);
if(v.magnitude > 1){v = v.normalized;}
Vector3 direction = (ped.position - startPos).normalized;
float rot_z = Mathf.Atan2(direction.y,direction.x) * Mathf.Rad2Deg;
ballProjection.rotation = Quaternion.Euler(0,0,rot_z+180);
float scaleDiff = ballProjectionScaleMax - ballProjectionScaleMin;
ballProjection.GetChild(0).localScale = new Vector3(ballProjection.GetChild(0).localScale.x,ballProjectionScaleMin + (scaleDiff*v.magnitude));
}
int _tempScore;
int _tempStrokes;
Vector3 scoreTxtDefaultSize, strokesTxtDefaultSize;
public void UpdateUI(){
if(Score != _tempScore){
_tempScore = Score;
ScoreTxt.transform.localScale = scoreTxtDefaultSize;
LeanTween.scale(ScoreTxt.gameObject, scoreTxtDefaultSize * 2f , 0.5f).setEasePunch();
}
if(CurStrokes != _tempStrokes){
_tempStrokes = CurStrokes;
LeanTween.scale(StrokesTxt.gameObject, strokesTxtDefaultSize * 1.5f, 0.5f).setEasePunch();
}
ScoreTxt.text = Score.ToString();
StrokesTxt.text = CurStrokes.ToString();
muteBtn.transform.GetChild(0).GetComponent<Image>().sprite = AudioManager.isMute ? muteIcon : unmuteIcon;
}
void OnMute(){
AudioManager.ToggleMute();
UpdateUI();
}
void OnDrawGizmos(){
Gizmos.DrawWireSphere(ball.transform.position, holeCheckRadius);
}
public void WatchAd(){
AdsManager.instance.ShowRewardedAd();
}
public static void AdWatched(){
try{
instance.GameOverUI.SetActive(false);
instance.CurStrokes= (int)((float)instance.MaxStrokes/2f);
}catch{
}
}
public void Restrt(){
LoadingScreen.LoadLevel(SceneManager.GetActiveScene().name);
DataManager.AddScores(Score);
}
public void MainMenu(){
LoadingScreen.LoadLevel("MainMenu");
DataManager.AddScores(Score);
}
public void PauseMenu(bool value){
if(value){
LeanTween.scale(PauseMenuUI, Vector3.one, 0.15f).setEaseInCirc();
}else{
LeanTween.scale(PauseMenuUI, Vector3.zero, 0.15f).setEaseOutCirc();
}
UpdateUI();
}
}

View File

@@ -1,11 +1,11 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Collider2D))]
public class GolfBall : MonoBehaviour
{
void OnCollisionEnter2D(Collision2D other){
AudioManager.DropSfx(other.relativeVelocity.magnitude);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Collider2D))]
public class GolfBall : MonoBehaviour
{
void OnCollisionEnter2D(Collision2D other){
AudioManager.DropSfx(other.relativeVelocity.magnitude);
}
}

View File

@@ -1,22 +1,22 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hole : MonoBehaviour
{
public void OnTriggerEnter2D(Collider2D other){
if(other.tag == "Player"){
Debug.Log(other.name + " Entered hole");
GameManager.Hole(transform.position);
}
}
public void OnTriggerExit2D(Collider2D other){
if(other.tag == "Player"){
Debug.Log(other.name + " Exited hole");
GameManager.CancelHole();
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hole : MonoBehaviour
{
public void OnTriggerEnter2D(Collider2D other){
if(other.tag == "Player"){
Debug.Log(other.name + " Entered hole");
GameManager.Hole(transform.position);
}
}
public void OnTriggerExit2D(Collider2D other){
if(other.tag == "Player"){
Debug.Log(other.name + " Exited hole");
GameManager.CancelHole();
}
}
}

View File

@@ -1,115 +1,115 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
public class LevelGenerator : MonoBehaviour
{
public static LevelGenerator instance { get; private set; }
public GameObject spriteShapeControllerPrefab;
public int LevelCount = 1000;
public float groundLevel = -5.5f;
public float maxHeight = 5;
public Vector2 minDiff, maxDiff;
public Vector3[] points {get; private set;}
public GameObject holePrefab;
public GameObject flagPrefab;
public GameObject treePrefab;
public static List<GameObject> holes;
public int GoalDistance= 10;
void Awake()
{
instance=this;
holes = new List<GameObject>();
GenerateBlock();
GenerateBlock();
}
float lastOffset=0;
void GenerateBlock(){
float offset = lastOffset;
SpriteShapeController spriteShapeController = Instantiate(spriteShapeControllerPrefab, new Vector3(offset,0),Quaternion.identity).GetComponent<SpriteShapeController>();
spriteShapeController.spline.Clear();
points = new Vector3[LevelCount+1];
for(int i=0; i < LevelCount; i++){
if(i ==0){
points[i] = new Vector3(0,groundLevel);
spriteShapeController.spline.InsertPointAt(i, points[i]);
continue;
}
Vector3 addition = new Vector3(Random.Range(minDiff.x, maxDiff.x), Random.Range(minDiff.y, maxDiff.y));
float newX = points[i-1].x + addition.x;
float newY = points[i-1].y + addition.y;
while(newY < groundLevel+2){
newY += Mathf.Abs(addition.y);
}
while(newY > maxHeight){
newY -= Mathf.Abs(addition.y);
}
points[i] = new Vector3(newX, newY);
// spriteShapeController.spline.InsertPointAt(i, points[i]);
InsertNewPoint(spriteShapeController, points[i]);
if(Random.Range(0f,1f) > 0.5f){
Vector2 newTreePosition = points[i];
Vector3 diff = points[i]-points[i-1];
Vector2 newTreePosition2 = points[i-1] + (diff/2f) + new Vector3(lastOffset,0);
Debug.Log($"{points[i-1]} + {points[i]} - {points[i-1]} / 0.5f | diff = {diff}");
GameObject newTree = Instantiate(treePrefab, newTreePosition2, Quaternion.identity);
newTree.transform.localScale = Vector3.one * Random.Range(0.75f, 1.1f);
}
if(i % GoalDistance == 0){
InsertNewPoint(spriteShapeController, points[i] + new Vector3(0, -1f));
InsertNewPoint(spriteShapeController, points[i] + new Vector3(1f, -1f));
InsertNewPoint(spriteShapeController, points[i] + new Vector3(1f, 0f));
Vector3 newHolePos = points[i] + new Vector3(lastOffset,0);
Instantiate(flagPrefab,newHolePos, Quaternion.identity);
holes.Add(Instantiate(holePrefab,newHolePos, Quaternion.identity));
}
}
points[LevelCount] = new Vector3(points[LevelCount-1].x+maxDiff.x, groundLevel);
lastOffset = points[LevelCount].x - maxDiff.x;
InsertNewPoint(spriteShapeController, points[LevelCount]);
}
void InsertNewPoint(SpriteShapeController spriteShapeController,Vector3 point){
int index= spriteShapeController.spline.GetPointCount();
spriteShapeController.spline.InsertPointAt(index, point);
spriteShapeController.spline.SetLeftTangent(index, Vector3.zero);
spriteShapeController.spline.SetTangentMode(index, ShapeTangentMode.Broken);
}
float checker = 0;
void Update()
{
if(GameManager.instance == null){return;}
if(checker < 30){
checker+=Time.deltaTime;
}else{
checker =0;
if(GameManager.instance.ball.position.x > lastOffset - 100){
GenerateBlock();
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
public class LevelGenerator : MonoBehaviour
{
public static LevelGenerator instance { get; private set; }
public GameObject spriteShapeControllerPrefab;
public int LevelCount = 1000;
public float groundLevel = -5.5f;
public float maxHeight = 5;
public Vector2 minDiff, maxDiff;
public Vector3[] points {get; private set;}
public GameObject holePrefab;
public GameObject flagPrefab;
public GameObject treePrefab;
public static List<GameObject> holes;
public int GoalDistance= 10;
void Awake()
{
instance=this;
holes = new List<GameObject>();
GenerateBlock();
GenerateBlock();
}
float lastOffset=0;
void GenerateBlock(){
float offset = lastOffset;
SpriteShapeController spriteShapeController = Instantiate(spriteShapeControllerPrefab, new Vector3(offset,0),Quaternion.identity).GetComponent<SpriteShapeController>();
spriteShapeController.spline.Clear();
points = new Vector3[LevelCount+1];
for(int i=0; i < LevelCount; i++){
if(i ==0){
points[i] = new Vector3(0,groundLevel);
spriteShapeController.spline.InsertPointAt(i, points[i]);
continue;
}
Vector3 addition = new Vector3(Random.Range(minDiff.x, maxDiff.x), Random.Range(minDiff.y, maxDiff.y));
float newX = points[i-1].x + addition.x;
float newY = points[i-1].y + addition.y;
while(newY < groundLevel+2){
newY += Mathf.Abs(addition.y);
}
while(newY > maxHeight){
newY -= Mathf.Abs(addition.y);
}
points[i] = new Vector3(newX, newY);
// spriteShapeController.spline.InsertPointAt(i, points[i]);
InsertNewPoint(spriteShapeController, points[i]);
if(Random.Range(0f,1f) > 0.5f){
Vector2 newTreePosition = points[i];
Vector3 diff = points[i]-points[i-1];
Vector2 newTreePosition2 = points[i-1] + (diff/2f) + new Vector3(lastOffset,0);
Debug.Log($"{points[i-1]} + {points[i]} - {points[i-1]} / 0.5f | diff = {diff}");
GameObject newTree = Instantiate(treePrefab, newTreePosition2, Quaternion.identity);
newTree.transform.localScale = Vector3.one * Random.Range(0.75f, 1.1f);
}
if(i % GoalDistance == 0){
InsertNewPoint(spriteShapeController, points[i] + new Vector3(0, -1f));
InsertNewPoint(spriteShapeController, points[i] + new Vector3(1f, -1f));
InsertNewPoint(spriteShapeController, points[i] + new Vector3(1f, 0f));
Vector3 newHolePos = points[i] + new Vector3(lastOffset,0);
Instantiate(flagPrefab,newHolePos, Quaternion.identity);
holes.Add(Instantiate(holePrefab,newHolePos, Quaternion.identity));
}
}
points[LevelCount] = new Vector3(points[LevelCount-1].x+maxDiff.x, groundLevel);
lastOffset = points[LevelCount].x - maxDiff.x;
InsertNewPoint(spriteShapeController, points[LevelCount]);
}
void InsertNewPoint(SpriteShapeController spriteShapeController,Vector3 point){
int index= spriteShapeController.spline.GetPointCount();
spriteShapeController.spline.InsertPointAt(index, point);
spriteShapeController.spline.SetLeftTangent(index, Vector3.zero);
spriteShapeController.spline.SetTangentMode(index, ShapeTangentMode.Broken);
}
float checker = 0;
void Update()
{
if(GameManager.instance == null){return;}
if(checker < 30){
checker+=Time.deltaTime;
}else{
checker =0;
if(GameManager.instance.ball.position.x > lastOffset - 100){
GenerateBlock();
}
}
}
}

View File

@@ -1,88 +1,88 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadingScreen : MonoBehaviour
{
public static LoadingScreen instance {get; private set;}
[SerializeField]private Image loadingProgress;
[SerializeField]private Text loadingProgressTxt;
void Awake(){
if(instance != null){Destroy(gameObject);return;}
instance =this;
canvasGroup = GetComponent<CanvasGroup>();
Application.targetFrameRate = 60;
}
void Start()
{
DontDestroyOnLoad(gameObject);
}
public static void LoadLevel(string levelName){
if(instance==null){Debug.LogError("No loading screen found, Raw load"); SceneManager.LoadScene(levelName); return;}
instance.loadLevel(levelName);
}
public void loadLevel(string levelName){
if (loading) { return; }
loading = true;
StartCoroutine(_loadlLevel(levelName));
}
public static bool loading {get; private set;}
private CanvasGroup canvasGroup;
IEnumerator _loadlLevel(string levelName)
{
// AudioManager.instnace.SetMusic(-1);
loading = true;
canvasGroup.alpha = 0;
canvasGroup.blocksRaycasts = true;
SetProgress(0);
while (canvasGroup.alpha < 1f)
{
canvasGroup.alpha += 0.03f;
yield return new WaitForFixedUpdate();
}
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(levelName);
while (!asyncOperation.isDone)
{
SetProgress(asyncOperation.progress);
yield return null;
}
Debug.Log("Loaded scene " + levelName);
// yield return new WaitForSecondsRealtime(2f);
while(loadingProgress.fillAmount < 1){
SetProgress( loadingProgress.fillAmount+0.01f);
yield return new WaitForSeconds(0.1f);
}
canvasGroup.blocksRaycasts = false;
while (canvasGroup.alpha > 0)
{
canvasGroup.alpha -= 0.03f;
yield return new WaitForSecondsRealtime(0.015f);
}
Debug.Log("Loading scene vanishing");
loading = false;
}
void SetProgress(float value)
{
loadingProgress.fillAmount = value;
loadingProgressTxt.text = (int)(value * 100) + "%";
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadingScreen : MonoBehaviour
{
public static LoadingScreen instance {get; private set;}
[SerializeField]private Image loadingProgress;
[SerializeField]private Text loadingProgressTxt;
void Awake(){
if(instance != null){Destroy(gameObject);return;}
instance =this;
canvasGroup = GetComponent<CanvasGroup>();
Application.targetFrameRate = 60;
}
void Start()
{
DontDestroyOnLoad(gameObject);
}
public static void LoadLevel(string levelName){
if(instance==null){Debug.LogError("No loading screen found, Raw load"); SceneManager.LoadScene(levelName); return;}
instance.loadLevel(levelName);
}
public void loadLevel(string levelName){
if (loading) { return; }
loading = true;
StartCoroutine(_loadlLevel(levelName));
}
public static bool loading {get; private set;}
private CanvasGroup canvasGroup;
IEnumerator _loadlLevel(string levelName)
{
// AudioManager.instnace.SetMusic(-1);
loading = true;
canvasGroup.alpha = 0;
canvasGroup.blocksRaycasts = true;
SetProgress(0);
while (canvasGroup.alpha < 1f)
{
canvasGroup.alpha += 0.03f;
yield return new WaitForFixedUpdate();
}
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(levelName);
while (!asyncOperation.isDone)
{
SetProgress(asyncOperation.progress);
yield return null;
}
Debug.Log("Loaded scene " + levelName);
// yield return new WaitForSecondsRealtime(2f);
while(loadingProgress.fillAmount < 1){
SetProgress( loadingProgress.fillAmount+0.01f);
yield return new WaitForSeconds(0.1f);
}
canvasGroup.blocksRaycasts = false;
while (canvasGroup.alpha > 0)
{
canvasGroup.alpha -= 0.03f;
yield return new WaitForSecondsRealtime(0.015f);
}
Debug.Log("Loading scene vanishing");
loading = false;
}
void SetProgress(float value)
{
loadingProgress.fillAmount = value;
loadingProgressTxt.text = (int)(value * 100) + "%";
}
}

View File

@@ -1,177 +1,177 @@
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Login : MonoBehaviour
{
public Button helpBtn;
public Button googleLoginBtn;
public Button[] switchBtns;
public Text statusTxt;
public GameObject quickLoginPanel, guestLoginPanel;
public Button BtnGuestLogin;
public InputField usernameInput, passwordInput;
bool quickLoginPanelOn =true;
void Awake(){
helpBtn.onClick.AddListener(OnHelp);
googleLoginBtn.onClick.AddListener(OnSignIn);
BtnGuestLogin.onClick.AddListener(OnGuestLogin);
// guestLoginBtn.onClick.AddListener(SwitchLoginPanel);
foreach(Button switchBtn in switchBtns){
switchBtn.onClick.AddListener(SwitchLoginPanel);
}
configuration = new GoogleSignInConfiguration {
WebClientId = webClientId,
RequestIdToken = true,
RequestEmail=true,
};
}
async void AutoLogin(){
Debug.Log("Start auto-login");
if(PlayerPrefs.HasKey("username")){
Debug.Log("Has saved credentials, Trying to login with them");
int loginResult = await DataManager.Login(PlayerPrefs.GetString("username"), PlayerPrefs.GetString("password"));
if(loginResult == 0){
LoadingScreen.LoadLevel("MainMenu");
}else{
Debug.Log("Failed auto-login");
}
}
}
void Start(){
AutoLogin();
}
// Update is called once per frame
void Update()
{
}
void OnGuestLogin(){
if(usernameInput.text.Length < 3){
MessageBox.ShowMessage("Please enter a username longer than 3 characters");
return;
}
if(usernameInput.text.Contains("#")){
MessageBox.ShowMessage("Characters like #,$,%,^,& can't be included in username");
return;
}
if(passwordInput.text.Length < 5){
MessageBox.ShowMessage("Please enter a password with more than 5 characters to stay secure!");
return;
}
DataManager.Login(usernameInput.text, passwordInput.text);
}
void OnHelp(){
MessageBox.ShowMessage("This game saves your progress in cloud, in order to preserve the data. We need you to login with either Google or Guest login.", "Why Login?");
}
void SwitchLoginPanel(){
quickLoginPanelOn = !quickLoginPanelOn;
LeanTween.scale(quickLoginPanel, quickLoginPanelOn ? Vector3.one : Vector3.zero, 0.5f).setEase(LeanTweenType.easeOutElastic);
LeanTween.scale(guestLoginPanel, quickLoginPanelOn ? Vector3.zero : Vector3.one, 0.5f).setEase(LeanTweenType.easeOutElastic);
}
public Text statusText;
public string webClientId = "<your client id here>";
private GoogleSignInConfiguration configuration;
public void OnSignIn() {
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = false;
GoogleSignIn.Configuration.RequestIdToken = true;
// AddStatusText("Calling SignIn");
GoogleSignIn.DefaultInstance.SignIn().ContinueWith(
OnAuthenticationFinished);
}
public void OnSignOut() {
// AddStatusText("Calling SignOut");
GoogleSignIn.DefaultInstance.SignOut();
}
public void OnDisconnect() {
// AddStatusText("Calling Disconnect");
GoogleSignIn.DefaultInstance.Disconnect();
}
internal void OnAuthenticationFinished(Task<GoogleSignInUser> task) {
if (task.IsFaulted) {
using (IEnumerator<System.Exception> enumerator =
task.Exception.InnerExceptions.GetEnumerator()) {
if (enumerator.MoveNext()) {
GoogleSignIn.SignInException error =
(GoogleSignIn.SignInException)enumerator.Current;
// AddStatusText("Got Error: " + error.Status + " " + error.Message);
MessageBox.ShowMessage("Got Error: " + error.Status + " " + error.Message);
} else {
// AddStatusText("Got Unexpected Exception?!?" + task.Exception);
MessageBox.ShowMessage("Got Unexpected Exception?!?" + task.Exception);
}
}
} else if(task.IsCanceled) {
// AddStatusText("Canceled");
} else {
// AddStatusText("Welcome: " + task.Result.DisplayName + "!");
// MessageBox.ShowMessage($"email: {task.Result.Email}\nDisplay:{task.Result.DisplayName}\ntoken:{task.Result.IdToken}");
StartCoroutine(DoneLogin(task.Result.Email));
}
}
IEnumerator DoneLogin(string username){
yield return new WaitForSeconds(0.5f);
DataManager.GoogleLogin(username);
}
public void OnSignInSilently() {
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = false;
GoogleSignIn.Configuration.RequestIdToken = true;
// AddStatusText("Calling SignIn Silently");
GoogleSignIn.DefaultInstance.SignInSilently()
.ContinueWith(OnAuthenticationFinished);
}
public void OnGamesSignIn() {
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = true;
GoogleSignIn.Configuration.RequestIdToken = false;
// AddStatusText("Calling Games SignIn");
GoogleSignIn.DefaultInstance.SignIn().ContinueWith(
OnAuthenticationFinished);
}
private List<string> messages = new List<string>();
}
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Login : MonoBehaviour
{
public Button helpBtn;
public Button googleLoginBtn;
public Button[] switchBtns;
public Text statusTxt;
public GameObject quickLoginPanel, guestLoginPanel;
public Button BtnGuestLogin;
public InputField usernameInput, passwordInput;
bool quickLoginPanelOn =true;
void Awake(){
helpBtn.onClick.AddListener(OnHelp);
googleLoginBtn.onClick.AddListener(OnSignIn);
BtnGuestLogin.onClick.AddListener(OnGuestLogin);
// guestLoginBtn.onClick.AddListener(SwitchLoginPanel);
foreach(Button switchBtn in switchBtns){
switchBtn.onClick.AddListener(SwitchLoginPanel);
}
configuration = new GoogleSignInConfiguration {
WebClientId = webClientId,
RequestIdToken = true,
RequestEmail=true,
};
}
async void AutoLogin(){
Debug.Log("Start auto-login");
if(PlayerPrefs.HasKey("username")){
Debug.Log("Has saved credentials, Trying to login with them");
int loginResult = await DataManager.Login(PlayerPrefs.GetString("username"), PlayerPrefs.GetString("password"));
if(loginResult == 0){
LoadingScreen.LoadLevel("MainMenu");
}else{
Debug.Log("Failed auto-login");
}
}
}
void Start(){
AutoLogin();
}
// Update is called once per frame
void Update()
{
}
void OnGuestLogin(){
if(usernameInput.text.Length < 3){
MessageBox.ShowMessage("Please enter a username longer than 3 characters");
return;
}
if(usernameInput.text.Contains("#")){
MessageBox.ShowMessage("Characters like #,$,%,^,& can't be included in username");
return;
}
if(passwordInput.text.Length < 5){
MessageBox.ShowMessage("Please enter a password with more than 5 characters to stay secure!");
return;
}
DataManager.Login(usernameInput.text, passwordInput.text);
}
void OnHelp(){
MessageBox.ShowMessage("This game saves your progress in cloud, in order to preserve the data. We need you to login with either Google or Guest login.", "Why Login?");
}
void SwitchLoginPanel(){
quickLoginPanelOn = !quickLoginPanelOn;
LeanTween.scale(quickLoginPanel, quickLoginPanelOn ? Vector3.one : Vector3.zero, 0.5f).setEase(LeanTweenType.easeOutElastic);
LeanTween.scale(guestLoginPanel, quickLoginPanelOn ? Vector3.zero : Vector3.one, 0.5f).setEase(LeanTweenType.easeOutElastic);
}
public Text statusText;
public string webClientId = "<your client id here>";
private GoogleSignInConfiguration configuration;
public void OnSignIn() {
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = false;
GoogleSignIn.Configuration.RequestIdToken = true;
// AddStatusText("Calling SignIn");
GoogleSignIn.DefaultInstance.SignIn().ContinueWith(
OnAuthenticationFinished);
}
public void OnSignOut() {
// AddStatusText("Calling SignOut");
GoogleSignIn.DefaultInstance.SignOut();
}
public void OnDisconnect() {
// AddStatusText("Calling Disconnect");
GoogleSignIn.DefaultInstance.Disconnect();
}
internal void OnAuthenticationFinished(Task<GoogleSignInUser> task) {
if (task.IsFaulted) {
using (IEnumerator<System.Exception> enumerator =
task.Exception.InnerExceptions.GetEnumerator()) {
if (enumerator.MoveNext()) {
GoogleSignIn.SignInException error =
(GoogleSignIn.SignInException)enumerator.Current;
// AddStatusText("Got Error: " + error.Status + " " + error.Message);
MessageBox.ShowMessage("Got Error: " + error.Status + " " + error.Message);
} else {
// AddStatusText("Got Unexpected Exception?!?" + task.Exception);
MessageBox.ShowMessage("Got Unexpected Exception?!?" + task.Exception);
}
}
} else if(task.IsCanceled) {
// AddStatusText("Canceled");
} else {
// AddStatusText("Welcome: " + task.Result.DisplayName + "!");
// MessageBox.ShowMessage($"email: {task.Result.Email}\nDisplay:{task.Result.DisplayName}\ntoken:{task.Result.IdToken}");
StartCoroutine(DoneLogin(task.Result.Email));
}
}
IEnumerator DoneLogin(string username){
yield return new WaitForSeconds(0.5f);
DataManager.GoogleLogin(username);
}
public void OnSignInSilently() {
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = false;
GoogleSignIn.Configuration.RequestIdToken = true;
// AddStatusText("Calling SignIn Silently");
GoogleSignIn.DefaultInstance.SignInSilently()
.ContinueWith(OnAuthenticationFinished);
}
public void OnGamesSignIn() {
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = true;
GoogleSignIn.Configuration.RequestIdToken = false;
// AddStatusText("Calling Games SignIn");
GoogleSignIn.DefaultInstance.SignIn().ContinueWith(
OnAuthenticationFinished);
}
private List<string> messages = new List<string>();
}

View File

@@ -1,155 +1,183 @@
using System.Collections;
using System.Collections.Generic;
using Google;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MainMenu : MonoBehaviour
{
public GameObject MainMenuPanel;
public GameObject SettingsPanel;
public GameObject LeaderboarPanel;
public GameObject LinkAccountPanel;
public InputField fhid_input;
public Button btnLink;
public Transform LeaderboardItemsParent;
public float transitionTime;
public LeanTweenType transitionEffect;
private Vector2 defaultCenter;
public Button copyBtn, muteBtn;
public Button signoutBtn;
public Sprite muteIcon, unmuteIcon;
public Text txtUserId;
void Awake(){
if(!DataManager.isLogged){
SceneManager.LoadScene(0);
return;
}
defaultCenter = MainMenuPanel.transform.position;
SettingsPanel.transform.position = MainMenuPanel.transform.position - new Vector3(10000,0);
SettingsPanel.SetActive(true);
LeaderboarPanel.SetActive(true);
LeaderboarPanel.transform.position = MainMenuPanel.transform.position + new Vector3(10000,0);
muteBtn.onClick.AddListener(ToggleMute);
copyBtn.onClick.AddListener(CopyId);
signoutBtn.onClick.AddListener(SignOut);
btnLink.onClick.AddListener(OnLinkClicked);
DataManager.RefreshLeaderboard();
}
public void Leave(){
Application.Quit();
}
void Start(){
Refresh();
// MessageBox.ShowMessage("Welcome to Infinite Golf 2D.\nThis is a slow paced 2d endless golf game, All the levels are proceduraly generated and you will be rewarded for putting the ball in every and each hole.\n\nGood Luck","Welcome");
}
void Refresh(){
txtUserId.text = Encryptor.intToString(DataManager.userData.id);
if(AudioManager.isMute){
muteBtn.transform.GetChild(0).GetComponent<Image>().sprite = muteIcon;
}else{
muteBtn.transform.GetChild(0).GetComponent<Image>().sprite = unmuteIcon;
}
}
public void SettingsPage(){
LeanTween.moveX(MainMenuPanel, 10000, transitionTime).setEase(transitionEffect);
LeanTween.moveX(SettingsPanel, defaultCenter.x, transitionTime).setEase(transitionEffect);
}
public void LeaderboarPage(){
LeanTween.moveX(MainMenuPanel, -10000, transitionTime).setEase(transitionEffect);
LeanTween.moveX(LeaderboarPanel, defaultCenter.x, transitionTime).setEase(transitionEffect);
RefreshLeaderboard();
}
public void MainPage(){
LeanTween.moveX(MainMenuPanel, defaultCenter.x, transitionTime).setEase(transitionEffect);
LeanTween.moveX(SettingsPanel, -10000, transitionTime).setEase(transitionEffect);
LeanTween.moveX(LeaderboarPanel, 10000, transitionTime).setEase(transitionEffect);
}
public void OpenLinkPanel(){
if(DataManager.userData.faucetId > 0){
MessageBox.ShowMessage("You've already linked this player account to Faucet Hub.", "Already Linked");
return;
}
LinkAccountPanel.transform.localScale = Vector3.zero;
LinkAccountPanel.SetActive(true);
LeanTween.scale(LinkAccountPanel, Vector3.one, transitionTime/2f).setEase(LeanTweenType.easeInCirc);
}
public async void OnLinkClicked(){
btnLink.interactable=false;
if(fhid_input.text.Length <= 0){
Debug.Log("Empty FHID was entered");
MessageBox.ShowMessage("Please enter a valid faucet hub ID","Invalid FH ID");
return;
}
int result = await DataManager.LinkFH(fhid_input.text);
if(result == 0){
MessageBox.ShowMessage("Congrats! You've successfully linked this player account with Faucet Hub. Enjoy!", "Success");
LinkAccountPanel.SetActive(false);
}else{
MessageBox.ShowMessage("Something went wrong trying to link this play account to FH ID of " + fhid_input.text, "Link failed");
}
btnLink.interactable=true;
}
public void CopyId(){
GUIUtility.systemCopyBuffer = txtUserId.text;
copyBtn.transform.Find("lbl").GetComponent<Text>().text = "Copied";
}
public void ToggleMute(){
AudioManager.ToggleMute();
Refresh();
}
public void Info(){
MessageBox.ShowMessage(@"This is a game where you can relax while playing,
Listen to a podcast or to music while playing this to get the best out of it!
Any feedback or suggestion can be directed to us via this email
sewmina7@gmail.com","About");
}
async void RefreshLeaderboard(){
UpdateLeaderboardUI();
await DataManager.RefreshLeaderboard();
UpdateLeaderboardUI();
}
void UpdateLeaderboardUI(){
for(int i =0; i < DataManager.Leaderboard.Count; i++){
LeaderboardItemsParent.GetChild(i).GetChild(0).GetComponent<Text>().text = $"{i+1}." + DataManager.Leaderboard[i].DisplayName;
// LeaderboardItemsParent.GetChild(i).GetChild(0).GetComponent<Text>().text = $"{i+1}." + DataManager.Leaderboard[i].name;
LeaderboardItemsParent.GetChild(i).GetChild(1).GetComponent<Text>().text = DataManager.Leaderboard[i].topScore.ToString();
LeaderboardItemsParent.GetChild(i).GetComponent<Image>().CrossFadeAlpha((DataManager.Leaderboard[i].name == DataManager.userData.username) ? 0.9f : 0,0.5f,true);
}
}
void SignOut(){
DataManager.Signout();
SceneManager.LoadScene(0);
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MainMenu : MonoBehaviour
{
public GameObject MainMenuPanel;
public GameObject SettingsPanel;
public GameObject LeaderboarPanel;
public GameObject LinkAccountPanel;
public InputField fhid_input;
public Button btnLink;
public Transform LeaderboardItemsParent;
public float transitionTime;
public LeanTweenType transitionEffect;
private Vector2 defaultCenter;
public Button copyBtn, muteBtn;
public Button signoutBtn;
public Sprite muteIcon, unmuteIcon;
public Image totalScoreBG, scoreBG;
public Text txtUserId;
public Text txtSeasonTimer;
void Awake(){
if(!DataManager.isLogged){
SceneManager.LoadScene(0);
return;
}
defaultCenter = MainMenuPanel.transform.position;
SettingsPanel.transform.position = MainMenuPanel.transform.position - new Vector3(10000,0);
SettingsPanel.SetActive(true);
LeaderboarPanel.SetActive(true);
LeaderboarPanel.transform.position = MainMenuPanel.transform.position + new Vector3(10000,0);
muteBtn.onClick.AddListener(ToggleMute);
copyBtn.onClick.AddListener(CopyId);
signoutBtn.onClick.AddListener(SignOut);
btnLink.onClick.AddListener(OnLinkClicked);
DataManager.RefreshLeaderboard();
}
public void Leave(){
Application.Quit();
}
void Start(){
Refresh();
// MessageBox.ShowMessage("Welcome to Infinite Golf 2D.\nThis is a slow paced 2d endless golf game, All the levels are proceduraly generated and you will be rewarded for putting the ball in every and each hole.\n\nGood Luck","Welcome");
}
void Refresh(){
txtUserId.text = Encryptor.intToString(DataManager.userData.id);
if(AudioManager.isMute){
muteBtn.transform.GetChild(0).GetComponent<Image>().sprite = muteIcon;
}else{
muteBtn.transform.GetChild(0).GetComponent<Image>().sprite = unmuteIcon;
}
DateTime now = DateTime.Now;
DateTime nextSeason = new DateTime(now.Year, (now.Month < 12) ? now.Month+1 : 1,1);
txtSeasonTimer.text = "Season Ends In : <size=80>" +(nextSeason - now).Days + "</size> Days";
}
public void ShowInfoSeason(){
MessageBox.ShowMessage("When the new season begins your Score and Top Score will reset\n By the end of this season, Current scores will be preserved and can be seen on this season's leaderboard", "Season info");
}
public void SettingsPage(){
LeanTween.moveX(MainMenuPanel, 10000, transitionTime).setEase(transitionEffect);
LeanTween.moveX(SettingsPanel, defaultCenter.x, transitionTime).setEase(transitionEffect);
}
public void LeaderboarPage(){
LeanTween.moveX(MainMenuPanel, -10000, transitionTime).setEase(transitionEffect);
LeanTween.moveX(LeaderboarPanel, defaultCenter.x, transitionTime).setEase(transitionEffect);
// RefreshLeaderboard();
ToggleTotalScoreLeaderboardAsync(false);
}
public void MainPage(){
LeanTween.moveX(MainMenuPanel, defaultCenter.x, transitionTime).setEase(transitionEffect);
LeanTween.moveX(SettingsPanel, -10000, transitionTime).setEase(transitionEffect);
LeanTween.moveX(LeaderboarPanel, 10000, transitionTime).setEase(transitionEffect);
}
public void OpenLinkPanel(){
if(DataManager.userData.faucetId > 0){
MessageBox.ShowMessage("You've already linked this player account to Faucet Hub.", "Already Linked");
return;
}
LinkAccountPanel.transform.localScale = Vector3.zero;
LinkAccountPanel.SetActive(true);
LeanTween.scale(LinkAccountPanel, Vector3.one, transitionTime/2f).setEase(LeanTweenType.easeInCirc);
}
public async void OnLinkClicked(){
btnLink.interactable=false;
if(fhid_input.text.Length <= 0){
Debug.Log("Empty FHID was entered");
MessageBox.ShowMessage("Please enter a valid faucet hub ID","Invalid FH ID");
return;
}
int result = await DataManager.LinkFH(fhid_input.text);
if(result == 0){
MessageBox.ShowMessage("Congrats! You've successfully linked this player account with Faucet Hub. Enjoy!", "Success");
LinkAccountPanel.SetActive(false);
}else{
MessageBox.ShowMessage("Something went wrong trying to link this play account to FH ID of " + fhid_input.text, "Link failed");
}
btnLink.interactable=true;
}
public void CopyId(){
GUIUtility.systemCopyBuffer = txtUserId.text;
copyBtn.transform.Find("lbl").GetComponent<Text>().text = "Copied";
}
public void ToggleMute(){
AudioManager.ToggleMute();
Refresh();
}
public void Info(){
MessageBox.ShowMessage(@"This is a game where you can relax while playing,
Listen to a podcast or to music while playing this to get the best out of it!
Any feedback or suggestion can be directed to us via this email
sewmina7@gmail.com","About");
}
async void RefreshLeaderboard(){
UpdateLeaderboardUI();
await DataManager.RefreshLeaderboard();
UpdateLeaderboardUI();
}
void UpdateLeaderboardUI(){
if(DataManager.Leaderboard == null){return;}
if(DataManager.Leaderboard.Count <= 0){return;}
for(int i =0; i < DataManager.Leaderboard.Count; i++){
LeaderboardItemsParent.GetChild(i).GetChild(0).GetComponent<Text>().text = $"{DataManager.Leaderboard[i].position}." + DataManager.Leaderboard[i].DisplayName;
// LeaderboardItemsParent.GetChild(i).GetChild(0).GetComponent<Text>().text = $"{i+1}." + DataManager.Leaderboard[i].name;
LeaderboardItemsParent.GetChild(i).GetChild(1).GetComponent<Text>().text = DataManager.Leaderboard[i].Score.ToString();
LeaderboardItemsParent.GetChild(i).GetChild(2).GetComponent<Text>().text = DataManager.Leaderboard[i].topScore.ToString();
LeaderboardItemsParent.GetChild(i).GetComponent<Image>().CrossFadeAlpha((DataManager.Leaderboard[i].name == DataManager.userData.username) ? 0.9f : 0,0.5f,true);
}
}
public async void ToggleTotalScoreLeaderboardAsync(bool total){
totalScoreBG.color = new Color(totalScoreBG.color.r, totalScoreBG.color.g, totalScoreBG.color.b, total? 1 : 0.1f);
scoreBG.color = new Color(scoreBG.color.r, scoreBG.color.g, scoreBG.color.b, total? 0.1f : 1f);
await DataManager.RefreshLeaderboard(total);
UpdateLeaderboardUI();
}
void SignOut(){
DataManager.Signout();
SceneManager.LoadScene(0);
}
}

View File

@@ -1,58 +1,58 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MessageBox : MonoBehaviour
{
public static MessageBox instance { get; private set;}
void Awake(){
if(instance != null){Destroy(gameObject);}
instance = this;
canvasGroup = GetComponent<CanvasGroup>();
closeButton.onClick.AddListener(()=>{SetActive(false);});
}
private CanvasGroup canvasGroup;
[SerializeField]private Text messageTxt;
[SerializeField]private Text titleTxt;
[SerializeField]private Button closeButton;
void Start()
{
DontDestroyOnLoad(gameObject);
SetActive(false);
}
void SetActive(bool value){
// StartCoroutine(setActive(value));
canvasGroup.alpha= value ? 1 : 0;
canvasGroup.blocksRaycasts = value;
canvasGroup.interactable = value;
}
private static string message;
public static void ShowMessage(string message,string title = "Notice"){
if(instance == null){Debug.LogError("Message was shown before message box was init");return;}
instance.showMessage(message,title);
}
public void showMessage(string _message, string title){
message = _message;
titleTxt.text = title;
StartCoroutine(_showMessage());
SetActive(true);
}
IEnumerator _showMessage(){
messageTxt.text = "";
closeButton.gameObject.SetActive(false);
for(int i=0; i < message.Length; i++){
messageTxt.text += message[i];
yield return new WaitForSeconds(0.01f);
}
closeButton.gameObject.SetActive(true);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MessageBox : MonoBehaviour
{
public static MessageBox instance { get; private set;}
void Awake(){
if(instance != null){Destroy(gameObject);}
instance = this;
canvasGroup = GetComponent<CanvasGroup>();
closeButton.onClick.AddListener(()=>{SetActive(false);});
}
private CanvasGroup canvasGroup;
[SerializeField]private Text messageTxt;
[SerializeField]private Text titleTxt;
[SerializeField]private Button closeButton;
void Start()
{
DontDestroyOnLoad(gameObject);
SetActive(false);
}
void SetActive(bool value){
// StartCoroutine(setActive(value));
canvasGroup.alpha= value ? 1 : 0;
canvasGroup.blocksRaycasts = value;
canvasGroup.interactable = value;
}
private static string message;
public static void ShowMessage(string message,string title = "Notice"){
if(instance == null){Debug.LogError("Message was shown before message box was init");return;}
instance.showMessage(message,title);
}
public void showMessage(string _message, string title){
message = _message;
titleTxt.text = title;
StartCoroutine(_showMessage());
SetActive(true);
}
IEnumerator _showMessage(){
messageTxt.text = "";
closeButton.gameObject.SetActive(false);
for(int i=0; i < message.Length; i++){
messageTxt.text += message[i];
yield return new WaitForSeconds(0.01f);
}
closeButton.gameObject.SetActive(true);
}
}

View File

@@ -1,110 +1,110 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TweenHelper : MonoBehaviour
{
// Start is called before the first frame update
public float delay = 1;
public LeanTweenType position_type, scale_type;
public Vector3 startPos;
public float position_time=1;
public float scale_time=1;
public Vector3 startScale;
Vector3 defaultPos, defaultScale;
[Header("Monitor data")]
public Vector3 curPosition;
public Vector3 curScale;
void Awake(){
defaultPos = transform.position;
defaultScale=transform.localScale;
transform.position = startPos;
transform.localScale = startScale;
}
void Start()
{
Intro();
}
public void Intro(){
TweenManager.Add(this);
StartCoroutine(start());
}
public void Outro(){
if(position_type != LeanTweenType.notUsed){
LeanTween.move(gameObject, startPos, position_time).setEase(position_type);
}
if(scale_type != LeanTweenType.notUsed){
LeanTween.scale(gameObject, startScale, scale_time).setEase(scale_type);
}
}
IEnumerator start(){
yield return new WaitForSeconds(delay);
LeanTween.move(gameObject, defaultPos, position_time).setEase(position_type);
LeanTween.scale(gameObject, defaultScale, scale_time).setEase(scale_type);
}
void OnDrawGizmos(){
curPosition = transform.position;
curScale = transform.localScale;
Gizmos.DrawLine(startPos, curPosition);
}
bool init = false;
void OnValidation(){
if(!init){
init=true;
}else{
return;
}
startPos = transform.position;
startScale = transform.localScale;
}
public void OutroAll(){
TweenManager.OutroAll();
}
}
public static class TweenManager{
public static List<TweenHelper> Tweens{get; private set;}
public static void Add(TweenHelper tween){
if(Tweens == null){Tweens = new List<TweenHelper>();}
if(Tweens.Contains(tween)){return;}
Tweens.Add(tween);
}
public static void Outro(TweenHelper tween){
tween.Outro();
Tweens.Remove(tween);
}
public static void OutroAll(){
foreach(TweenHelper tween in Tweens){
if(tween == null){continue;}
tween.Outro();
}
for(int i=Tweens.Count-1; i >= 0; i--){
Tweens.RemoveAt(i);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TweenHelper : MonoBehaviour
{
// Start is called before the first frame update
public float delay = 1;
public LeanTweenType position_type, scale_type;
public Vector3 startPos;
public float position_time=1;
public float scale_time=1;
public Vector3 startScale;
Vector3 defaultPos, defaultScale;
[Header("Monitor data")]
public Vector3 curPosition;
public Vector3 curScale;
void Awake(){
defaultPos = transform.position;
defaultScale=transform.localScale;
transform.position = startPos;
transform.localScale = startScale;
}
void Start()
{
Intro();
}
public void Intro(){
TweenManager.Add(this);
StartCoroutine(start());
}
public void Outro(){
if(position_type != LeanTweenType.notUsed){
LeanTween.move(gameObject, startPos, position_time).setEase(position_type);
}
if(scale_type != LeanTweenType.notUsed){
LeanTween.scale(gameObject, startScale, scale_time).setEase(scale_type);
}
}
IEnumerator start(){
yield return new WaitForSeconds(delay);
LeanTween.move(gameObject, defaultPos, position_time).setEase(position_type);
LeanTween.scale(gameObject, defaultScale, scale_time).setEase(scale_type);
}
void OnDrawGizmos(){
curPosition = transform.position;
curScale = transform.localScale;
Gizmos.DrawLine(startPos, curPosition);
}
bool init = false;
void OnValidation(){
if(!init){
init=true;
}else{
return;
}
startPos = transform.position;
startScale = transform.localScale;
}
public void OutroAll(){
TweenManager.OutroAll();
}
}
public static class TweenManager{
public static List<TweenHelper> Tweens{get; private set;}
public static void Add(TweenHelper tween){
if(Tweens == null){Tweens = new List<TweenHelper>();}
if(Tweens.Contains(tween)){return;}
Tweens.Add(tween);
}
public static void Outro(TweenHelper tween){
tween.Outro();
Tweens.Remove(tween);
}
public static void OutroAll(){
foreach(TweenHelper tween in Tweens){
if(tween == null){continue;}
tween.Outro();
}
for(int i=Tweens.Count-1; i >= 0; i--){
Tweens.RemoveAt(i);
}
}
}