-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainGame.cs
1191 lines (1034 loc) · 39.4 KB
/
MainGame.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
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
using Gamegrid;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Speech.Synthesis;
using System.Windows.Forms;
using System.Media;
using System.Linq;
using System.Threading;
using System.ComponentModel;
namespace O_Neillo
{
/// <summary>
/// Cell values, used internally instead of hard coded values.
/// </summary>
public enum CellValues
{
black = 1,
white = 2,
blank = 10
}
public partial class MainGame : Form
{
static int SerialisationVersion = 1;
static private Random random = new Random();
#region Public classes
/// <summary>
/// Class used to pass savefile data between functions
/// </summary>
public class GameData
{
public string Player1Name;
public string Player2Name;
public int Player1Score;
public int Player2Score;
public int CurrentPlayer;
public int GameRows;
public int GameColumns;
public CellValues[,] GameValsData;
}
#endregion
#region Internal classes
/// <summary>
/// Contains a deltaX and a deltaY value to 'travel' in that direction.
/// </summary>
private class Direction
{
public int dx, dy;
public Direction(int dx, int dy)
{
this.dx = dx;
this.dy = dy;
}
}
/// <summary>
/// Array containing all possible directions that you can flank
/// </summary>
private static Direction[] Directions =
{
new Direction(-1,-1),
new Direction(-1,0),
new Direction(-1,1),
new Direction(0,-1),
new Direction(0,0),
new Direction(0,1),
new Direction(1,-1),
new Direction(1,0),
new Direction(1,1)
};
/// <summary>
/// Class used to pass around point stacks for tokens to flip
/// </summary>
private class FlankInfo
{
/// <summary>
/// Indicates if at least one flank is available, saves O(n) lookup on the flankpoints array.
/// </summary>
public bool CanFlank = false;
public Stack<Point>[] FlankPoints = new Stack<Point>[Directions.Length];
}
#endregion
#region Internal variables
Image GridBlack = Properties.Resources.GridBlack;
Image GridWhite = Properties.Resources.GridWhite;
/// <summary>
/// Says whether or not the game's currently being played.
/// </summary>
bool playing = false;
/// <summary>
/// Stores the values of each grid for ease of lookup
/// </summary>
CellValues[,] gameVals;
/// <summary>
/// Stores which player's currently playing
/// </summary>
Playerinfo currentPlayer;
/// <summary>
/// Stores if the previous player passed (If both pass, game ends)
/// </summary>
bool previousPlayerPassed;
/// <summary>
/// Speach Synthesize used for TTS
/// </summary>
SpeechSynthesizer synth = new SpeechSynthesizer();
#endregion
#region Internal functions (Events)
/// <summary>
/// Initialises class.
/// </summary>
public MainGame(string SaveFile = "")
{
InitializeComponent();
gameGrid1.InitializeGrid();
// Improves FPS
DoubleBuffered = true;
synth.SetOutputToDefaultAudioDevice();
if (SaveFile != "" && File.Exists(SaveFile))
{
LoadGameFromFile(SaveFile);
}
}
/// <summary>
/// Called whenever you click exit
/// </summary>
private void exitBtn_click(object sender, EventArgs e)
{
if (playing)
{
switch (MessageBox.Show("Would you like to save the game before exiting?", "Save game?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
{
case (DialogResult.Yes):
{
SaveGameToFile();
break;
}
case (DialogResult.Cancel):
{
return;
}
default:
break;
}
}
Application.Exit();
}
/// <summary>
/// Called whenever you click start game
/// </summary>
private void newGame_Click(object sender, EventArgs e)
{
if (playing)
{
switch (MessageBox.Show("Would you like to save the present game before starting a new one?", "Save game?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
{
case (DialogResult.Yes):
{
SaveGameToFile();
break;
}
case (DialogResult.Cancel):
{
return;
}
default:
break;
}
}
if (playerinfo1.PlayerName == "" || playerinfo2.PlayerName == "")
{
Speak("Both Players need a name to start.", false, true);
return;
}
NewGameDialog diag = new NewGameDialog();
diag.ColumnCount = gameGrid1.Columns;
diag.RowCount = gameGrid1.Rows;
switch (diag.ShowDialog())
{
case (DialogResult.OK):
{
StartGame(diag.RowCount, diag.ColumnCount);
diag.Dispose();
break;
}
case (DialogResult.Cancel):
{
break;
}
default:
{
break;
}
}
}
/// <summary>
/// Called whenever the grid's pressed
/// </summary>
private void gameGrid1_CellPressed(object sender, CellPressedEventArgs e)
{
AttemptMove(e.x, e.y);
}
/// <summary>
/// Called whenever the pass button's pressed.
/// </summary>
private void passBtn_click(object sender, EventArgs e)
{
if (!playing)
{
MustBePlayingError();
return;
}
pass();
}
/// <summary>
/// Called whenever the speak checkbox is clicked.
/// </summary>
private void chk_speak_Click(object sender, EventArgs e)
{
Speak($"Voice Synthesis Turned {(chk_speak.Checked ? "On" : "Off")}");
}
/// <summary>
/// Called whenever the load button is pressed
/// </summary>
private void loadBtn_Click(object sender, EventArgs e)
{
switch (openFileDialog1.ShowDialog())
{
case (DialogResult.OK):
{
LoadGameFromFile(openFileDialog1.FileName);
break;
}
default:
break;
}
}
/// <summary>
/// Called whenever the save button is pressed
/// </summary>
private void saveBtn_Click(object sender, EventArgs e)
{
if (!playing)
{
MustBePlayingError();
return;
}
SaveGameToFile();
}
/// <summary>
/// Called whenever the help button is pressed
/// </summary>
private void helpBtn_Click(object sender, EventArgs e)
{
new About().Show();
}
#endregion
#region Internal functions (Gameplay)
/// <summary>
/// Call this function to switch which player's currently playing.
/// </summary>
private void SwitchPlayer()
{
if (!playing) return;
currentPlayer.PlayerTurn = false;
currentPlayer = (currentPlayer == playerinfo1) ? playerinfo2 : playerinfo1;
currentPlayer.PlayerTurn = true;
if (currentPlayer.CellValue == CellValues.black)
{
this.Icon = Properties.Resources.Icon_GridBlack;
}
else if (currentPlayer.CellValue == CellValues.white)
{
this.Icon = Properties.Resources.Icon_GridWhite;
}
else
{
this.Icon = Properties.Resources.Icon_GridBase;
}
if (!AnyLegalMoves() && playing)
{
if (!currentPlayer.isAI)
Speak($"No Legal moves found, Skipping {currentPlayer.PlayerName}'s turn", false, true);
if (previousPlayerPassed == true)
{
EndGame();
}
else
{
previousPlayerPassed = true;
SwitchPlayer();
}
}
if (currentPlayer.isAI)
{
currentPlayer.AItimer.Enabled = true;
}
}
/// <summary>
/// Function called to setup the board and start a new game.
/// </summary>
private void StartGame(int rows, int columns)
{
gameGrid1.Rows = rows;
gameGrid1.Columns = columns;
gameGrid1.InitializeGrid();
gameVals = new CellValues[gameGrid1.Columns, gameGrid1.Rows];
for (int x = 0; x < gameGrid1.Columns; x++)
{
for (int y = 0; y < gameGrid1.Rows; y++)
{
gameVals[x, y] = CellValues.blank;
}
}
int cx = gameGrid1.Columns / 2;
int cy = gameGrid1.Rows / 2;
SetCell(cx - 1, cy - 1, CellValues.black);
SetCell(cx, cy, CellValues.black);
SetCell(cx, cy - 1, CellValues.white);
SetCell(cx - 1, cy, CellValues.white);
playerinfo1.Tokens = 2;
playerinfo1.PlayerTurn = true;
playerinfo2.Tokens = 2;
playerinfo2.PlayerTurn = false;
Speak($"Starting Game, {playerinfo1.PlayerName} as black versus {playerinfo2.PlayerName} as white.", true);
currentPlayer = playerinfo1;
this.Icon = Properties.Resources.Icon_GridBlack;
aiThoughtTimer1.Enabled = true;
playing = true;
}
/// <summary>
/// Function called to declare a winner and end the game
/// </summary>
private void EndGame()
{
aiThoughtTimer1.Enabled = false;
aiThoughtTimer2.Enabled = false;
playing = false;
if (playerinfo1.Tokens == playerinfo2.Tokens)
{
Speak($"Game Ended, It's a draw");
MessageBox.Show(
$"Game Ended, It's a draw.",
"Game Ended",
MessageBoxButtons.OK,
MessageBoxIcon.Information
);
}
else
{
Playerinfo winner = (playerinfo1.Tokens > playerinfo2.Tokens) ? ref playerinfo1 : ref playerinfo2;
Speak($"Game Ended, {winner.PlayerName} won with {winner.Tokens} tokens!");
MessageBox.Show(
$"Game Ended, {winner.PlayerName} won with {winner.Tokens} tokens!",
"Game Ended",
MessageBoxButtons.OK,
MessageBoxIcon.Information
);
}
}
/// <summary>
/// Attempt to place a piece on the specific co-ordinate
/// </summary>
/// <param name="x">The X value of the cell to place on</param>
/// <param name="y">The Y value of the cell to place on</param>
private void AttemptMove(int x, int y)
{
// For purposes of this, n is the average width/height of the grid.
// Test O(1)
if (!playing)
{
MustBePlayingError();
return;
}
// Move must follow these rules:
// 0) The square you place in must not have a piece already in it
// 1) Must be adjacent to an opponents piece
// 2) Must outflank an opponents piece (and by extension, be able to flip them)
// 3) If outflanks in multiple directions, all flip
// 4) If no moves are available you must pass.
// 5) If moves are availble, you can't pass.
// 6) If neither player has avalable moves, the game ends.
// To make sure i'm checking in a decent
// O(1) lookup on an array
if (GetCell(x, y) != CellValues.blank)
{
// Breaks rule 0, there's somethign already there
Speak("You can't place a token there, the space is already occupied.");
return;
}
// O(9) checks all 9 squares in a 3x3 for opponents (including it's own square)
if (!OpponentAdjacent(x, y))
{
// Breaks rule 1, return and let them try again
// MessageBox.Show("R1");
Speak("You can't place a token there, you must be adjacent to an opponent's token");
return;
}
int dScore = 0;
// Runs get flanks, checks approiximately 3n cells
// (for 8x8 grid, 5this would be approximately 24, can check up to 27, but will probably be less)
FlankInfo flanks = GetFlanks(x, y);
if (!flanks.CanFlank)
{
// Breaks rule 2, return and let them try again
// MessageBox.Show("R2");
Speak("You can't place a token there, you must be outflanking at least one enemy piece.");
return;
}
else
{
// Stop any existing messages
StopSpeak();
// Complies with rule 1 and 2, flip flanks in all directions
// MessageBox.Show("R2");
for (int i = 0; i < flanks.FlankPoints.Length; i++)
{
ref Stack<Point> points = ref flanks.FlankPoints[i];
while (points.Count != 0)
{
Point p = points.Pop();
SetCell(p.X, p.Y, currentPlayer.CellValue);
dScore++;
}
}
}
SetCell(x, y, currentPlayer.CellValue);
Speak($"{currentPlayer.PlayerName} placed a token at grid{x + 1}, {y + 1} and flipped {dScore} {(dScore > 1 ? "tokens" : "token")}.", true);
previousPlayerPassed = false;
currentPlayer.Tokens += dScore + 1;
SwitchPlayer();
currentPlayer.Tokens -= dScore;
}
/// <summary>
/// Sets the value for a cell
/// </summary>
/// <param name="x">The X value of the cell to set</param>
/// <param name="y">The Y value of the cell to set</param>
/// <param name="val">The Value to set the cell to</param>
private void SetCell(int x, int y, CellValues val)
{
gameVals[x, y] = val;
if (val == CellValues.black)
{
gameGrid1.SetCell(x, y, GridBlack);
}
else if (val == CellValues.white)
{
gameGrid1.SetCell(x, y, GridWhite);
}
}
/// <summary>
/// Get the value of a cell
/// </summary>
/// <param name="x">The X value of the cell to check</param>
/// <param name="y">The Y value of the cell to check</param>
/// <returns>The cells value</returns>
private CellValues GetCell(int x, int y)
{
return gameVals[x, y];
}
/// <summary>
/// Used to display an error that you must be playing the game in order to perform a certain action.
/// </summary>
private void MustBePlayingError()
{
Speak("You need to start a game first!(Game->Start Game)", false, true);
//MessageBox.Show("You need to start a game first! (Game -> Start Game)");
return;
}
/// <summary>
/// Checks if placing a token on a spot is a legal move.
/// </summary>
/// <param name="x">The X value of the spot to check</param>
/// <param name="y">The Y value of the spot to check</param>
/// <returns>True if a piece can be legally placed there</returns>
private bool LegalMove(int x, int y)
{
if ((GetCell(x, y) == CellValues.blank) && OpponentAdjacent(x, y) && AnyFlanks(x, y).CanFlank)
{
return true;
}
return false;
}
/// <summary>
/// Calculates the change in score if you place in a certain spot
/// </summary>
/// <param name="x">The X value of the spot to check</param>
/// <param name="y">The Y value of the spot to check</param>
/// <returns>Cellscore info, with .valid indicating if it's valid, and .score saying the change in score</returns>
private CellScoreInfo GetMoveScore(int x, int y)
{
// make sure that even if every single cell is valid, there will be enough space in the array.
CellScoreInfo ret = new CellScoreInfo { x = x, y = y, score = 0 };
if (GetCell(x, y) != CellValues.blank)
{
ret.valid = false;
}
else if (!OpponentAdjacent(x, y))
{
ret.valid = false;
}
else
{
FlankInfo flanks = GetFlanks(x, y);
if (flanks.CanFlank)
{
foreach (Stack<Point> points in flanks.FlankPoints)
{
ret.score += points.Count;
}
ret.valid = true;
}
else
{
ret.valid = false;
}
}
return ret;
}
/// <summary>
/// Checks if there is an opponent peice in any adjacent square
/// </summary>
/// <param name="centerX">The X value to center the search on</param>
/// <param name="centerY">The Y value to center the search on</param>
/// <returns>True if there is an opponent adjacent</returns>
private bool OpponentAdjacent(int centerX, int centerY)
{
CellValues enemyCell;
if (currentPlayer == playerinfo1)
{
enemyCell = CellValues.white;
}
else
{
enemyCell = CellValues.black;
}
for (int x = centerX - 1; x <= centerX + 1; x++)
{
for (int y = centerY - 1; y <= centerY + 1; y++)
{
if ((x >= 0 && x < gameGrid1.Columns) && (y >= 0 && y < gameGrid1.Rows))
{
if (gameVals[x, y] == enemyCell)
{
return true;
}
}
else
{
// Out of bounds error, go to next value in loop
}
}
}
return false;
}
/// <summary>
/// This function takes a point and checks for flanks in every direction.
/// </summary>
/// <param name="centerX">The X value to center the search on</param>
/// <param name="centerY">The Y value to center the search on</param>
/// <returns>Flankinfo class</returns>
private FlankInfo GetFlanks(int centerX, int centerY)
{
FlankInfo flankInfo = new FlankInfo();
// Loops through each direction
for (int i = 0; i < Directions.Length; i++)
{
ref Direction dir = ref Directions[i];
// Stack size is slightly overkill, but it's to avoid any potential stack overflows
Stack<Point> Flanks = new Stack<Point>(128);
// If I find a flank in a specific direction, add its stack to the array,
// if not, add a blank stack.
if (FindFlank(centerX + dir.dx, centerY + dir.dy, dir, Flanks, true))
{
// MessageBox.Show($"FlankDir: {dir.dx},{dir.dy} successfull");
flankInfo.FlankPoints[i] = Flanks;
// indicates that at least one flank is available (saves any looping later)
flankInfo.CanFlank = true;
}
else
{
flankInfo.FlankPoints[i] = new Stack<Point>(0);
}
}
return flankInfo;
}
/// <summary>
/// Similar to GetFlanks, but exists when it finds the first one. Mainly for checking if a play is legal.
/// </summary>
/// <param name="centerX">The X value to center the search on</param>
/// <param name="centerY">The Y value to center the search on</param>
/// <returns>Flankinfo class (WILL NOT HAVE ALL POSSIBLE FLANKS)</returns>
/// <remarks>This functuion is purely for checking that at least one flank exists on the piece.
/// There is no guarantee that it will find all the flanks because it stops at the first one.
/// If you want to get all the flanks, use <see cref="GetFlanks(int, int)"/> instead.</remarks>
private FlankInfo AnyFlanks(int centerX, int centerY)
{
FlankInfo flankInfo = new FlankInfo();
// Loops through each direction
for (int i = 0; i < Directions.Length; i++)
{
ref Direction dir = ref Directions[i];
// Stack size is slightly overkill, but it's to avoid any potential stack overflows
Stack<Point> Flanks = new Stack<Point>(128);
// If I find a flank in a specific direction, add its stack to the array,
// if not, add a blank stack.
if (FindFlank(centerX + dir.dx, centerY + dir.dy, dir, Flanks, true))
{
// MessageBox.Show($"FlankDir: {dir.dx},{dir.dy} successfull");
flankInfo.FlankPoints[i] = Flanks;
// indicates that at least one flank is available (saves any looping later)
flankInfo.CanFlank = true;
return flankInfo;
}
else
{
flankInfo.FlankPoints[i] = new Stack<Point>(0);
}
}
return flankInfo;
}
/// <summary>
/// Recursive function that goes in a specified direction and finds all the objects that can be flanked
/// </summary>
/// <param name="x">Current point X</param>
/// <param name="y">Current point Y</param>
/// <param name="dir">Direction to go (if recursing)</param>
/// <param name="Flanks">A stack that all flank info will be pushed to</param>
/// <param name="first">Is this the first iteration?</param>
/// <returns>Returns true if a flank is found</returns>
private bool FindFlank(int x, int y, Direction dir, Stack<Point> Flanks, bool first = false)
{
// Only runs the checks if x and y are on the grid.
if ((x >= 0 && x < gameGrid1.Columns) && (y >= 0 && y < gameGrid1.Rows))
{
CellValues opponentCell = (currentPlayer == playerinfo1) ? playerinfo2.CellValue : playerinfo1.CellValue;
CellValues cell = GetCell(x, y);
// This should only occur if it's all the wrong color, then blank.
// (So no flank found)
if (cell == CellValues.blank)
{
return false;
}
// If it encounters an enemy cell, add to the flanks stack, and continue moving in that direction
if (cell == opponentCell)
{
// fixes weird edge case that occasionally happens
if (Flanks == null)
{
return false;
}
// Add to flanks
Flanks.Push(new Point(x, y));
return FindFlank(x + dir.dx, y + dir.dy, dir, Flanks);
}
// If it encounters a friendly cell, return true and end the search.
if (cell == currentPlayer.CellValue)
{
// if this is the first cell it's going to and it's friendly, it's not a flank
// Otherwise, it is a flank (and will return true)
return !first;
}
}
// In the event none of the above trigger, return false
return false;
}
/// <summary>
/// Displays text on top right as well as synthesises it
/// </summary>
/// <param name="text">Text to display / speak</param>
private void Speak(string text, bool silent = false, bool messagebox = false)
{
txt_speech.Text = text;
if (chk_speak.Checked)
{
synth.SpeakAsyncCancelAll();
synth.SpeakAsync(text);
}
else if (!silent)
{
SystemSounds.Beep.Play();
}
if (messagebox)
{
MessageBox.Show(text);
}
}
/// <summary>
/// Stops all currently running voice lines, and clears the output box
/// </summary>
private void StopSpeak()
{
Speak("", true);
}
/// <summary>
/// Checks the whole board for all legal moves
/// </summary>
/// <returns>Array of legal moves, and their positions</returns>
private CellScoreInfo[] GetLegalMoves()
{
List<CellScoreInfo> cellList = new List<CellScoreInfo>(gameGrid1.Columns * gameGrid1.Rows);
for (int x = 0; x < gameGrid1.Columns; x++)
{
for (int y = 0; y < gameGrid1.Rows; y++)
{
CellScoreInfo cell = GetMoveScore(x, y);
if (cell.valid)
{
//MessageBox.Show($"found legal move {x},{y}");
cellList.Add(cell);
}
}
}
return cellList.ToArray();
}
/// <summary>
/// Checks the whole board for any legal moves
/// </summary>
/// <returns>True if any legal moves are found, false if none are found</returns>
private bool AnyLegalMoves()
{
for (int x = 0; x < gameGrid1.Columns; x++)
{
for (int y = 0; y < gameGrid1.Rows; y++)
{
if (LegalMove(x, y))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Sets the values of the different squares to the new values.
/// </summary>
private void SetGameVals(CellValues[,] newVals)
{
gameVals = newVals;
gameGrid1.Columns = gameVals.GetLength(0);
gameGrid1.Rows = gameVals.GetLength(1);
gameGrid1.InitializeGrid();
for (int x = 0; x < newVals.GetLength(0); x++)
{
for (int y = 0; y < newVals.GetLength(1); y++)
{
SetCell(x, y, gameVals[x, y]);
}
}
}
/// <summary>
/// Prompts the user to select a file location, then saves the current game to it
/// </summary>
private void SaveGameToFile()
{
saveFileDialog1.FileName = "O'NeilloSave.ej";
switch (saveFileDialog1.ShowDialog())
{
case (DialogResult.OK):
{
GameData gd = new GameData()
{
CurrentPlayer = (int)currentPlayer.CellValue,
Player1Name = playerinfo1.PlayerName,
Player2Name = playerinfo2.PlayerName,
Player1Score = playerinfo1.Tokens,
Player2Score = playerinfo2.Tokens,
GameColumns = gameGrid1.Columns,
GameRows = gameGrid1.Rows,
GameValsData = gameVals
};
File.WriteAllText(saveFileDialog1.FileName, SerializeGame(gd));
break;
}
default:
break;
}
}
/// <summary>
/// Prompts the user to select a file, then loads it
/// </summary>
private void LoadGameFromFile(string fileName)
{
try
{
if (!File.Exists(fileName)) throw new Exception("File not found");
GameData gd = DeSerializeGame(File.ReadAllLines(fileName));
LoadGame(gd);
}
catch (Exception e)
{
MessageBox.Show(e.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Loads the data from the gd paramter into the current game
/// </summary>
/// <param name="gd">Game Data to load</param>
private void LoadGame(GameData gd)
{
currentPlayer = (playerinfo1.CellValue == (CellValues)gd.CurrentPlayer) ? playerinfo1 : playerinfo2;
playerinfo1.PlayerName = gd.Player1Name;
playerinfo1.Tokens = gd.Player1Score;
playerinfo2.PlayerName = gd.Player2Name;
playerinfo2.Tokens = gd.Player2Score;
gameGrid1.Columns = gd.GameColumns;
gameGrid1.Rows = gd.GameRows;
gameGrid1.InitializeGrid();
SetGameVals(gd.GameValsData);
playing = true;
playerinfo1.PlayerTurn = false;
playerinfo2.PlayerTurn = false;
currentPlayer.PlayerTurn = true;
}
/// <summary>
/// Converts the supplied gamedata to a string (Mainly for saving to a file)
/// </summary>
/// <param name="data">GameData to save</param>
/// <returns></returns>
private string SerializeGame(GameData data)
{
string OutputString = @"
# Serialization format: (lines starting with # are comments)
# All new values should be prefaced with two letters, then a colon
# ve:xx
# - Serialization version
# p1:xxx
# - Player1 Name
# p2:xxx
# - Player2 Name
# s1:xxx
# - Player1 Score
# s2:xxx
# - Player2 Score
# pc:xxx
# - Current Player (0|1)
# gr:xxx
# - Game Rows
# gc:xxx
# - Game Columns
# gd:x,x,x
# - gamevals Data, in CSV format, all one line in following order:
# ╔═══╦═══╦═══╗
# ║ 2 ║ 5 ║ 8 ║
# ║ 1 ║ 4 ║ 7 ║
# ║ 0 ║ 3 ║ 6 ║
# ╚═══╩═══╩═══╝
";
OutputString += Environment.NewLine;
OutputString += $"ve:{SerialisationVersion}";
OutputString += Environment.NewLine;
OutputString += $"p1:{data.Player1Name}";
OutputString += Environment.NewLine;
OutputString += $"p2:{data.Player2Name}";
OutputString += Environment.NewLine;
OutputString += $"s1:{data.Player1Score}";
OutputString += Environment.NewLine;
OutputString += $"s2:{data.Player2Score}";
OutputString += Environment.NewLine;
OutputString += $"pc:{data.CurrentPlayer}";
OutputString += Environment.NewLine;
OutputString += $"gr:{data.GameRows}";
OutputString += Environment.NewLine;
OutputString += $"gc:{data.GameColumns}";
int[] flatVars = new int[gameVals.GetLength(0) * gameVals.GetLength(1)];
for (int x = 0; x < data.GameColumns; x++)