-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.xaml.cs
1041 lines (950 loc) · 42.6 KB
/
MainWindow.xaml.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 Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Shogi
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ShogiGame game = new(false);
private readonly Settings config;
private Pieces.Piece? grabbedPiece = null;
/// <summary>
/// <see langword="true"/> if the player has selected a piece but isn't dragging it, <see langword="false"/> otherwise
/// </summary>
private bool highlightGrabbedMoves = false;
private Type? selectedDropType = null;
private HashSet<System.Drawing.Point> squareHighlights = new();
private HashSet<(System.Drawing.Point, System.Drawing.Point)> lineHighlights = new();
private System.Drawing.Point? mouseDownStartPoint = null;
private bool senteIsComputer = false;
private bool goteIsComputer = false;
private BoardAnalysis.PossibleMove? currentBestMove = null;
private bool manuallyEvaluating = false;
private readonly Dictionary<Pieces.Piece, Border> pieceViews = new();
private CancellationTokenSource cancelMoveComputation = new();
private double tileWidth;
private double tileHeight;
public MainWindow()
{
string jsonPath = System.IO.Path.Join(AppDomain.CurrentDomain.BaseDirectory, "shogi-settings.json");
config = File.Exists(jsonPath)
? JsonConvert.DeserializeObject<Settings>(File.ReadAllText(jsonPath)) ?? new Settings()
: new Settings();
InitializeComponent();
shogiBoardBackground.Background = new SolidColorBrush(config.BoardColor);
miniShogiBoardBackground.Background = new SolidColorBrush(config.BoardColor);
flipBoardItem.IsChecked = config.FlipBoard;
updateEvalAfterBotItem.IsChecked = config.UpdateEvalAfterBot;
foreach (MenuItem item in pieceSetItem.Items)
{
item.IsChecked = config.PieceSet == (string)item.Tag;
}
foreach (MenuItem item in notationSetItem.Items)
{
item.IsChecked = config.Notation == (string)item.Tag;
}
}
public void UpdateGameDisplay()
{
if (game.AwaitingPromotionResponse)
{
return;
}
shogiGameCanvas.Children.Clear();
pieceViews.Clear();
shogiBoardBackground.Children.Remove(sizeReference);
miniShogiBoardBackground.Children.Remove(sizeReference);
bool boardFlipped = config.FlipBoard && ((!game.CurrentTurnSente && !goteIsComputer) || (senteIsComputer && !goteIsComputer));
bool minishogi = game.Board.GetLength(0) == 5;
tileWidth = shogiGameCanvas.ActualWidth / game.Board.GetLength(0);
tileHeight = shogiGameCanvas.ActualHeight / game.Board.GetLength(1);
foreach (Grid dropItem in senteDropsPanel.Children)
{
Type pieceType = (Type)dropItem.Tag;
int heldCount = game.SentePieceDrops[pieceType];
dropItem.Opacity = heldCount == 0 ? 0.55 : 1;
SolidColorBrush dropBackground;
if (game.CurrentTurnSente)
{
if (currentBestMove is not null && currentBestMove.Value.Source.X == -1
&& ShogiGame.DropTypeOrder[currentBestMove.Value.Source.Y] == pieceType)
{
dropBackground = new SolidColorBrush(config.BestMoveSourceColor);
}
else if (selectedDropType == pieceType)
{
dropBackground = new SolidColorBrush(config.SelectedPieceColor);
}
else
{
dropBackground = Brushes.Transparent;
}
}
else
{
dropBackground = Brushes.Transparent;
}
dropItem.Background = dropBackground;
((Label)dropItem.Children[1]).Content = heldCount;
((Label)dropItem.Children[1]).VerticalAlignment = boardFlipped ? VerticalAlignment.Bottom : VerticalAlignment.Top;
((Image)dropItem.Children[0]).Source = new BitmapImage(new Uri(
$"pack://application:,,,/Pieces/{config.PieceSet}/{(boardFlipped ? "Gote" : "Sente")}/{((Image)dropItem.Children[0]).Tag}.png"));
}
foreach (Grid dropItem in goteDropsPanel.Children)
{
Type pieceType = (Type)dropItem.Tag;
int heldCount = game.GotePieceDrops[pieceType];
dropItem.Opacity = heldCount == 0 ? 0.55 : 1;
SolidColorBrush dropBackground;
if (!game.CurrentTurnSente)
{
if (currentBestMove is not null && currentBestMove.Value.Source.X == -1
&& ShogiGame.DropTypeOrder[currentBestMove.Value.Source.Y] == pieceType)
{
dropBackground = new SolidColorBrush(config.BestMoveSourceColor);
}
else if (selectedDropType == pieceType)
{
dropBackground = new SolidColorBrush(config.SelectedPieceColor);
}
else
{
dropBackground = Brushes.Transparent;
}
}
else
{
dropBackground = Brushes.Transparent;
}
dropItem.Background = dropBackground;
((Label)dropItem.Children[1]).Content = heldCount;
((Label)dropItem.Children[1]).VerticalAlignment = boardFlipped ? VerticalAlignment.Top : VerticalAlignment.Bottom;
((Image)dropItem.Children[0]).Source = new BitmapImage(new Uri(
$"pack://application:,,,/Pieces/{config.PieceSet}/{(boardFlipped ? "Sente" : "Gote")}/{((Image)dropItem.Children[0]).Tag}.png"));
}
if (currentBestMove is null && !manuallyEvaluating)
{
if (game.CurrentTurnSente && !senteIsComputer)
{
senteEvaluation.Content = "?";
}
else if (!goteIsComputer)
{
goteEvaluation.Content = "?";
}
}
if (boardFlipped)
{
Grid.SetColumn(senteEvaluationView, 2);
Grid.SetRow(senteEvaluationView, 0);
Grid.SetColumn(goteEvaluationView, 0);
Grid.SetRow(goteEvaluationView, 2);
Grid.SetRow(senteDropsContainer, 1);
Grid.SetRow(goteDropsContainer, 3);
foreach (UIElement child in ranksLeft.Children)
{
DockPanel.SetDock(child, Dock.Bottom);
}
foreach (UIElement child in ranksRight.Children)
{
DockPanel.SetDock(child, Dock.Bottom);
}
foreach (UIElement child in filesTop.Children)
{
DockPanel.SetDock(child, Dock.Right);
}
foreach (UIElement child in filesBottom.Children)
{
DockPanel.SetDock(child, Dock.Left);
}
}
else
{
Grid.SetColumn(senteEvaluationView, 0);
Grid.SetRow(senteEvaluationView, 2);
Grid.SetColumn(goteEvaluationView, 2);
Grid.SetRow(goteEvaluationView, 0);
Grid.SetRow(senteDropsContainer, 3);
Grid.SetRow(goteDropsContainer, 1);
foreach (UIElement child in ranksLeft.Children)
{
DockPanel.SetDock(child, Dock.Top);
}
foreach (UIElement child in ranksRight.Children)
{
DockPanel.SetDock(child, Dock.Top);
}
foreach (UIElement child in filesTop.Children)
{
DockPanel.SetDock(child, Dock.Left);
}
foreach (UIElement child in filesBottom.Children)
{
DockPanel.SetDock(child, Dock.Right);
}
}
if (minishogi)
{
shogiBoardBackground.Visibility = Visibility.Collapsed;
miniShogiBoardBackground.Visibility = Visibility.Visible;
_ = miniShogiBoardBackground.Children.Add(sizeReference);
}
else
{
shogiBoardBackground.Visibility = Visibility.Visible;
miniShogiBoardBackground.Visibility = Visibility.Collapsed;
_ = shogiBoardBackground.Children.Add(sizeReference);
}
movesPanel.Children.Clear();
List<string> moves = config.Notation == "western"
? game.WesternMoveText
: game.JapaneseMoveText;
for (int i = 0; i < moves.Count; i++)
{
string text = $"{i + 1}. {moves[i]}";
_ = movesPanel.Children.Add(new Label()
{
Content = text,
FontSize = 18
});
}
GameState state = game.DetermineGameState();
int boardMaxY = game.Board.GetLength(1) - 1;
int boardMaxX = game.Board.GetLength(0) - 1;
if (state is GameState.CheckMateSente or GameState.CheckMateGote)
{
System.Drawing.Point kingPosition = state == GameState.CheckMateSente ? game.SenteKing.Position : game.GoteKing.Position;
Rectangle mateHighlight = new()
{
Width = tileWidth,
Height = tileHeight,
Fill = new SolidColorBrush(config.CheckMateHighlightColor)
};
_ = shogiGameCanvas.Children.Add(mateHighlight);
Canvas.SetBottom(mateHighlight, (boardFlipped ? boardMaxY - kingPosition.Y : kingPosition.Y) * tileHeight);
Canvas.SetLeft(mateHighlight, (boardFlipped ? boardMaxX - kingPosition.X : kingPosition.X) * tileWidth);
}
if (game.Moves.Count > 0)
{
(_, System.Drawing.Point lastMoveSource, System.Drawing.Point lastMoveDestination, _, _) = game.Moves[^1];
if (lastMoveSource.X != -1)
{
Rectangle sourceMoveHighlight = new()
{
Width = tileWidth,
Height = tileHeight,
Fill = new SolidColorBrush(config.LastMoveSourceColor)
};
_ = shogiGameCanvas.Children.Add(sourceMoveHighlight);
Canvas.SetBottom(sourceMoveHighlight, (boardFlipped ? boardMaxY - lastMoveSource.Y : lastMoveSource.Y) * tileHeight);
Canvas.SetLeft(sourceMoveHighlight, (boardFlipped ? boardMaxX - lastMoveSource.X : lastMoveSource.X) * tileWidth);
}
Rectangle destinationMoveHighlight = new()
{
Width = tileWidth,
Height = tileHeight,
Fill = new SolidColorBrush(config.LastMoveDestinationColor)
};
_ = shogiGameCanvas.Children.Add(destinationMoveHighlight);
Canvas.SetBottom(destinationMoveHighlight, (boardFlipped ? boardMaxY - lastMoveDestination.Y : lastMoveDestination.Y) * tileHeight);
Canvas.SetLeft(destinationMoveHighlight, (boardFlipped ? boardMaxX - lastMoveDestination.X : lastMoveDestination.X) * tileWidth);
}
if (currentBestMove is not null
// Prevent cases where there are no valid moves highlighting (0, 0)
&& currentBestMove.Value.Source != currentBestMove.Value.Destination)
{
if (currentBestMove.Value.Source.X != -1)
{
Rectangle bestMoveSrcHighlight = new()
{
Width = tileWidth,
Height = tileHeight,
Fill = new SolidColorBrush(config.BestMoveSourceColor)
};
_ = shogiGameCanvas.Children.Add(bestMoveSrcHighlight);
Canvas.SetBottom(bestMoveSrcHighlight,
(boardFlipped ? boardMaxY - currentBestMove.Value.Source.Y : currentBestMove.Value.Source.Y) * tileHeight);
Canvas.SetLeft(bestMoveSrcHighlight,
(boardFlipped ? boardMaxX - currentBestMove.Value.Source.X : currentBestMove.Value.Source.X) * tileWidth);
}
Rectangle bestMoveDstHighlight = new()
{
Width = tileWidth,
Height = tileHeight,
Fill = new SolidColorBrush(config.BestMoveDestinationColor)
};
_ = shogiGameCanvas.Children.Add(bestMoveDstHighlight);
Canvas.SetBottom(bestMoveDstHighlight,
(boardFlipped ? boardMaxY - currentBestMove.Value.Destination.Y : currentBestMove.Value.Destination.Y) * tileHeight);
Canvas.SetLeft(bestMoveDstHighlight,
(boardFlipped ? boardMaxX - currentBestMove.Value.Destination.X : currentBestMove.Value.Destination.X) * tileWidth);
}
if (grabbedPiece is not null && highlightGrabbedMoves)
{
foreach (System.Drawing.Point validMove in grabbedPiece.GetValidMoves(game.Board, true))
{
Brush fillBrush;
if (game.Board[validMove.X, validMove.Y] is not null)
{
fillBrush = new SolidColorBrush(config.AvailableCaptureColor);
}
else
{
fillBrush = new SolidColorBrush(config.AvailableMoveColor);
}
Rectangle newRect = new()
{
Width = tileWidth,
Height = tileHeight,
Fill = fillBrush
};
_ = shogiGameCanvas.Children.Add(newRect);
Canvas.SetBottom(newRect, (boardFlipped ? boardMaxY - validMove.Y : validMove.Y) * tileHeight);
Canvas.SetLeft(newRect, (boardFlipped ? boardMaxX - validMove.X : validMove.X) * tileWidth);
}
}
if (selectedDropType is not null)
{
for (int x = 0; x < game.Board.GetLength(0); x++)
{
for (int y = 0; y < game.Board.GetLength(1); y++)
{
if (game.IsDropPossible(selectedDropType, new System.Drawing.Point(x, y)))
{
Rectangle newRect = new()
{
Width = tileWidth,
Height = tileHeight,
Fill = new SolidColorBrush(config.AvailableMoveColor)
};
_ = shogiGameCanvas.Children.Add(newRect);
Canvas.SetBottom(newRect, (boardFlipped ? boardMaxY - y : y) * tileHeight);
Canvas.SetLeft(newRect, (boardFlipped ? boardMaxX - x : x) * tileWidth);
}
}
}
}
for (int x = 0; x < game.Board.GetLength(0); x++)
{
for (int y = 0; y < game.Board.GetLength(1); y++)
{
Pieces.Piece? piece = game.Board[x, y];
if (piece is not null)
{
Brush? backgroundBrush = null;
if (piece is Pieces.King && ((piece.IsSente && state == GameState.CheckSente) || (!piece.IsSente && state == GameState.CheckGote)))
{
backgroundBrush = new SolidColorBrush(config.CheckedKingColor);
}
else if (highlightGrabbedMoves && piece == grabbedPiece)
{
backgroundBrush = new SolidColorBrush(config.SelectedPieceColor);
}
Border newPiece = new()
{
Child = new Image()
{
Source = new BitmapImage(
new Uri($"pack://application:,,,/Pieces/{config.PieceSet}/{(piece.IsSente ^ boardFlipped ? "Sente" : "Gote")}/{piece.Name}.png"))
},
Width = tileWidth,
Height = tileHeight,
Background = backgroundBrush
};
RenderOptions.SetBitmapScalingMode(newPiece, BitmapScalingMode.HighQuality);
pieceViews[piece] = newPiece;
_ = shogiGameCanvas.Children.Add(newPiece);
Canvas.SetBottom(newPiece, (boardFlipped ? boardMaxY - y : y) * tileHeight);
Canvas.SetLeft(newPiece, (boardFlipped ? boardMaxX - x : x) * tileWidth);
}
}
}
foreach (System.Drawing.Point square in squareHighlights)
{
Ellipse ellipse = new()
{
Fill = new SolidColorBrush(config.SelectedPieceColor),
Opacity = 0.5,
Width = tileWidth * 0.8,
Height = tileHeight * 0.8
};
_ = shogiGameCanvas.Children.Add(ellipse);
Canvas.SetBottom(ellipse, ((boardFlipped ? boardMaxY - square.Y : square.Y) * tileHeight) + (tileHeight * 0.1));
Canvas.SetLeft(ellipse, (boardFlipped ? boardMaxX - square.X : square.X) * tileWidth + (tileWidth * 0.1));
}
foreach ((System.Drawing.Point lineStart, System.Drawing.Point lineEnd) in lineHighlights)
{
double arrowLength = Math.Min(tileWidth, tileHeight) / 4;
Petzold.Media2D.ArrowLine line = new()
{
Stroke = new SolidColorBrush(config.SelectedPieceColor),
Fill = new SolidColorBrush(config.SelectedPieceColor),
Opacity = 0.5,
StrokeThickness = 10,
ArrowLength = arrowLength,
ArrowAngle = 45,
IsArrowClosed = true,
X1 = (boardFlipped ? boardMaxX - lineStart.X : lineStart.X) * tileWidth + (tileWidth / 2),
X2 = (boardFlipped ? boardMaxX - lineEnd.X : lineEnd.X) * tileWidth + (tileWidth / 2),
Y1 = (boardFlipped ? lineStart.Y : boardMaxY - lineStart.Y) * tileHeight + (tileHeight / 2),
Y2 = (boardFlipped ? lineEnd.Y : boardMaxY - lineEnd.Y) * tileHeight + (tileHeight / 2)
};
_ = shogiGameCanvas.Children.Add(line);
}
}
private void UpdateCursor()
{
if (game.GameOver)
{
Mouse.OverrideCursor = Cursors.Arrow;
return;
}
if (grabbedPiece is not null && !highlightGrabbedMoves)
{
Mouse.OverrideCursor = Cursors.ScrollAll;
return;
}
Pieces.Piece? checkPiece = GetPieceAtCanvasPoint(Mouse.GetPosition(shogiGameCanvas));
if (checkPiece is not null && ((checkPiece.IsSente && game.CurrentTurnSente && !senteIsComputer)
|| (!checkPiece.IsSente && !game.CurrentTurnSente && !goteIsComputer)))
{
Mouse.OverrideCursor = Cursors.Hand;
return;
}
Mouse.OverrideCursor = Cursors.Arrow;
}
/// <summary>
/// If the game has ended, alert the user how it ended, otherwise do nothing
/// </summary>
private void PushEndgameMessage()
{
if (game.GameOver)
{
_ = MessageBox.Show(game.DetermineGameState() switch
{
GameState.CheckMateSente => "Gote wins by checkmate!",
GameState.CheckMateGote => "Sente wins by checkmate!",
GameState.StalemateSente => "Gote wins by stalemate!",
GameState.StalemateGote => "Sente wins by stalemate!",
GameState.PerpetualCheckSente => "Sente wins as gote attempted to draw through perpetual check",
GameState.PerpetualCheckGote => "Gote wins as sente attempted to draw through perpetual check",
GameState.DrawRepetition => "Game drawn as the same position has occured four times",
_ => "Game over"
}, "Game Over", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
private void UpdateEvaluationMeter(BoardAnalysis.PossibleMove? bestMove, bool sente)
{
Label toUpdate = sente ? senteEvaluation : goteEvaluation;
if (bestMove is null)
{
toUpdate.Content = "...";
toUpdate.ToolTip = null;
return;
}
if ((bestMove.Value.SenteMateLocated && !bestMove.Value.GoteMateLocated)
|| bestMove.Value.EvaluatedFutureValue == double.NegativeInfinity)
{
toUpdate.Content = $"-M{bestMove.Value.DepthToSenteMate}";
}
else if ((bestMove.Value.GoteMateLocated && !bestMove.Value.SenteMateLocated)
|| bestMove.Value.EvaluatedFutureValue == double.PositiveInfinity)
{
toUpdate.Content = $"+M{bestMove.Value.DepthToGoteMate}";
}
else
{
toUpdate.Content = bestMove.Value.EvaluatedFutureValue.ToString("+0.00;-0.00;0.00");
}
string convertedBestLine = "";
ShogiGame moveStringGenerator = game.Clone(false);
foreach ((System.Drawing.Point source, System.Drawing.Point destination, bool doPromotion) in bestMove.Value.BestLine)
{
_ = moveStringGenerator.MovePiece(source, destination, true, doPromotion);
convertedBestLine += " " + moveStringGenerator.JapaneseMoveText[^1];
}
toUpdate.ToolTip = convertedBestLine.Trim();
}
/// <summary>
/// Get the best move according to either the built-in or external engine, depending on configuration
/// </summary>
private async Task<BoardAnalysis.PossibleMove> GetEngineMove(CancellationToken cancellationToken)
{
BoardAnalysis.PossibleMove? bestMove = null;
// Search deeper in minishogi games
bestMove ??= await BoardAnalysis.EstimateBestPossibleMove(game, game.Board.GetLength(0) == 5 ? 4 : 3, true, cancellationToken);
return bestMove.Value;
}
/// <summary>
/// Perform a computer move if necessary
/// </summary>
private async Task CheckComputerMove()
{
while (!game.GameOver && ((game.CurrentTurnSente && senteIsComputer) || (!game.CurrentTurnSente && goteIsComputer)))
{
CancellationToken cancellationToken = cancelMoveComputation.Token;
if (config.UpdateEvalAfterBot)
{
UpdateEvaluationMeter(null, game.CurrentTurnSente);
}
BoardAnalysis.PossibleMove bestMove = await GetEngineMove(cancellationToken);
if (cancellationToken.IsCancellationRequested)
{
return;
}
_ = game.MovePiece(bestMove.Source, bestMove.Destination, true, doPromotion: bestMove.DoPromotion);
UpdateGameDisplay();
movesScroll.ScrollToBottom();
if (config.UpdateEvalAfterBot)
{
// Turn has been inverted already but we have value for the now old turn
UpdateEvaluationMeter(bestMove, !game.CurrentTurnSente);
}
PushEndgameMessage();
}
}
private System.Drawing.Point GetCoordFromCanvasPoint(Point position)
{
bool boardFlipped = config.FlipBoard && ((!game.CurrentTurnSente && !goteIsComputer) || (senteIsComputer && !goteIsComputer));
// Canvas coordinates are relative to top-left, whereas shogi's are from bottom-left, so y is inverted
return new System.Drawing.Point((int)((boardFlipped ? shogiGameCanvas.ActualWidth - position.X : position.X) / tileWidth),
(int)((!boardFlipped ? shogiGameCanvas.ActualHeight - position.Y : position.Y) / tileHeight));
}
private Pieces.Piece? GetPieceAtCanvasPoint(Point position)
{
if (position.X < 0 || position.Y < 0
|| position.X > shogiGameCanvas.ActualWidth || position.Y > shogiGameCanvas.ActualHeight)
{
return null;
}
System.Drawing.Point coord = GetCoordFromCanvasPoint(position);
return coord.X < 0 || coord.Y < 0 || coord.X >= game.Board.GetLength(0) || coord.Y >= game.Board.GetLength(1)
? null
: game.Board[coord.X, coord.Y];
}
private async Task NewGame(bool minishogi)
{
cancelMoveComputation.Cancel();
cancelMoveComputation = new CancellationTokenSource();
game = new ShogiGame(minishogi);
currentBestMove = null;
manuallyEvaluating = false;
grabbedPiece = null;
highlightGrabbedMoves = false;
selectedDropType = null;
senteEvaluation.Content = "?";
goteEvaluation.Content = "?";
UpdateGameDisplay();
UpdateCursor();
await CheckComputerMove();
}
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
UpdateGameDisplay();
await CheckComputerMove();
}
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
UpdateGameDisplay();
moveListColumn.Width = ActualWidth < 900 ? new GridLength(0) : new GridLength(210);
}
private void Window_MouseMove(object sender, MouseEventArgs e)
{
if (grabbedPiece is not null && !highlightGrabbedMoves)
{
Canvas.SetBottom(pieceViews[grabbedPiece], shogiGameCanvas.ActualHeight - Mouse.GetPosition(shogiGameCanvas).Y - (tileHeight / 2));
Canvas.SetLeft(pieceViews[grabbedPiece], Mouse.GetPosition(shogiGameCanvas).X - (tileWidth / 2));
}
UpdateCursor();
}
private async void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
Point mousePos = Mouse.GetPosition(shogiGameCanvas);
if (e.ChangedButton == MouseButton.Left)
{
squareHighlights.Clear();
lineHighlights.Clear();
if (game.GameOver)
{
return;
}
if (selectedDropType is not null && mousePos.X >= 0 && mousePos.Y >= 0 && mousePos.X <= shogiGameCanvas.ActualWidth
&& mousePos.Y <= shogiGameCanvas.ActualHeight)
{
System.Drawing.Point destination = GetCoordFromCanvasPoint(mousePos);
bool success = game.MovePiece(ShogiGame.PieceDropSources[selectedDropType], destination, doPromotion: null);
if (success)
{
highlightGrabbedMoves = false;
grabbedPiece = null;
currentBestMove = null;
selectedDropType = null;
UpdateCursor();
UpdateGameDisplay();
movesScroll.ScrollToBottom();
PushEndgameMessage();
await CheckComputerMove();
return;
}
}
selectedDropType = null;
// If a piece is selected, try to move it
if (grabbedPiece is not null && highlightGrabbedMoves)
{
System.Drawing.Point destination = GetCoordFromCanvasPoint(mousePos);
bool success = game.MovePiece(grabbedPiece.Position, destination, doPromotion: null);
if (success)
{
highlightGrabbedMoves = false;
grabbedPiece = null;
currentBestMove = null;
UpdateCursor();
UpdateGameDisplay();
movesScroll.ScrollToBottom();
PushEndgameMessage();
await CheckComputerMove();
return;
}
}
highlightGrabbedMoves = false;
Pieces.Piece? toCheck = GetPieceAtCanvasPoint(mousePos);
if (toCheck is not null)
{
if ((toCheck.IsSente && game.CurrentTurnSente && !senteIsComputer)
|| (!toCheck.IsSente && !game.CurrentTurnSente && !goteIsComputer))
{
grabbedPiece = toCheck;
manuallyEvaluating = false;
cancelMoveComputation.Cancel();
cancelMoveComputation = new CancellationTokenSource();
}
else
{
grabbedPiece = null;
}
}
else
{
grabbedPiece = null;
}
}
else
{
if (mousePos.X < 0 || mousePos.Y < 0
|| mousePos.X > shogiGameCanvas.ActualWidth || mousePos.Y > shogiGameCanvas.ActualHeight)
{
return;
}
mouseDownStartPoint = GetCoordFromCanvasPoint(mousePos);
}
UpdateGameDisplay();
UpdateCursor();
}
private async void Window_MouseUp(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
if (game.GameOver)
{
return;
}
if (grabbedPiece is not null)
{
System.Drawing.Point destination = GetCoordFromCanvasPoint(Mouse.GetPosition(shogiGameCanvas));
if (destination == grabbedPiece.Position)
{
highlightGrabbedMoves = true;
UpdateCursor();
UpdateGameDisplay();
return;
}
bool success = game.MovePiece(grabbedPiece.Position, destination, doPromotion: null);
if (success)
{
grabbedPiece = null;
highlightGrabbedMoves = false;
currentBestMove = null;
UpdateCursor();
UpdateGameDisplay();
movesScroll.ScrollToBottom();
PushEndgameMessage();
await CheckComputerMove();
return;
}
else
{
highlightGrabbedMoves = true;
}
}
}
else
{
Point mousePos = Mouse.GetPosition(shogiGameCanvas);
if (mousePos.X < 0 || mousePos.Y < 0
|| mousePos.X > shogiGameCanvas.ActualWidth || mousePos.Y > shogiGameCanvas.ActualHeight)
{
return;
}
System.Drawing.Point onSquare = GetCoordFromCanvasPoint(mousePos);
if (mouseDownStartPoint is null || mouseDownStartPoint == onSquare)
{
if (!squareHighlights.Add(onSquare))
{
_ = squareHighlights.Remove(onSquare);
}
}
else
{
if (!lineHighlights.Add((mouseDownStartPoint.Value, onSquare)))
{
_ = lineHighlights.Remove((mouseDownStartPoint.Value, onSquare));
}
}
}
UpdateCursor();
UpdateGameDisplay();
}
private void Window_MouseLeave(object sender, MouseEventArgs e)
{
if (grabbedPiece is not null)
{
highlightGrabbedMoves = true;
}
UpdateGameDisplay();
}
private async void evaluation_MouseUp(object sender, MouseButtonEventArgs e)
{
if (currentBestMove is not null || game.GameOver
|| (game.CurrentTurnSente && senteIsComputer) || (!game.CurrentTurnSente && goteIsComputer))
{
return;
}
manuallyEvaluating = true;
grabbedPiece = null;
highlightGrabbedMoves = false;
selectedDropType = null;
UpdateEvaluationMeter(null, game.CurrentTurnSente);
UpdateGameDisplay();
UpdateCursor();
CancellationToken cancellationToken = cancelMoveComputation.Token;
BoardAnalysis.PossibleMove bestMove = await GetEngineMove(cancellationToken);
if (cancellationToken.IsCancellationRequested)
{
return;
}
UpdateEvaluationMeter(bestMove, game.CurrentTurnSente);
currentBestMove = bestMove;
UpdateGameDisplay();
manuallyEvaluating = false;
}
private async void NewGame_Click(object sender, RoutedEventArgs e)
{
senteIsComputer = false;
goteIsComputer = false;
await NewGame(false);
}
private async void NewGameCpuSente_Click(object sender, RoutedEventArgs e)
{
senteIsComputer = false;
goteIsComputer = true;
await NewGame(false);
}
private async void NewGameCpuGote_Click(object sender, RoutedEventArgs e)
{
senteIsComputer = true;
goteIsComputer = false;
await NewGame(false);
}
private async void NewGameCpuOnly_Click(object sender, RoutedEventArgs e)
{
senteIsComputer = true;
goteIsComputer = true;
await NewGame(false);
}
private async void NewMiniGame_Click(object sender, RoutedEventArgs e)
{
senteIsComputer = false;
goteIsComputer = false;
await NewGame(true);
}
private async void NewMiniGameCpuSente_Click(object sender, RoutedEventArgs e)
{
senteIsComputer = false;
goteIsComputer = true;
await NewGame(true);
}
private async void NewMiniGameCpuGote_Click(object sender, RoutedEventArgs e)
{
senteIsComputer = true;
goteIsComputer = false;
await NewGame(true);
}
private async void NewMiniGameCpuOnly_Click(object sender, RoutedEventArgs e)
{
senteIsComputer = true;
goteIsComputer = true;
await NewGame(true);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
cancelMoveComputation.Cancel();
string jsonPath = System.IO.Path.Join(AppDomain.CurrentDomain.BaseDirectory, "shogi-settings.json");
File.WriteAllText(jsonPath, JsonConvert.SerializeObject(config));
}
private async void KIFExport_Click(object sender, RoutedEventArgs e)
{
manuallyEvaluating = false;
cancelMoveComputation.Cancel();
cancelMoveComputation = new CancellationTokenSource();
_ = new KIFExport(game, senteIsComputer, goteIsComputer).ShowDialog();
await CheckComputerMove();
}
private async void CustomGame_Click(object sender, RoutedEventArgs e)
{
manuallyEvaluating = false;
cancelMoveComputation.Cancel();
cancelMoveComputation = new CancellationTokenSource();
CustomGame customDialog = new(config, false);
_ = customDialog.ShowDialog();
if (customDialog.GeneratedGame is not null)
{
game = customDialog.GeneratedGame;
senteIsComputer = customDialog.SenteIsComputer;
goteIsComputer = customDialog.GoteIsComputer;
grabbedPiece = null;
highlightGrabbedMoves = false;
selectedDropType = null;
currentBestMove = null;
senteEvaluation.Content = "?";
goteEvaluation.Content = "?";
UpdateGameDisplay();
PushEndgameMessage();
}
await CheckComputerMove();
}
private async void CustomMiniGame_Click(object sender, RoutedEventArgs e)
{
manuallyEvaluating = false;
cancelMoveComputation.Cancel();
cancelMoveComputation = new CancellationTokenSource();
CustomGame customDialog = new(config, true);
_ = customDialog.ShowDialog();
if (customDialog.GeneratedGame is not null)
{
game = customDialog.GeneratedGame;
senteIsComputer = customDialog.SenteIsComputer;
goteIsComputer = customDialog.GoteIsComputer;
grabbedPiece = null;
highlightGrabbedMoves = false;
selectedDropType = null;
currentBestMove = null;
senteEvaluation.Content = "?";
goteEvaluation.Content = "?";
UpdateGameDisplay();
PushEndgameMessage();
}
await CheckComputerMove();
}
private void SettingsCheckItem_Click(object sender, RoutedEventArgs e)
{
config.FlipBoard = flipBoardItem.IsChecked;
config.UpdateEvalAfterBot = updateEvalAfterBotItem.IsChecked;
UpdateGameDisplay();
}
private void FENCopy_Click(object sender, RoutedEventArgs e)
{
Clipboard.SetText(game.ToString());
}
private void CustomiseItem_Click(object sender, RoutedEventArgs e)
{
_ = new Customisation(config).ShowDialog();
shogiBoardBackground.Background = new SolidColorBrush(config.BoardColor);
miniShogiBoardBackground.Background = new SolidColorBrush(config.BoardColor);
UpdateGameDisplay();
}
private void PieceSetItem_Click(object sender, RoutedEventArgs e)
{
string chosenSet = (string)((MenuItem)sender).Tag;
config.PieceSet = chosenSet;
foreach (MenuItem item in pieceSetItem.Items)
{
item.IsChecked = chosenSet == (string)item.Tag;
}
UpdateGameDisplay();
}
private void NotationSetItem_Click(object sender, RoutedEventArgs e)
{
string chosenNotation = (string)((MenuItem)sender).Tag;
config.Notation = chosenNotation;
foreach (MenuItem item in notationSetItem.Items)
{
item.IsChecked = chosenNotation == (string)item.Tag;
}
UpdateGameDisplay();
}
private async void UndoMove_Click(object sender, RoutedEventArgs e)
{
if (game.PreviousGameState is not null
&& ((game.CurrentTurnSente && !senteIsComputer) || (!game.CurrentTurnSente && !goteIsComputer)))
{
game = game.PreviousGameState;
if (senteIsComputer || goteIsComputer)
{
// Reverse two moves if the opponent is computer controlled
game = game.PreviousGameState!;
}
grabbedPiece = null;
highlightGrabbedMoves = false;
selectedDropType = null;
currentBestMove = null;
senteEvaluation.Content = "?";