forked from asalga/Horadrix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Horadrix-min.pde
4413 lines (3450 loc) · 108 KB
/
Horadrix-min.pde
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*/
public class Stack<T>{
private ArrayList<T> items;
public Stack(){
items = new ArrayList<T>();
}
public void pop(){
items.remove(items.size() - 1);
}
public T top(){
return items.get(items.size() - 1);
}
public void push(T item){
items.add(item);
}
public boolean isEmpty(){
return items.isEmpty();
}
public int size(){
return items.size();
}
public void clear(){
items.clear();
}
}
/*
Not currently being used yet.
*/
public class Queue<T>{
private ArrayList<T> items;
public Queue(){
items = new ArrayList<T>();
}
public void pushBack(T i){
items.add(i);
}
public T popFront(){
T item = items.get(0);
items.remove(0);
return item;
}
public boolean isEmpty(){
return items.isEmpty();
}
public int size(){
return items.size();
}
public T peekFront(){
return items.get(0);
}
public void clear(){
items.clear();
}
}
/*
Displays game name and credits
*/
public class ScreenGameOver implements IScreen{
boolean screenAlive;
RetroFont solarWindsFont;
RetroLabel gameOverLabel;
public ScreenGameOver(){
screenAlive = true;
// TODO: convert this to a singleton or factory.
solarWindsFont = new RetroFont("data/fonts/solarwinds.png", 14, 16, 2);
gameOverLabel = new RetroLabel(solarWindsFont);
gameOverLabel.setText("G A M E O V E R");
gameOverLabel.pixelsFromCenter(0, 0);
}
/**
*/
public void draw(){
background(0);
gameOverLabel.draw();
}
public void update(){
/* ticker.tick();
if(ticker.getTotalTime() > 0.5f){
screenAlive = false;
debugPrint("Splash screen closed.");
}*/
}
public String getName(){
return "game over";
}
public boolean isAlive(){
return screenAlive;
}
public void keyReleased(){}
public void keyPressed(){}
public void mousePressed(){}
public void mouseReleased(){}
public void mouseDragged(){}
public void mouseMoved(){}
}
/*
*/
public static class FPSTimer{
private static float resolution;
private static int fps;
//private static Ticker ticker = new Horadrix.Ticker();
public void setResolution(float res){
if(res >= 0){
resolution = res;
}
}
/*
*/
public int getFPS(){
return 42;//globalApplet.frameRate;
}
}
/*
Shows the score, level on top of the gameplay screen.
*/
public class HUDLayer implements LayerObserver{
RetroPanel parent;
RetroLabel scoreLabel;
RetroLabel levelLabel;
RetroLabel timeLabel;
RetroLabel gemsAcquired;
RetroLabel FPS;
RetroFont solarWindsFont;
ScreenGameplay screenGameplay;
public HUDLayer(ScreenGameplay s){
screenGameplay = s;
// Add a bit of a border between the edge of the canvas for aesthetics
parent = new RetroPanel(10, 10, width - 20, height - 20);
parent.setDebug(false);
solarWindsFont = new RetroFont("data/fonts/solarwinds.png", 7*2, 8*2, 1*2);
// Position of panel isn't being set correctly.
RetroPanel scorePanel = new RetroPanel(10, 10, 100, 20);
scorePanel.pixelsFromTop(10);
// Score
scoreLabel = new RetroLabel(solarWindsFont);
scoreLabel.setHorizontalTrimming(false);
scoreLabel.setHorizontalSpacing(1);
scoreLabel.pixelsFromTopRight(0, 0);
scorePanel.addWidget(scoreLabel);
parent.addWidget(scorePanel);
// Gems
gemsAcquired = new RetroLabel(solarWindsFont);
gemsAcquired.setHorizontalTrimming(true);
gemsAcquired.setHorizontalSpacing(2);
gemsAcquired.pixelsFromRight(1);
parent.addWidget(gemsAcquired);
// Time
timeLabel = new RetroLabel(solarWindsFont);
timeLabel.setHorizontalTrimming(true);
timeLabel.setHorizontalSpacing(2);
timeLabel.pixelsFromTopLeft(75, 5);
parent.addWidget(timeLabel);
// Level
levelLabel = new RetroLabel(solarWindsFont);
levelLabel.setHorizontalTrimming(true);
levelLabel.pixelsFromTopLeft(60, 5);
parent.addWidget(levelLabel);
// FPS
FPS = new RetroLabel(solarWindsFont);
FPS.pixelsFromBottomLeft(0, 0);
FPS.setHorizontalTrimming(true);
parent.addWidget(FPS);
}
public void draw(){
parent.draw();
}
/*
*/
public void notifyObserver(){
String scoreStr = Utils.prependStringWithString("" + screenGameplay.getScore(), "0", 8);
int min = Utils.floatToInt(screenGameplay.getLevelTimeLeft() / 60);
int sec = screenGameplay.getLevelTimeLeft() % 60;
FPS.setText("FPS: " + (int)frameRate);
scoreLabel.setText("" + scoreStr);
levelLabel.setText("Level:" + screenGameplay.getLevel());
timeLabel.setText("TIME: " + min + ":" + (sec < 10 ? "0" : "") + sec);
gemsAcquired.setText("Gems: " + screenGameplay.getNumGems() + "/" + screenGameplay.getNumGemsForNextLevel());
}
public void update(){
}
public void setZIndex(int zIndex){
}
}
/*
*/
public interface IScreen{
public void draw();
public void update();
// Mouse methods
public void mousePressed();
public void mouseReleased();
public void mouseDragged();
public void mouseMoved();
public void keyPressed();
public void keyReleased();
public String getName();
public boolean isAlive();
}
/*
*/
public interface Subject{
public void addObserver(LayerObserver o);
public void removeObserver(LayerObserver o);
public void notifyObservers();
}
/*
A screen can have many layers associated with it. Layers are rendered
from smaller indices to larger.
*/
public interface LayerObserver{
public void draw();
public void update();
// public void setZIndex(int zIndex);
//
public void notifyObserver();
}
/*
TODO: add rotation
*/
public class SpriteSheetLoader{
PImage test;
HashMap map;
public void load(String texturePackerMetaFile){
/* JSONObject json;
json = loadJSONObject(texturePackerMetaFile);
String imageFilename = json.getJSONObject("meta").getString("image");
// print(imageFilename);
PImage texture = loadImage(imageFilename);
JSONArray frames = json.getJSONArray("frames");
map = new HashMap<String, PImage>(frames.size());
//println(frames.size());
// Iterate over all the sprites in the json file
for(int i = 0; i < frames.size(); i++){
//
JSONObject frame = frames.getJSONObject(i);
// Regardless of whether the sprite is rotated or not, it's final dimensions
// can be extracted from sourceSize.
JSONObject sourceSize = frame.getJSONObject("sourceSize");
int dstSpriteWidth = sourceSize.getInt("w");
int dstSpriteHeight = sourceSize.getInt("h");
PImage img = createImage(dstSpriteWidth, dstSpriteHeight, ARGB);
println("Created image: (" + dstSpriteWidth + "," + dstSpriteHeight + ")");
// Pull the actual sprite from the sheet
JSONObject dimensions = frame.getJSONObject("frame");
int srcStartX = dimensions.getInt("x");
int srcStartY = dimensions.getInt("y");
int srcWidth = dimensions.getInt("w");
int srcHeight = dimensions.getInt("h");
// This is actually our destination, where we copy the pixels into the image.
JSONObject spriteSourceSize = frame.getJSONObject("spriteSourceSize");
int dstStartX = spriteSourceSize.getInt("x");
int dstStartY = spriteSourceSize.getInt("y");
int dw = spriteSourceSize.getInt("w");
int dh = spriteSourceSize.getInt("h");
//println("dw: " + dw);
//println("dh: " + dh);
// println("dstSpriteWidth: " + dstSpriteWidth);
//println("dstSpriteHeight: " + dstSpriteHeight);
// If the sprite isn't rotated, our logic is much simpler so we break up the cases.
if(frame.getBoolean("rotated")){
println("sprite is rotated");
// Going to copy the pixels starting from the sprite in the sheet
// upper left corner downwards moving left to right
// inverted for src
//int dstWidth = 400;
// int dstHeight = 324;
// We only need to copy the trimmed part
int pixelsCopied = 0;
int pixelsToCopy = srcWidth * srcHeight;
int srcX = srcStartX;
int srcY = srcStartY;
int dstX = dstStartX;
int dstY = dh - 1;
//println(dw);
int srcRotHeight = srcWidth;
//println(srcRotHeight);
for( ;pixelsCopied < pixelsToCopy; pixelsCopied++, dstX++, srcY++){
//
if(srcY == srcRotHeight + srcStartY){
srcY = srcStartY;
srcX++;
dstX = dstStartX;
dstY--;
}
// println(dstY*dw+dstX);
color c = texture.pixels[srcY * texture.width + srcX];
//
img.pixels[dstY * dstSpriteWidth + dstX] = c;
}
img.updatePixels();
map.put(frame.getString("filename"), img);
}
else{
println("sprite is not rotated");
// Copy from the sprite sheet to our individual sprite
// potentially not touching the transparent pixels that border the sprite.
img.copy(texture, srcStartX, srcStartY, srcWidth, srcHeight, dstStartX, dstStartY, dw, dh);
map.put(frame.getString("filename"), img);
}
}*/
}
public PImage get(String sprite){
return (PImage)map.get(sprite);
}
}
/*
This screen is the main gameplay screen.
*/
public class ScreenGameplay implements IScreen, Subject{
final int TOKEN_SPACING = 3;
// Tokens that have been remove from the board, but still need to be rendered for their
// death animation.
ArrayList<Token> dyingTokens;
ArrayList<LayerObserver> layerObserver;
PImage bk;
// When a match is created, the matched tokens are removed from the board array
// and 'float' above the board and drop down until they arrive where they need to go.
// We do this because as they fall, we can't give them a integer position, but need to
// use a float.
ArrayList<Token> floatingTokens;
// These are used to specify the direction of checking
// matches in numMatchesSideways and numMatches
private final int LEFT = -1;
private final int RIGHT = 1;
private final int UP = -1;
private final int DOWN = 1;
private final int TOKEN_SCORE = 100;
public boolean screenAlive;
// Only for debugging to see which token would be selected
// by the player.
public boolean drawBoxUnderCursor;
Debugger debug;
int mouseRowIndex = 0;
int mouseColumnIndex = 0;
int Testing = 0;
Ticker debugTicker;
Ticker delayTicker;
Ticker gemRemovalTicker;
Ticker levelCountDownTimer;
int tokensDestroyed = 0;
boolean isPaused = false;
int gemCounter = 0;
int gemsRequiredForLevel = 0;
// This is immediately incremented in the ctor by calling goToNextLevel().
int currLevel = 0;
boolean waitingForTokensToFall = false;
// User can only be in the process of swapping two tokens
// at any given time.
Token swapToken1 = null;
Token swapToken2 = null;
// As the levels increase, more and more token types are added
// This makes it a slightly harder to match tokens.
int numTokenTypesOnBoard = 5;
//
int numGemsOnBoard = 2;
// TODO: fix
// Keep track of the number of gems removed from the board.
//int[] numMatchedGems;
Token currToken1 = null;
Token currToken2 = null;
int score = 0;
public void addObserver(LayerObserver o){
layerObserver.add(o);
// recalculate indices
}
public void removeObserver(LayerObserver o){
// recalc
}
public void notifyObservers(){
for(int i = 0; i < layerObserver.size(); i++){
layerObserver.get(i).notifyObserver();
}
}
/**
*/
ScreenGameplay(){
screenAlive = true;
gemsRequiredForLevel = currLevel * 5;
floatingTokens = new ArrayList<Token>();
dyingTokens = new ArrayList<Token>();
bk = loadImage("data/images/board.png");
//
layerObserver = new ArrayList<LayerObserver>();
/*Layer bkLayer = new BackgroundLayer();
layers.add(bkLayer);
Layer hudLayer = new HUDLayer();
observers.add(hudLayer);*/
debugTicker = new Ticker();
debug = new Debugger();
// lock P for pause
Keyboard.lockKeys(new int[]{KEY_P});
drawBoxUnderCursor = false;
fillBoardWithRandomTokens();
deselectCurrentTokens();
// levelCountDownTimer is set in this method.
goToNextLevel();
}
/*
*/
public void draw(){
if(Keyboard.isKeyDown(KEY_P)){
return;
}
background(0);
pushMatrix();
translate(START_X, START_Y);
// Draw the board background image
pushStyle();
imageMode(CORNER);
// Offset the image slighly so that it lines up with the grid of tokens.
image(bk, -13, -16);
popStyle();
// Draw the debug board with gridlines
//pushMatrix();
//translate(0, 300);
//fill(33,66,99,100);
//strokeWeight(1);
//rect(START_X, START_Y, BOARD_W_IN_PX, BOARD_H_IN_PX);
//rect(0, 0, BOARD_W_IN_PX, BOARD_H_IN_PX);
//popMatrix();
// The dying tokens shrink and the falling tokens get rendered on top of them.
for(int i = 0; i < dyingTokens.size(); i++){
dyingTokens.get(i).draw();
}
for(int i = 0; i < floatingTokens.size(); i++){
floatingTokens.get(i).draw();
}
if(swapToken1 != null){
swapToken1.draw();
}
if(swapToken2 != null){
swapToken2.draw();
}
if(drawBoxUnderCursor == true){
pushStyle();
noFill();
stroke(255, 0, 0);
rect(mouseColumnIndex * TOKEN_SIZE - TOKEN_SIZE/2, mouseRowIndex * TOKEN_SIZE - TOKEN_SIZE/2, TOKEN_SIZE, TOKEN_SIZE);
popStyle();
}
drawBoard();
// In some cases it is necessary to see the non-visible tokens
// above the visible board. Other cases, I want that part covered.
// for example, when tokens are falling.
pushStyle();
fill(0);
noStroke();
rect(START_X-150, -237, 250, 222);
popStyle();
// Draw a box around the grid, just for debugging.
//noFill();
//stroke(255);
//strokeWeight(1);
//rect(0, 350, TOKEN_SIZE, 320);
popMatrix();
// HACK: This line is here as a workaround a bug in Processing.js
// If removed, the board would translate diagonally on the canvas.
// when tokens are removed.
resetMatrix();
if(layerObserver != null){
for(int i = 0; i < layerObserver.size(); i++){
layerObserver.get(i).draw();
}
}
debug.draw();
}
/**
*/
public void update(){
// Once the player meets their quota...
if(gemCounter >= gemsRequiredForLevel){
goToNextLevel();
}
if(waitingForTokensToFall && floatingTokens.size() == 0){
waitingForTokensToFall = false;
fillHoles();
}
isPaused = Keyboard.isKeyDown(KEY_P);
// Goes right to the game over screen, just for testing
if(Keyboard.isKeyDown(KEY_Q)){
screenAlive = false;
}
if(isPaused){
return;
}
debug.clear();
debugTicker.tick();
levelCountDownTimer.tick();
// Update all the tokens that are falling down
for(int i = 0; i < floatingTokens.size(); i++){
Token token = floatingTokens.get(i);
token.update();
//
if(token.arrivedAtDest()){
token.dropIntoCell();
markTokensForRemoval();
delayTicker = new Ticker();
// the token could have been floating down, if it wasn't
// Don't need to explicitly check if it was in the list, the
// structure does that for us automatically.
floatingTokens.remove(token);
//removeMarkedTokens();
gemRemovalTicker = new Ticker();
}
waitingForTokensToFall = true;
}
// Now, update the two tokens that the user has swapped
if(swapToken1 != null){
swapToken1.update();
swapToken2.update();
if(swapToken1.arrivedAtDest() && swapToken1.isReturning() == false && swapToken1.isMoving()){
//
// Need to drop into the cells before check if it was indeed a valid swap
swapToken1.dropIntoCell();
swapToken2.dropIntoCell();
int matches = getNumCosecutiveMatches(swapToken1, swapToken2);
// If it was not a valid swap, animate it back from where it came.
if(matches < 3){
int r1 = swapToken1.getRow();
int c1 = swapToken1.getColumn();
int r2 = swapToken2.getRow();
int c2 = swapToken2.getColumn();
swapToken1.animateTo(r2, c2);
swapToken2.animateTo(r1, c1);
swapToken1.setReturning(true);
swapToken2.setReturning(true);
}
// Swap was valid
else{
swapToken1 = swapToken2 = null;
// gemRemovalTicker = new Ticker();
markTokensForRemoval();
removeMarkedTokens(true);
deselectCurrentTokens();
}
}
else if(swapToken1.arrivedAtDest() && swapToken1.isReturning()){
swapToken1.dropIntoCell();
swapToken2.dropIntoCell();
swapToken1.setReturning(false);
swapToken2.setReturning(false);
swapToken1 = swapToken2 = null;
}
}
// Iterate over all the tokens that are dying and
// increase the score.
for(int i = 0; i < dyingTokens.size(); i++){
dyingTokens.get(i).update();
if(dyingTokens.get(i).isAlive() == false){
if(dyingTokens.get(i).hasGem()){
gemCounter++;
addGemToQueuedToken();
}
addToScore(TOKEN_SCORE);
dyingTokens.remove(i);
tokensDestroyed++;
}
}
for(int r = 0; r < BOARD_ROWS; r++){
for(int c = 0; c < BOARD_COLS; c++){
board[r][c].update();
}
}
if(gemRemovalTicker != null){
gemRemovalTicker.tick();
}
if(delayTicker != null){
delayTicker.tick();
}
if(gemRemovalTicker != null && gemRemovalTicker.getTotalTime() > 0.5f){
gemRemovalTicker = null;
removeMarkedTokens(true);
delayTicker = new Ticker();
}
if(delayTicker != null && delayTicker.getTotalTime() > 0.35f){
dropTokens();
if(validSwapExists() == false){
debugPrint("No more moves available");
}
//if(markTokensForRemoval()){
// gemRemovalTicker = new Ticker();
//}
delayTicker = null;
}
resetMatrix();
// Add a leading zero if seconds is a single digit
String secStr = "";
int seconds = (int)levelCountDownTimer.getTotalTime() % 60;
//
if( (int)levelCountDownTimer.getTotalTime() == 0){
screenAlive = false;
}
notifyObservers();
if(seconds <= 9){
secStr = Utils.prependStringWithString( "" + seconds, "0", 2);
}
else{
secStr = "" + seconds;
}
//debug.addString( "" + (int)(levelCountDownTimer.getTotalTime()/60) + ":" + secStr );
// debug.addString("color: " + numMatchedGems[i]);
}
public boolean isAlive(){
return screenAlive;
}
public String getName(){
return "gameplay";
}
public int getRowIndex(){
return (int)map(mouseY, START_Y, START_Y + BOARD_H_IN_PX, 8, 16);
}
public int getColumnIndex(){
return (int)map(mouseX, START_X, START_X+ BOARD_W_IN_PX, 0, BOARD_COLS);
}
/**
* Tokens that are considrered too far to swap include ones that
* are across from each other diagonally or have 1 token between them.
*/
public boolean isCloseEnoughForSwap(Token t1, Token t2){
//
return abs(t1.getRow() - t2.getRow()) + abs(t1.getColumn() - t2.getColumn()) == 1;
}
public void mouseMoved(){
mouseRowIndex = getRowIndex();
mouseColumnIndex = getColumnIndex();
}
public void mouseReleased(){
}
/*
*
*/
public void mousePressed(){
if(isPaused){
return;
}
// convert the mouse coords to grid coordinates
int r = getRowIndex();
int c = getColumnIndex();
// We can get some wacky values when clicking outside of the
// board. If the player does that, just ignore the click.
if( r >= BOARD_ROWS || c >= BOARD_COLS || r < 0 || c < 0){
return;
}
if(currToken1 == null){
currToken1 = board[r][c];
currToken1.setSelect(true);
}
// The real work is done once we know what to swap with.
else if(currToken2 == null){
currToken2 = board[r][c];
// User clicked on a token that's too far to swap with the one already selected
// In that case, what they are probably doing is starting the 'swap process' over.
if( isCloseEnoughForSwap(currToken1, currToken2) == false){
currToken1.setSelect(false);
currToken1 = currToken2;
currToken1.setSelect(true);
currToken2 = null;
}
else{
animateSwapTokens(currToken1, currToken2);
}
}
}
/**
* To swap tokens, players will clic/tap a token then drag to the token
* they want to swap with.
*/
public void mouseDragged(){
// convert the mouse coords to grid coordinates
int r = getRowIndex();
int c = getColumnIndex();
if( r >= BOARD_ROWS || c >= BOARD_COLS || r < 0 || c < 0){
return;
}
if(currToken1 != null && currToken2 == null){
//
if(c != currToken1.getColumn() || r != currToken1.getRow()){
currToken2 = board[r][c];
if(isCloseEnoughForSwap(currToken1, currToken2) == false){
currToken2 = null;
}
else{
animateSwapTokens(currToken1, currToken2);
}
}
}
}
public int getScore(){
return score;
}
public int getLevelTimeLeft(){
return (int)levelCountDownTimer.getTotalTime();
}
public int getLevel(){
return currLevel;
}
/*
As soon as a token is removed, we add to the score.
*/
public void addToScore(int offset){
score += offset;
notifyObservers();
}
/*
*
*/
void animateSwapTokens(Token t1, Token t2){
// We need to cache these so we get get the wrong
// values when calling animateTo.
int t1Row = t1.getRow();
int t1Col = t1.getColumn();
int t2Row = t2.getRow();
int t2Col = t2.getColumn();
swapToken1 = t1;
swapToken2 = t2;
// Animate will detach the tokens from the board
swapToken1.animateTo(t2Row, t2Col);
swapToken2.animateTo(t1Row, t1Col);
deselectCurrentTokens();
}
/**
Speed: O(n)
Returns true as soon as it finds a valid swap/move.
There may be a case in which there are no valid swap/moves left
in that case the board needs to be reset.
*/
private boolean validSwapExists(){
// First check any potential matches in the horizontal
for(int r = START_ROW_INDEX; r < BOARD_ROWS; r++){
for(int c = 0; c < BOARD_COLS - 1; c++){
Token t1 = board[r][c];
Token t2 = board[r][c + 1];
swapTokens(t1, t2);
//if(wasValidSwap(gem1, gem2)){
if(getNumCosecutiveMatches(t1, t2) >= 3){
swapTokens(t1, t2);
return true;
}
// Swap them back
else{
swapTokens(t1, t2);
}
}
}
// Check any potential matches in the vertical
for(int c = 0; c < BOARD_COLS; c++){
for(int r = START_ROW_INDEX; r < BOARD_ROWS - 1; r++){
Token gem1 = board[r][c];
Token gem2 = board[r + 1][c];