-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathReversi.cpp
More file actions
689 lines (608 loc) · 17.9 KB
/
Reversi.cpp
File metadata and controls
689 lines (608 loc) · 17.9 KB
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
#include "Reversi.h"
void Reversi::Setup(const vector<string>& args) {
ResetGame(true);
}
void Reversi::Loop()
{
struct KeyEvent keyEvent;
while (MatrixOS::KeyPad::Get(&keyEvent))
{ KeyEventHandler(keyEvent); }
if(renderTimer.Tick(1000/Device::LED::fps))
{
Render();
}
}
uint8_t Reversi::Flip(Point pos, uint8_t currentPlayer, bool update)
{
uint8_t opponentPlayer = (1 == currentPlayer) ? 2 : 1;
uint8_t flipped = 0;
// Check all 8 directions
for(int8_t dy = -1; dy <= 1; dy++)
{
for(int8_t dx = -1; dx <= 1; dx++)
{
if(dy == 0 && dx == 0)
{
continue;
}
int distance = 1;
int checkY = pos.y + dy * distance;
int checkX = pos.x + dx * distance;
// Immediate neighbor check
if(checkY >= 0 && checkY < 8 && checkX >= 0 && checkX < 8 && board[checkY][checkX].player == opponentPlayer)
{
while(true)
{
distance++;
checkY = pos.y + dy * distance;
checkX = pos.x + dx * distance;
// Check for board boundaries
if(checkY < 0 || checkY >= 8 || checkX < 0 || checkX >= 8)
{
break;
}
int playerAtPosition = board[checkY][checkX].player;
if(playerAtPosition == opponentPlayer)
{
continue;
}
else if(playerAtPosition == currentPlayer)
{
// Flip pieces between pos and (checkX, checkY)
int flipY = pos.y + dy;
int flipX = pos.x + dx;
while(flipY != checkY || flipX != checkX)
{
if(update)
{
board[flipY][flipX].player = currentPlayer;
}
flipped++;
flipY += dy;
flipX += dx;
}
break;
}
else
{
// Empty cell, cannot flip in this direction
break;
}
}
}
}
}
return flipped;
}
void Reversi::Place(Point pos)
{
invalidPlace = pos;
invalidPlaceTime = MatrixOS::SYS::Millis();
if(pos.x < 0 || pos.x >= 8 || pos.y < 0 || pos.y >= 8)
{
return;
}
if(gameState != Waiting)
{
return;
}
if(board[pos.y][pos.x].validMove == 0)
{
return;
}
invalidPlace = Point::Invalid();
started = true;
// Update board
for(uint8_t y = 0; y < 8; y++)
{
for(uint8_t x = 0; x < 8; x++)
{
// Copy player to wasPlayer
board[y][x].wasPlayer = board[y][x].player;
board[y][x].newlyPlaced = false;
}
}
board[pos.y][pos.x].newlyPlaced = true;
board[pos.y][pos.x].player = currentPlayer;
placedPos = pos;
Flip(pos, currentPlayer, true);
gameState = Moving;
MLOGD("Reversi", "Moving");
lastEventTime = MatrixOS::SYS::Millis();
}
void Reversi::Render()
{
uint32_t timeSinceEvent = MatrixOS::SYS::Millis() - lastEventTime;
if(gameState == Waiting)
{
Color hint_move_color;
if(hint)
{
uint8_t hint_move_ratio;
if(timeSinceEvent <= 750)
{
hint_move_ratio = ColorEffects::Breath(1500, lastEventTime);
}
else
{
hint_move_ratio = ColorEffects::BreathLowBound(64, 1500, lastEventTime);
}
hint_move_color = GetPlayerColor(currentPlayer).Dim().Dim(hint_move_ratio);
last_breating_brightness = hint_move_color.B; // Hack: Get the channel brightness val
}
else
{
last_breating_brightness = 0;
}
for(uint8_t y = 0; y < 8; y++)
{
for(uint8_t x = 0; x < 8; x++)
{
if(board[y][x].validMove && hint)
{
MatrixOS::LED::SetColor(Point(x, y), hint_move_color);
}
else
{
MatrixOS::LED::SetColor(Point(x, y), GetPlayerColor(board[y][x].player));
}
}
}
uint32_t timeSinceInvalidPlace = MatrixOS::SYS::Millis() - invalidPlaceTime;
if(invalidPlace && timeSinceInvalidPlace < 800)
{
if(timeSinceInvalidPlace <= 500)
{
MatrixOS::LED::SetColor(invalidPlace, Color(0xFF0000));
}
else
{
MatrixOS::LED::SetColor(invalidPlace, Color::Crossfade(Color(0xFF0000), GetPlayerColor(board[invalidPlace.y][invalidPlace.x].player), 255 - ((timeSinceInvalidPlace - 500) * 255 / 300)));
}
}
MatrixOS::LED::FillPartition("Underglow", ColorEffects::ColorBreath(GetPlayerColor(currentPlayer), 2000, lastEventTime - 500));
}
else if(gameState == Moving)
{
bool done = true;
for(uint8_t y = 0; y < 8; y++)
{
for(uint8_t x = 0; x < 8; x++)
{
if(board[y][x].player != board[y][x].wasPlayer)
{
int8_t deltaX = x - placedPos.x;
int16_t powerX = pow(deltaX, 2);
int8_t deltaY = y - placedPos.y;
int16_t powerY = pow(deltaY, 2);
float distanceFromPlaced = sqrt(powerX + powerY);
Fract16 ratio;
uint32_t startTime = distanceFromPlaced * 100 + 200;
if(board[y][x].newlyPlaced)
{
MatrixOS::LED::SetColor(Point(x, y), GetPlayerColor(board[y][x].player));//.Dim(new_piece_ratio));
continue;
}
if(timeSinceEvent <= startTime)
{
ratio = 0;
done = false;
}
else if(timeSinceEvent - 300 > startTime )
{
ratio = FRACT16_MAX;
}
else
{
ratio = (timeSinceEvent - startTime) * FRACT16_MAX / 300;
done = false;
}
MatrixOS::LED::SetColor(Point(x, y), Color::Crossfade(GetPlayerColor(board[y][x].wasPlayer), GetPlayerColor(currentPlayer), ratio));
}
else if(board[y][x].validMove && hint)
{
uint8_t ratio;
if(timeSinceEvent <= 200)
{
ratio = last_breating_brightness - (timeSinceEvent * last_breating_brightness / 200);
}
else
{
ratio = 0;
}
MatrixOS::LED::SetColor(Point(x, y), GetPlayerColor(currentPlayer).Dim(ratio));
}
else
{
MatrixOS::LED::SetColor(Point(x, y), GetPlayerColor(board[y][x].player));
}
}
}
MatrixOS::LED::FillPartition("Underglow", GetPlayerColor(currentPlayer));
if(done && timeSinceEvent >= 250)
{
winner = 255;
gameState = Intermission;
MLOGD("Reversi", "Intermission");
lastEventTime = MatrixOS::SYS::Millis();
}
}
else if(gameState == NoValidMoves)
{
for(uint8_t y = 0; y < 8; y++)
{
for(uint8_t x = 0; x < 8; x++)
{
if(board[y][x].player == 0)
{
MatrixOS::LED::SetColor(Point(x, y), ColorEffects::ColorStrobe(Color(0xFF0000).Dim(), 500, lastEventTime));
}
}
}
MatrixOS::LED::FillPartition("Underglow", ColorEffects::ColorStrobe(GetPlayerColor(currentPlayer), 500, lastEventTime));
if(timeSinceEvent >= 2000)
{
winner = 255;
gameState = Intermission;
MLOGD("Reversi", "Intermission");
lastEventTime = MatrixOS::SYS::Millis();
}
}
else if(gameState == Intermission)
{
if(winner == 255)
{
winner = CheckGameOver();
}
uint8_t nextPlayer = currentPlayer == 1 ? 2 : 1;
Fract16 ratio;
if (timeSinceEvent <= 500)
{ ratio = timeSinceEvent * FRACT16_MAX / 500;}
else
{ ratio = FRACT16_MAX; }
if(winner != 0 && winner != 254)
{
MatrixOS::LED::FillPartition("Underglow", Color::Crossfade(GetPlayerColor(currentPlayer), GetPlayerColor(winner), ratio));
}
else
{
MatrixOS::LED::FillPartition("Underglow", Color::Crossfade(GetPlayerColor(currentPlayer), GetPlayerColor(nextPlayer), ratio));
}
if(timeSinceEvent >= 500)
{
if(winner == 0)
{
gameState = Waiting;
MLOGD("Reversi", "Waiting");
currentPlayer = nextPlayer;
}
else if(winner == 254)
{
gameState = NoValidMoves;
MLOGD("Reversi", "NoValidMoves");
currentPlayer = nextPlayer;
}
else
{
gameState = WinnerUnveil;
MLOGD("Reversi", "WinnerUnveil");
}
lastEventTime = MatrixOS::SYS::Millis();
}
}
else if(gameState == WinnerUnveil)
{
bool done = true;
for(uint8_t y = 0; y < 8; y++)
{
for(uint8_t x = 0; x < 8; x++)
{
uint32_t startTime = (y * 8 + x) * 50;
if(timeSinceEvent >= (startTime + 1000)) // 1000 (Done)
{
uint8_t localWinner = winner;
if(winner == 3)
{
localWinner = (x + y * 7) % 2 == 0 ? 1 : 2;
}
MatrixOS::LED::SetColor(Point(x, y), GetPlayerColor(localWinner));
}
else if(timeSinceEvent >= (startTime + 700)) // 700 - 1000
{
done = false;
uint8_t localWinner = winner;
if(winner == 3)
{
localWinner = (x + y * 7) % 2 == 0 ? 1 : 2;
}
Fract16 ratio = (timeSinceEvent - 700 - startTime) * FRACT16_MAX / 300;
MatrixOS::LED::SetColor(Point(x, y), Color::Crossfade(Color::White, GetPlayerColor(localWinner), ratio));
}
else if(timeSinceEvent >= (startTime + 300)) // 300 - 700
{
done = false;
MatrixOS::LED::SetColor(Point(x, y), Color::White);
}
else if(timeSinceEvent >= startTime) // 0 - 300
{
done = false;
Fract16 ratio = (timeSinceEvent - startTime) * FRACT16_MAX / 300;
MatrixOS::LED::SetColor(Point(x, y), Color::Crossfade(GetPlayerColor(board[y][x].player), Color::White, ratio));
}
else // Before the start time
{
done = false;
MatrixOS::LED::SetColor(Point(x, y), GetPlayerColor(board[y][x].player));
}
}
}
if(done)
{
gameState = Ended;
MLOGD("Reversi", "Ended");
}
}
else if(gameState == Ended)
{
for(uint8_t y = 0; y < 8; y++)
{
for(uint8_t x = 0; x < 8; x++)
{
uint8_t localWinner = winner;
if(winner == 3)
{
localWinner = (x + y * 7) % 2 == 0 ? 1 : 2;
}
MatrixOS::LED::SetColor(Point(x,y), ColorEffects::ColorBreathLowBound(GetPlayerColor(localWinner), 64, 2000, lastEventTime + 1000));
}
}
}
MatrixOS::LED::Update();
}
uint8_t Reversi::CheckGameOver()
{
uint8_t opponentPlayer = currentPlayer == 1 ? 2 : 1;
// Check if there are any valid moves
bool validMove = false;
for(uint8_t y = 0; y < 8; y++)
{
for(uint8_t x = 0; x < 8; x++)
{
if(board[y][x].player == 0)
{
if(Flip(Point(x, y), opponentPlayer, false))
{
board[y][x].validMove = 1;
validMove = true;
}
else
{
board[y][x].validMove = 0;
}
}
else
{
board[y][x].validMove = 0;
}
}
}
if(!validMove) // Check the current player has valid move
{
MLOGD("Reversi", "No valid moves for player %d", currentPlayer);
validMove = false;
for(uint8_t y = 0; y < 8; y++)
{
for(uint8_t x = 0; x < 8; x++)
{
if(board[y][x].player == 0)
{
if(Flip(Point(x, y), currentPlayer, false))
{
validMove = true;
}
}
}
}
if(!validMove)
{
MLOGD("Reversi", "No valid moves for both players, forcing a winner");
}
else
{
MLOGD("Reversi", "Valid moves for next player");
return 254; // No valid moves
}
}
else
{
MLOGD("Reversi", "Valid moves for current player");
return 0;
}
uint8_t player1Count = 0;
uint8_t player2Count = 0;
for(uint8_t y = 0; y < 8; y++)
{
for(uint8_t x = 0; x < 8; x++)
{
if(board[y][x].player == 1)
{
player1Count++;
}
else if(board[y][x].player == 2)
{
player2Count++;
}
}
}
if(player1Count > player2Count)
{
return 1;
}
else if(player2Count > player1Count)
{
return 2;
}
else // Draw
{
return 3;
}
}
bool Reversi::ConfirmMenu()
{
bool confirmed = false;
UI confirmUI("Reset Game?", Color(0xFF0000), false);
UIButton cancelResetBtn;
cancelResetBtn.SetName("Cancel");
cancelResetBtn.SetColor(Color(0xFF0000));
cancelResetBtn.SetSize(Dimension(2, 2));
cancelResetBtn.OnPress([&]() -> void {
confirmed = false;
confirmUI.Exit();
});
confirmUI.AddUIComponent(cancelResetBtn, Point(1, 3));
UIButton confirmResetBtn;
confirmResetBtn.SetName("Confirm");
confirmResetBtn.SetColor(Color(0x00FF00));
confirmResetBtn.SetSize(Dimension(2, 2));
confirmResetBtn.OnPress([&]() -> void {
confirmed = true;
confirmUI.Exit();
});
confirmUI.AddUIComponent(confirmResetBtn, Point(5, 3));
confirmUI.Start();
return confirmed;
}
bool Reversi::ResetGame(bool confirmed)
{
if(!(gameState == Ended || !started) && (!confirmed && !ConfirmMenu()))
{
return false;
}
for(uint8_t y = 0; y < 8; y++)
{
for(uint8_t x = 0; x < 8; x++)
{
board[y][x].newlyPlaced = 0;
board[y][x].player = 0;
board[y][x].wasPlayer = 0;
board[y][x].validMove = 0;
}
}
firstPlayer.Load(); // For some reason, the firstPlayer is not auto loaded correctly
uint8_t secondPlayer = (1 == firstPlayer) ? 2 : 1;
board[3][3].player = firstPlayer;
board[3][3].wasPlayer = firstPlayer;
board[4][4].player = firstPlayer;
board[4][4].wasPlayer = firstPlayer;
board[3][4].player = secondPlayer;
board[3][4].wasPlayer = secondPlayer;
board[4][3].player = secondPlayer;
board[4][3].wasPlayer = secondPlayer;
board[2][4].validMove = 1;
board[3][5].validMove = 1;
board[4][2].validMove = 1;
board[5][3].validMove = 1;
currentPlayer = firstPlayer;
gameState = Waiting;
MLOGD("Reversi", "Waiting");
winner = 0;
started = false;
lastEventTime = MatrixOS::SYS::Millis();
return true;
}
Color Reversi::GetPlayerColor(uint8_t player)
{
if(player == 1)
{
return player1Color;
}
else if(player == 2)
{
return player2Color;
}
else if(player == 3) // Draw
{
return Color::White;
}
else
{
return Color(0x000000);
}
}
void Reversi::KeyEventHandler(KeyEvent& keyEvent) {
if (keyEvent.ID() == FUNCTION_KEY)
{
if (keyEvent.State() == PRESSED)
{
Settings();
}
return;
}
if(gameState == Waiting)
{
Point xy = MatrixOS::KeyPad::ID2XY(keyEvent.ID());
if (xy && keyEvent.State() == RELEASED) // IF XY is valid, means it's on the main grid
{
Place(xy);
}
}
}
void Reversi::Settings() {
UI settingsUI("Settings", Color(0x00FFFF), true);
UIButton player1ColorSelector;
player1ColorSelector.SetName("Player 1 Color");
player1ColorSelector.SetColorFunc([&]() -> Color { return player1Color; });
player1ColorSelector.SetSize(Dimension(8,1));
player1ColorSelector.OnPress([&]() -> void { if(MatrixOS::UIUtility::ColorPicker(player1Color)) { player1Color.Save(); } });
settingsUI.AddUIComponent(player1ColorSelector, Point(0, 7));
UIButton player2ColorSelector;
player2ColorSelector.SetName("Player 2 Color");
player2ColorSelector.SetColorFunc([&]() -> Color { return player2Color; });
player2ColorSelector.SetSize(Dimension(8,1));
player2ColorSelector.OnPress([&]() -> void { if(MatrixOS::UIUtility::ColorPicker(player2Color)) { player2Color.Save(); } });
settingsUI.AddUIComponent(player2ColorSelector, Point(0, 0));
UIButton player1FirstHand;
player1FirstHand.SetName("Player 1 First Hand");
player1FirstHand.SetColorFunc([&]() -> Color { return Color::White.DimIfNot(1 == firstPlayer); });
player1FirstHand.OnPress([&]() -> void { if(1 == firstPlayer) {return;} if (gameState == Ended || !started || ConfirmMenu()) { firstPlayer = 1; ResetGame(true);} });
settingsUI.AddUIComponent(player1FirstHand, Point(7, 6));
UIButton player2FirstHand;
player2FirstHand.SetName("Player 2 First Hand");
player2FirstHand.SetColorFunc([&]() -> Color { return Color::White.DimIfNot(2 == firstPlayer); });
player2FirstHand.OnPress([&]() -> void { if(2 == firstPlayer) {return;} if (gameState == Ended || !started || ConfirmMenu()) { firstPlayer = 2; ResetGame(true);} });
settingsUI.AddUIComponent(player2FirstHand, Point(0, 1));
UIToggle hintToggle;
hintToggle.SetName("Placement Hint");
hintToggle.SetColor(Color(0x00FF00));
hintToggle.SetSize(Dimension(1, 2));
hintToggle.SetValuePointer(&hint);
hintToggle.OnPress([&]() -> void {hint.Save();});
settingsUI.AddUIComponent(hintToggle, Point(0, 3));
UIButton resetGameBtn;
resetGameBtn.SetName("Reset Game");
resetGameBtn.SetColorFunc([&]() -> Color { return Color(0xFF0000); });
resetGameBtn.OnPress([&]() -> void {
if(ResetGame(false)) { settingsUI.Exit(); }
});
resetGameBtn.SetSize(Dimension(1, 2));
settingsUI.AddUIComponent(resetGameBtn, Point(7, 3));
// Second, set the key event handler to match the intended behavior
settingsUI.SetKeyEventHandler([&](KeyEvent* keyEvent) -> bool {
// If function key is hold down. Exit the application
if (keyEvent->id == FUNCTION_KEY)
{
if (keyEvent->info.state == HOLD)
{
Exit(); // Exit the application.
}
else if (keyEvent->info.state == RELEASED)
{
settingsUI.Exit(); // Exit the UI
}
return true; // Block UI from to do anything with FN, basically this function control the life cycle of the UI
}
return false; // Nothing happened. Let the UI handle the key event
});
// The UI object is now fully set up. Let the UI runtime to start and take over.
settingsUI.Start();
}