-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameControllerManager_4.cs
641 lines (478 loc) · 21.8 KB
/
GameControllerManager_4.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
using UnityEngine;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using UnityEngine.UI;
public class GameControllerManager_4 : MonoBehaviour
{
//Controlling the Game.
public Text ScoreText;
public ShapesArray_4 shapes;
public Bettr_Encryption.Encrypt score;
public string Score_Encrypt;
public readonly Vector2 BottomRight = new Vector2(-2.46f, -4.4f);
public readonly Vector2 CandySize = new Vector2(0.7f, 0.7f);
private GameState_4 state = GameState_4.None;
private GameObject hitGo = null;
private Vector2[] SpawnPositions;
public GameObject[] CandyPrefabs;
public GameObject[] ExplosionPrefabs;
public GameObject[] BonusPrefabs;
public GameObject Bigbonusprefabs;
private IEnumerator CheckPotentialMatchesCoroutine;
private IEnumerator AnimatePotentialMatchesCoroutine;
IEnumerable<GameObject> potentialMatches;
public AudioClip[] Sounds;
private AudioSource Audio_Source;
public bool Gameover = false;
// Use this for initialization
void Start()
{
Audio_Source = this.GetComponent<AudioSource>();
InitializeTypesOnPrefabShapesAndBonuses();
InitializeCandyAndSpawnPositions();
StartCheckForPotentialMatches();
}
//Initialize shapes
private void InitializeTypesOnPrefabShapesAndBonuses()
{
//just assign the name of the prefab
foreach (var item in CandyPrefabs)
{
item.GetComponent<Shape_4>().Type = item.name;
}
//assign the name of the respective "normal" candy as the type of the Bonus
foreach (var item in BonusPrefabs)
{
item.GetComponent<Shape_4>().Type = CandyPrefabs.
Where(x => x.GetComponent<Shape_4>().Type.Contains(item.name.Split('_')[1].Trim())).Single().name;
}
}
//Initialize CandyAndSpawnPositions
public void InitializeCandyAndSpawnPositions()
{
InitializeVariables();
if (shapes != null)
DestroyAllCandy();
shapes = new ShapesArray_4();
SpawnPositions = new Vector2[ConstantsVariable_4.Columns];
for (int row = 0; row < ConstantsVariable_4.Rows; row++)
{
for (int column = 0; column < ConstantsVariable_4.Columns; column++)
{
GameObject newCandy = GetRandomCandy();
//check if two previous horizontal are of the same type
while (column >= 2 && shapes[row, column - 1].GetComponent<Shape_4>()
.IsSameType(newCandy.GetComponent<Shape_4>())
&& shapes[row, column - 2].GetComponent<Shape_4>().IsSameType(newCandy.GetComponent<Shape_4>()))
{
newCandy = GetRandomCandy();
}
//check if two previous vertical are of the same type
while (row >= 2 && shapes[row - 1, column].GetComponent<Shape_4>()
.IsSameType(newCandy.GetComponent<Shape_4>())
&& shapes[row - 2, column].GetComponent<Shape_4>().IsSameType(newCandy.GetComponent<Shape_4>()))
{
newCandy = GetRandomCandy();
}
InstantiateAndPlaceNewCandy(row, column, newCandy);
}
}
SetupSpawnPositions();
}
private void InstantiateAndPlaceNewCandy(int row, int column, GameObject newCandy)
{
GameObject go = Instantiate(newCandy,
BottomRight + new Vector2(column * CandySize.x, row * CandySize.y), Quaternion.identity)
as GameObject;
//assign the specific properties
go.GetComponent<Shape_4>().Assign(newCandy.GetComponent<Shape_4>().Type, row, column);
shapes[row, column] = go;
}
private void SetupSpawnPositions()
{
//create the spawn positions for the new shapes (will pop from the 'ceiling')
for (int column = 0; column < ConstantsVariable_4.Columns; column++)
{
SpawnPositions[column] = BottomRight
+ new Vector2(column * CandySize.x, ConstantsVariable_4.Rows * CandySize.y);
}
}
/// Destroy all candy gameobjects
private void DestroyAllCandy()
{
for (int row = 0; row < ConstantsVariable_4.Rows; row++)
{
for (int column = 0; column < ConstantsVariable_4.Columns; column++)
{
Destroy(shapes[row, column]);
}
}
}
// Update is called once per frame
void Update()
{
if (Gameover == false)
{
if (state == GameState_4.None)
{
//user has clicked or touched
if (Input.GetMouseButton(0))
{
//get the hit position
var hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit.collider != null) //we have a hit!!!
{
hitGo = hit.collider.gameObject;
state = GameState_4.SelectionStarted;
}
}
}
else if (state == GameState_4.SelectionStarted)
{
//user dragged
if (Input.GetMouseButton(0))
{
var hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
//we have a hit
if (hit.collider != null && hitGo != hit.collider.gameObject)
{
//user did a hit, no need to show him hints
StopCheckForPotentialMatches();
//if the two shapes are diagonally aligned (different row and column), just return
if (!GameUtilities_4.AreVerticalOrHorizontalNeighbors(hitGo.GetComponent<Shape_4>(),
hit.collider.gameObject.GetComponent<Shape_4>()))
{
state = GameState_4.None;
}
else
{
state = GameState_4.Animating;
FixSortingLayer(hitGo, hit.collider.gameObject);
StartCoroutine(FindMatchesAndCollapse(hit));
}
}
}
}
//Touch touch = Input.GetTouch(0);
//if (state == GameState.None)
//{
// //user has clicked or touched
// if (Input.touchCount > 0)
// {
// //get the hit position
// var hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(touch.position), Vector2.zero);
// if (hit.collider != null) //we have a hit!!!
// {
// hitGo = hit.collider.gameObject;
// state = GameState.SelectionStarted;
// }
// }
//}
//else if (state == GameState.SelectionStarted)
//{
// //user dragged
// if (Input.touchCount > 0)
// {
// var hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(touch.position), Vector2.zero);
// //we have a hit
// if (hit.collider != null && hitGo != hit.collider.gameObject)
// {
// //user did a hit, no need to show him hints
// StopCheckForPotentialMatches();
// //if the two shapes are diagonally aligned (different row and column), just return
// if (!GameUtilities.AreVerticalOrHorizontalNeighbors(hitGo.GetComponent<Shape>(),
// hit.collider.gameObject.GetComponent<Shape>()))
// {
// state = GameState.None;
// }
// else
// {
// state = GameState.Animating;
// FixSortingLayer(hitGo, hit.collider.gameObject);
// StartCoroutine(FindMatchesAndCollapse(hit));
// }
// }
// }
//}
}
}
/// Modifies sorting layers for better appearance when dragging/animating
private void FixSortingLayer(GameObject hitGo, GameObject hitGo2)
{
SpriteRenderer sp1 = hitGo.GetComponent<SpriteRenderer>();
SpriteRenderer sp2 = hitGo2.GetComponent<SpriteRenderer>();
if (sp1.sortingOrder <= sp2.sortingOrder)
{
sp1.sortingOrder = 1;
sp2.sortingOrder = 0;
}
}
private IEnumerator FindMatchesAndCollapse(RaycastHit2D hit2)
{
//get the second item that was part of the swipe
var hitGo2 = hit2.collider.gameObject;
shapes.Swap(hitGo, hitGo2);
//move the swapped ones
hitGo.transform.positionTo(ConstantsVariable_4.AnimationDuration, hitGo2.transform.position);
hitGo2.transform.positionTo(ConstantsVariable_4.AnimationDuration, hitGo.transform.position);
yield return new WaitForSeconds(ConstantsVariable_4.AnimationDuration);
//get the matches via the helper methods
var hitGoMatchesSet = shapes.GetMatches(hitGo);
var hitGo2MatchesSet = shapes.GetMatches(hitGo2);
var totalMatches = hitGoMatchesSet.MatchedCandy
.Union(hitGo2MatchesSet.MatchedCandy).Distinct();
//if user's swap didn't create at least a 3-match, undo their swap
if (totalMatches.Count() < ConstantsVariable_4.MinimumMatches)
{
Audio_Source.PlayOneShot(Sounds[0]);
hitGo.transform.positionTo(ConstantsVariable_4.AnimationDuration, hitGo2.transform.position);
hitGo2.transform.positionTo(ConstantsVariable_4.AnimationDuration, hitGo.transform.position);
yield return new WaitForSeconds(ConstantsVariable_4.AnimationDuration);
shapes.UndoSwap();
}else{
Audio_Source.PlayOneShot(Sounds[1]);
}
if (totalMatches.Count() > ConstantsVariable_4.MinimumMatches)
{
Audio_Source.PlayOneShot(Sounds[4]);
}
//if more than 3 matches and no Bonus is contained in the line, we will award a new Bonus
bool addBonus = totalMatches.Count() == ConstantsVariable_4.MinimumMatchesForBonus &&
!BonusTypeUtilities_4.ContainsDestroyWholeRowColumn(hitGoMatchesSet.BonusesContained) &&
!BonusTypeUtilities_4.ContainsDestroyWholeRowColumn(hitGo2MatchesSet.BonusesContained);
bool addbigbonus = totalMatches.Count() >= ConstantsVariable_4.MinimumMatchesForBigBonus &&
!BonusTypeUtilities_4.ContainsDestroyWholeRowColumn(hitGoMatchesSet.BonusesContained) &&
!BonusTypeUtilities_4.ContainsDestroyWholeRowColumn(hitGo2MatchesSet.BonusesContained) &&
!BonusTypeUtilities_4.ContainsDestroyBothWholeRowColumn(hitGoMatchesSet.BonusesContained) &&
!BonusTypeUtilities_4.ContainsDestroyBothWholeRowColumn(hitGo2MatchesSet.BonusesContained);
Shape_4 hitGoCache = null;
if (addBonus)
{
//get the game object that was of the same type
var sameTypeGo = hitGoMatchesSet.MatchedCandy.Count() > 0 ? hitGo : hitGo2;
hitGoCache = sameTypeGo.GetComponent<Shape_4>();
}
if (addbigbonus)
{
var allTypeGo = hitGoMatchesSet.MatchedCandy.Count()>0?hitGo : hitGo2;
hitGoCache = allTypeGo.GetComponent<Shape_4>();
}
int timesRun = 1;
while (totalMatches.Count() >= ConstantsVariable_4.MinimumMatches)
{
//increase score
IncreaseScore((totalMatches.Count() - 2) * ConstantsVariable_4.Match3Score);
if (timesRun >= 2)
IncreaseScore(ConstantsVariable_4.SubsequentMatchScore);
foreach (var item in totalMatches)
{
shapes.Remove(item);
RemoveFromScene(item);
}
//check and instantiate Bonus if needed
if (addBonus)
CreateBonus(hitGoCache);
if (addbigbonus)
{
Debug.Log("Bigbonus");
CreateBigBonus(hitGoCache);
}
addbigbonus = false;
addBonus = false;
//get the columns that we had a collapse
var columns = totalMatches.Select(go => go.GetComponent<Shape_4>().Column).Distinct();
//the order the 2 methods below get called is important!!!
//collapse the ones gone
var collapsedCandyInfo = shapes.Collapse(columns);
//create new ones
var newCandyInfo = CreateNewCandyInSpecificColumns(columns);
int maxDistance = Mathf.Max(collapsedCandyInfo.MaxDistance, newCandyInfo.MaxDistance);
MoveAndAnimate(newCandyInfo.AlteredCandy, maxDistance);
MoveAndAnimate(collapsedCandyInfo.AlteredCandy, maxDistance);
//will wait for both of the above animations
yield return new WaitForSeconds(ConstantsVariable_4.MoveAnimationMinDuration * maxDistance);
//search if there are matches with the new/collapsed items
totalMatches = shapes.GetMatches(collapsedCandyInfo.AlteredCandy).
Union(shapes.GetMatches(newCandyInfo.AlteredCandy)).Distinct();
timesRun++;
}
state = GameState_4.None;
StartCheckForPotentialMatches();
}
/// Creates a new Bonus based on the shape parameter
private void CreateBonus(Shape_4 hitGoCache)
{
GameObject Bonus = Instantiate(GetBonusFromType(hitGoCache.Type), BottomRight
+ new Vector2(hitGoCache.Column * CandySize.x,
hitGoCache.Row * CandySize.y), Quaternion.identity)
as GameObject;
shapes[hitGoCache.Row, hitGoCache.Column] = Bonus;
var BonusShape = Bonus.GetComponent<Shape_4>();
//will have the same type as the "normal" candy
BonusShape.Assign(hitGoCache.Type, hitGoCache.Row, hitGoCache.Column);
//add the proper Bonus type
BonusShape.Bonus |= BonusType_4.DestroyWholeRowColumn;
}
private void CreateBigBonus(Shape_4 hitGoCache)
{
GameObject BigBonus = Instantiate(Bigbonusprefabs, BottomRight + new Vector2(hitGoCache.Column * CandySize.x, hitGoCache.Row * CandySize.y), Quaternion.identity) as GameObject;
shapes[hitGoCache.Row, hitGoCache.Column] = BigBonus;
var BigBonusShape = BigBonus.GetComponent<Shape_4>();
BigBonusShape.Assign("BigBomb",hitGoCache.Row, hitGoCache.Column);
BigBonusShape.Bigbonus |= BonusType_4.DestroyBothWholeRowColumn;
}
/// Spawns new candy in columns that have missing ones
private DistinctCandyCreator_4 CreateNewCandyInSpecificColumns(IEnumerable<int> columnsWithMissingCandy)
{
DistinctCandyCreator_4 newCandyInfo = new DistinctCandyCreator_4();
//find how many null values the column has
foreach (int column in columnsWithMissingCandy)
{
var emptyItems = shapes.GetEmptyItemsOnColumn(column);
foreach (var item in emptyItems)
{
var go = GetRandomCandy();
GameObject newCandy = Instantiate(go, SpawnPositions[column], Quaternion.identity)
as GameObject;
newCandy.GetComponent<Shape_4>().Assign(go.GetComponent<Shape_4>().Type, item.Row, item.Column);
if (ConstantsVariable_4.Rows - item.Row > newCandyInfo.MaxDistance)
newCandyInfo.MaxDistance = ConstantsVariable_4.Rows - item.Row;
shapes[item.Row, item.Column] = newCandy;
newCandyInfo.AddCandy(newCandy);
}
}
return newCandyInfo;
}
/// Animates gameobjects to their new position
private void MoveAndAnimate(IEnumerable<GameObject> movedGameObjects, int distance)
{
foreach (var item in movedGameObjects)
{
item.transform.positionTo(ConstantsVariable_4.MoveAnimationMinDuration * distance, BottomRight +
new Vector2(item.GetComponent<Shape_4>().Column * CandySize.x, item.GetComponent<Shape_4>().Row * CandySize.y));
}
}
/// Destroys the item from the scene and instantiates a new explosion gameobject
private void RemoveFromScene(GameObject item)
{
GameObject explosion = GetRandomExplosion();
var newExplosion = Instantiate(explosion, item.transform.position, Quaternion.identity) as GameObject;
Destroy(newExplosion, ConstantsVariable_4.ExplosionDuration);
if (item.GetComponent<Shape_4>().Is_Bomb)
{
Audio_Source.PlayOneShot(Sounds[2]);
}
else
{
Audio_Source.PlayOneShot(Sounds[3]);
}
Destroy(item);
}
/// Get a random candy
private GameObject GetRandomCandy()
{
return CandyPrefabs[Random.Range(0, CandyPrefabs.Length)];
}
private void InitializeVariables()
{
score = new Bettr_Encryption.Encrypt(0);
Score_Encrypt = "0";
Score_Encrypt = XOREncryption.encryptDecrypt(Score_Encrypt);
ShowScore();
}
private void IncreaseScore(int amount)
{
score += new Bettr_Encryption.Encrypt(amount);
Score_Encrypt = XOREncryption.encryptDecrypt(Score_Encrypt);
Score_Encrypt = (int.Parse(Score_Encrypt) + amount).ToString();
Score_Encrypt = XOREncryption.encryptDecrypt(Score_Encrypt);
ShowScore();
}
private void ShowScore()
{
ScoreText.text = score.ToString();
}
/// Get a random explosion
private GameObject GetRandomExplosion()
{
return ExplosionPrefabs[Random.Range(0, ExplosionPrefabs.Length)];
}
/// Gets the specified Bonus for the specific type
private GameObject GetBonusFromType(string type)
{
string color = type.Split('_')[1].Trim();
foreach (var item in BonusPrefabs)
{
if (item.GetComponent<Shape_4>().Type.Contains(color))
return item;
}
throw new System.Exception("Wrong type");
}
/// Starts the coroutines, keeping a reference to stop later
private void StartCheckForPotentialMatches()
{
StopCheckForPotentialMatches();
//get a reference to stop it later
CheckPotentialMatchesCoroutine = CheckPotentialMatches();
StartCoroutine(CheckPotentialMatchesCoroutine);
}
/// Stops the coroutines
private void StopCheckForPotentialMatches()
{
if (AnimatePotentialMatchesCoroutine != null)
StopCoroutine(AnimatePotentialMatchesCoroutine);
if (CheckPotentialMatchesCoroutine != null)
StopCoroutine(CheckPotentialMatchesCoroutine);
ResetOpacityOnPotentialMatches();
}
/// Resets the opacity on potential matches (probably user dragged something?)
private void ResetOpacityOnPotentialMatches()
{
if (potentialMatches != null)
foreach (var item in potentialMatches)
{
if (item == null) break;
Color c = item.GetComponent<SpriteRenderer>().color;
c.a = 1.0f;
item.GetComponent<SpriteRenderer>().color = c;
}
}
/// Finds potential matches
private IEnumerator CheckPotentialMatches()
{
yield return new WaitForSeconds(ConstantsVariable_4.WaitBeforePotentialMatchesCheck);
potentialMatches = GameUtilities_4.GetPotentialMatches(shapes);
if (potentialMatches != null)
{
while (true)
{
AnimatePotentialMatchesCoroutine = GameUtilities_4.AnimatePotentialMatches(potentialMatches);
StartCoroutine(AnimatePotentialMatchesCoroutine);
yield return new WaitForSeconds(ConstantsVariable_4.WaitBeforePotentialMatchesCheck);
}
}
}
/// Gets a specific candy or Bonus based on the premade level information.
private GameObject GetSpecificCandyOrBonusForPremadeLevel(string info)
{
var tokens = info.Split('_');
if (tokens.Count() == 1)
{
foreach (var item in CandyPrefabs)
{
if (item.GetComponent<Shape_4>().Type.Contains(tokens[0].Trim()))
return item;
}
}
else if (tokens.Count() == 2 && tokens[1].Trim() == "B")
{
foreach (var item in BonusPrefabs)
{
if (item.name.Contains(tokens[0].Trim()))
return item;
}
}
throw new System.Exception("Wrong type, check your premade level");
}
}