-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
3213 lines (2870 loc) · 83.7 KB
/
main.go
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
package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"image/color"
"io"
"math"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/dialog"
"fyne.io/fyne/v2/driver/desktop"
"fyne.io/fyne/v2/storage"
"fyne.io/fyne/v2/widget"
)
const (
empty = "."
black = "B"
white = "W"
gridLineThickness = 0.15
version = "2"
)
var (
gobanColor = color.RGBA{108, 84, 60, 255}
lineColor = color.RGBA{93, 74, 51, 255}
blackColor = color.Black
whiteColor = color.White
blackScoreColor = color.RGBA{0, 0, 255, 255}
whiteScoreColor = color.RGBA{0, 255, 0, 255}
transparentWhiteColor = color.NRGBA{255, 255, 255, 128}
transparentBlackColor = color.NRGBA{0, 0, 0, 128}
redColor = color.RGBA{255, 0, 0, 255}
purpleColor = color.RGBA{128, 0, 128, 255}
)
type Config struct {
Komi int `json:"komi"`
GTPPath string `json:"gtpPath"`
GTPArgs string `json:"gtpArgs"`
GTPColor string `json:"gtpColor"`
}
func (g *Game) loadConfig() error {
exePath, err := os.Executable()
if err != nil {
return err
}
configPath := filepath.Join(filepath.Dir(exePath), "ConnectedGroupsGoban.config")
file, err := os.Open(configPath)
if err != nil {
return err
}
defer file.Close()
var config Config
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
if err != nil {
return err
}
// Apply the loaded configuration
g.komi = config.Komi
g.gtpPath = config.GTPPath
g.gtpArgs = config.GTPArgs
g.gtpColor = config.GTPColor
return nil
}
func (g *Game) saveConfig() error {
exePath, err := os.Executable()
if err != nil {
return err
}
configPath := filepath.Join(filepath.Dir(exePath), "ConnectedGroupsGoban.config")
config := Config{
Komi: g.komi,
GTPPath: g.gtpPath,
GTPArgs: g.gtpArgs,
GTPColor: g.gtpColor,
}
file, err := os.Create(configPath)
if err != nil {
return err
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ") // Pretty print for readability
err = encoder.Encode(config)
if err != nil {
return err
}
return nil
}
type Game struct {
sizeX int
sizeY int
boardCanvas *fyne.Container
gridContainer *fyne.Container
hoverStone *canvas.Circle
window fyne.Window
cellSize float32
currentNode *GameTreeNode
rootNode *GameTreeNode
nodeMap map[string]*GameTreeNode
idCounter int
gameTreeContainer *container.Scroll
mouseMode string
territoryMap [][]string
territoryLayer *fyne.Container
scoringStatus *widget.Label
commentEntry *widget.Entry
komi int
gtpPath string
gtpArgs string
gtpColor string
gtpCmd *exec.Cmd
gtpIn io.WriteCloser
gtpOut io.ReadCloser
gtpReader *bufio.Reader
selfPlaying bool
selfPlayCtx context.Context
selfPlayCancel context.CancelFunc
selfPlayWaitGrp sync.WaitGroup
}
func (g *Game) newGameTreeNode() *GameTreeNode {
g.idCounter++
newNode := &GameTreeNode{
boardState: makeEmptyBoard(g.sizeX, g.sizeY),
id: fmt.Sprintf("%d", g.idCounter),
koX: -1,
koY: -1,
addedBlackStones: make([][]bool, g.sizeY),
addedWhiteStones: make([][]bool, g.sizeY),
AE: make([][]bool, g.sizeY),
CR: make([][]bool, g.sizeY),
SQ: make([][]bool, g.sizeY),
TR: make([][]bool, g.sizeY),
MA: make([][]bool, g.sizeY),
LB: make([][]string, g.sizeY),
}
for y := 0; y < g.sizeY; y++ {
newNode.addedBlackStones[y] = make([]bool, g.sizeX)
newNode.addedWhiteStones[y] = make([]bool, g.sizeX)
newNode.AE[y] = make([]bool, g.sizeX)
newNode.CR[y] = make([]bool, g.sizeX)
newNode.SQ[y] = make([]bool, g.sizeX)
newNode.TR[y] = make([]bool, g.sizeX)
newNode.MA[y] = make([]bool, g.sizeX)
newNode.LB[y] = make([]string, g.sizeX)
}
g.nodeMap[newNode.id] = newNode
return newNode
}
type GameTreeNode struct {
boardState [][]string // Current state of the board at this node
move [2]int // Coordinates of the move ([x, y]); (-1, -1) represents a pass
player string // Player who made the move ("B" for Black, "W" for White)
children []*GameTreeNode // Child nodes representing subsequent moves
parent *GameTreeNode // Parent node in the game tree
id string // Unique identifier for the node
koX int // X-coordinate for ko rule; -1 if not applicable
koY int // Y-coordinate for ko rule; -1 if not applicable
Comment string // Optional comment for the move
addedBlackStones [][]bool // Coordinates of additional Black stones (AB properties)
addedWhiteStones [][]bool // Coordinates of additional White stones (AW properties)
AE [][]bool // Coordinates of points made empty (AE properties)
CR [][]bool // Coordinates for circle annotations
SQ [][]bool // Coordinates for square annotations
TR [][]bool // Coordinates for triangle annotations
MA [][]bool // Coordinates for mark (X) annotations
LB [][]string // Labels for specific points on the board
}
func (gtn *GameTreeNode) addBlackStone(x, y int) {
if x >= 0 && x < len(gtn.addedBlackStones[0]) && y >= 0 && y < len(gtn.addedBlackStones) {
gtn.addedBlackStones[y][x] = true
}
}
func (gtn *GameTreeNode) hasAddedBlackStones() bool {
for _, arr := range gtn.addedBlackStones {
for _, el := range arr {
if el {
return true
}
}
}
return false
}
func (gtn *GameTreeNode) addWhiteStone(x, y int) {
if x >= 0 && x < len(gtn.addedWhiteStones[0]) && y >= 0 && y < len(gtn.addedWhiteStones) {
gtn.addedWhiteStones[y][x] = true
}
}
func (gtn *GameTreeNode) hasAddedWhiteStones() bool {
for _, arr := range gtn.addedWhiteStones {
for _, el := range arr {
if el {
return true
}
}
}
return false
}
type ResizingContainer struct {
widget.BaseWidget
content fyne.CanvasObject
placeholder fyne.CanvasObject
resizeTimer *time.Timer
mutex sync.Mutex
}
func NewResizingContainer(content fyne.CanvasObject, placeholder fyne.CanvasObject) *ResizingContainer {
rc := &ResizingContainer{
content: content,
placeholder: placeholder,
}
rc.ExtendBaseWidget(rc)
rc.placeholder.Hide() // Hide the placeholder initially
return rc
}
func (rc *ResizingContainer) CreateRenderer() fyne.WidgetRenderer {
return &resizingContainerRenderer{
container: rc,
}
}
func (rc *ResizingContainer) Resize(size fyne.Size) {
// Check if the size is different before proceeding
if rc.Size() == size {
return // Skip handling if the size has not changed
}
rc.BaseWidget.Resize(size)
rc.handleResize()
}
func (rc *ResizingContainer) handleResize() {
rc.mutex.Lock()
defer rc.mutex.Unlock()
if rc.resizeTimer != nil {
rc.resizeTimer.Stop()
}
rc.content.Hide()
rc.placeholder.Show()
rc.Refresh()
rc.resizeTimer = time.AfterFunc(39*time.Millisecond, func() {
rc.mutex.Lock()
defer rc.mutex.Unlock()
rc.placeholder.Hide()
rc.content.Show()
rc.Refresh()
})
}
type resizingContainerRenderer struct {
container *ResizingContainer
}
func (r *resizingContainerRenderer) Layout(size fyne.Size) {
if r.container.content.Visible() {
r.container.content.Resize(size)
}
if r.container.placeholder.Visible() {
r.container.placeholder.Resize(size)
}
}
func (r *resizingContainerRenderer) MinSize() fyne.Size {
minSize := fyne.NewSize(0, 0)
if r.container.content.Visible() {
minSize = minSize.Max(r.container.content.MinSize())
}
if r.container.placeholder.Visible() {
minSize = minSize.Max(r.container.placeholder.MinSize())
}
return minSize
}
func (r *resizingContainerRenderer) Refresh() {
canvas.Refresh(r.container)
}
func (r *resizingContainerRenderer) BackgroundColor() color.Color {
return color.Transparent
}
func (r *resizingContainerRenderer) Objects() []fyne.CanvasObject {
return []fyne.CanvasObject{r.container.content, r.container.placeholder}
}
func (r *resizingContainerRenderer) Destroy() {}
func main() {
a := app.NewWithID("com.nazgand.connectedgroupsgoban")
w := a.NewWindow("Connected Groups Goban Version " + version)
game := &Game{
window: w,
mouseMode: "play",
nodeMap: make(map[string]*GameTreeNode),
komi: 7.0,
gtpPath: "/usr/games/leela_gtp",
gtpArgs: "-g -p 931 --noponder",
gtpColor: "W",
}
// Load configuration
err := game.loadConfig()
if err != nil {
// Handle error (e.g., file not found is acceptable)
fmt.Println("Could not load config:", err)
}
w.Canvas().SetOnTypedKey(game.handleKeyEvent)
// Create scoring status label
game.scoringStatus = widget.NewLabel("Not in scoring mode.")
// Create comment entry with placeholder
game.commentEntry = widget.NewMultiLineEntry()
game.commentEntry.SetPlaceHolder("Current move comment")
// Attach a listener to update the current node's comment when the textbox changes
game.commentEntry.OnChanged = func(content string) {
if game.currentNode != nil {
game.currentNode.Comment = content
}
}
// Create board canvas and related containers
background := canvas.NewRectangle(gobanColor)
inputLayer := newInputLayer(game)
game.gridContainer = container.NewWithoutLayout()
game.boardCanvas = container.NewStack(
background,
game.gridContainer,
inputLayer,
)
game.sizeX = 19
game.sizeY = 19
// Initialize the board here
game.initializeBoard()
game.redrawBoard()
// Initialize the game tree
game.gameTreeContainer = container.NewScroll(nil)
game.updateGameTreeUI()
// Define the "File" menu
fileMenu := fyne.NewMenu("File",
fyne.NewMenuItem("Import SGF", func() {
dialog.ShowFileOpen(func(reader fyne.URIReadCloser, err error) {
if err != nil || reader == nil {
return
}
defer reader.Close()
sgfContent, err := io.ReadAll(reader)
if err != nil {
game.showError(err)
return
}
err = game.importFromSGF(string(sgfContent))
if err != nil {
game.showError(err)
return
}
game.gameTreeContainer.ScrollToBottom()
}, game.window)
}),
fyne.NewMenuItem("Export SGF", func() {
dialog.ShowFileSave(func(writer fyne.URIWriteCloser, err error) {
if err != nil || writer == nil {
return
}
defer writer.Close()
sgfContent, err := game.exportToSGF()
if err != nil {
game.showError(err)
return
}
_, err = writer.Write([]byte(sgfContent))
if err != nil {
game.showError(err)
return
}
}, game.window)
}),
)
gameMenu := fyne.NewMenu("Game",
fyne.NewMenuItem("Fresh Board", func() {
// Define the input entries outside the dialog
widthEntry := widget.NewEntry()
widthEntry.SetPlaceHolder("(1-52)")
widthEntry.SetText(strconv.Itoa(game.sizeX))
heightEntry := widget.NewEntry()
heightEntry.SetPlaceHolder("(1-52)")
heightEntry.SetText(strconv.Itoa(game.sizeY))
// Create form items
formItems := []*widget.FormItem{
widget.NewFormItem("Width", widthEntry),
widget.NewFormItem("Height", heightEntry),
}
// Create a custom dialog to input board width and height
boardSizeDialog := dialog.NewForm(
"Fresh Board",
"OK",
"Cancel",
formItems,
func(ok bool) {
if !ok {
return
}
widthStr := widthEntry.Text
heightStr := heightEntry.Text
x, errX := strconv.Atoi(widthStr)
y, errY := strconv.Atoi(heightStr)
if errX != nil || errY != nil || x < 1 || y < 1 || x > 52 || y > 52 {
game.showError(fmt.Errorf("invalid board size (must be between 1 and 52)"))
return
}
game.sizeX = x
game.sizeY = y
game.initializeBoard()
game.redrawBoard()
game.updateGameTreeUI() // Refresh the game tree UI
},
game.window,
)
// Optionally, handle dialog close if needed
boardSizeDialog.SetOnClosed(func() {
// You can perform additional actions here when the dialog is closed
})
// Show the dialog
boardSizeDialog.Show()
}),
fyne.NewMenuItem("Pass", func() {
game.handlePass()
}),
fyne.NewMenuItem("Set Komi", func() {
game.showSetKomiDialog()
}),
fyne.NewMenuItem("Delete Node", func() {
game.deleteCurrentNode()
}),
)
// Define the "MouseMode" menu
mouseModeMenu := fyne.NewMenu("MouseMode",
fyne.NewMenuItem("Play", func() { game.setMouseMode("play") }),
fyne.NewMenuItem("Score", func() { game.setMouseMode("score") }),
fyne.NewMenuItem("Set Label", func() { game.setMouseMode("label") }),
fyne.NewMenuItem("Add Black", func() { game.setMouseMode("addBlack") }),
fyne.NewMenuItem("Add White", func() { game.setMouseMode("addWhite") }),
fyne.NewMenuItem("Add Empty", func() { game.setMouseMode("addEmpty") }),
fyne.NewMenuItem("Toggle Circle", func() { game.setMouseMode("circle") }),
fyne.NewMenuItem("Toggle Square", func() { game.setMouseMode("square") }),
fyne.NewMenuItem("Toggle Triangle", func() { game.setMouseMode("triangle") }),
fyne.NewMenuItem("Toggle X Mark", func() { game.setMouseMode("xMark") }),
)
// Define the "Engine" menu
engineMenu := fyne.NewMenu("Engine",
fyne.NewMenuItem("Settings", func() {
game.showEngineSettings()
}),
fyne.NewMenuItem("Attach Engine", func() {
game.attachEngine()
}),
fyne.NewMenuItem("Detach Engine", func() {
game.detachEngine()
}),
fyne.NewMenuItem("Start Self Play", func() {
game.gtpColor = "Both"
if game.gtpCmd == nil {
game.attachEngine()
}
game.startSelfPlay()
}),
fyne.NewMenuItem("Stop Self Play", func() {
game.stopSelfPlay()
}),
)
// Update the main menu to include the new "Engine" menu
mainMenu := fyne.NewMainMenu(
fileMenu,
gameMenu,
mouseModeMenu,
engineMenu, // Add Engine menu here
)
w.SetMainMenu(mainMenu)
// Wrap the gameTreeContainer in a ResizingContainer
resizingLabel := widget.NewLabel("Resizing")
gameTreeResizingContainer := NewResizingContainer(game.gameTreeContainer, resizingLabel)
// Layout for controls
controls := container.NewVSplit(
container.NewVBox(
game.scoringStatus,
game.commentEntry,
),
gameTreeResizingContainer, // Use the ResizingContainer here
)
controls.SetOffset(0)
// Main layout with split view
content := container.NewHSplit(
controls,
game.boardCanvas,
)
content.SetOffset(0)
w.SetContent(content)
w.Resize(fyne.NewSize(800, 600))
w.Show()
a.Run()
}
func (g *Game) deleteCurrentNode() {
if g.currentNode == g.rootNode {
// Deleting the root node, reset the game
g.initializeBoard()
g.updateGameTreeUI()
g.updateCommentTextbox()
g.redrawBoard()
} else {
parent := g.currentNode.parent
if parent != nil {
// Remove current node from its parent's children
for i, child := range parent.children {
if child == g.currentNode {
parent.children = append(parent.children[:i], parent.children[i+1:]...)
break
}
}
// Set current node to parent
g.currentNode = parent
g.updateGameTreeUI()
g.updateCommentTextbox()
g.redrawBoard()
}
}
}
func (g *Game) handleKeyEvent(event *fyne.KeyEvent) {
switch event.Name {
case fyne.KeyUp:
if g.currentNode.parent != nil {
g.setCurrentNode(g.currentNode.parent)
g.updateGameTreeUI()
g.redrawBoard()
}
case fyne.KeyDown:
if len(g.currentNode.children) > 0 {
g.setCurrentNode(g.currentNode.children[0])
g.updateGameTreeUI()
g.redrawBoard()
}
case fyne.KeyRight:
if g.currentNode.parent != nil {
siblings := g.currentNode.parent.children
for i, node := range siblings {
if node == g.currentNode && i+1 < len(siblings) {
g.setCurrentNode(siblings[i+1])
g.updateGameTreeUI()
g.redrawBoard()
break
}
}
}
case fyne.KeyLeft:
if g.currentNode.parent != nil {
siblings := g.currentNode.parent.children
for i, node := range siblings {
if node == g.currentNode && i-1 >= 0 {
g.setCurrentNode(siblings[i-1])
g.updateGameTreeUI()
g.redrawBoard()
break
}
}
}
case fyne.KeyDelete:
g.deleteCurrentNode()
case fyne.KeyP:
g.handlePass()
}
}
func (g *Game) showSetKomiDialog() {
komiEntry := widget.NewEntry()
komiEntry.SetText(fmt.Sprintf("%d", g.komi))
komiEntry.Validator = func(s string) error {
if _, err := strconv.ParseFloat(s, 64); err != nil {
return fmt.Errorf("invalid komi value")
}
return nil
}
formItems := []*widget.FormItem{
widget.NewFormItem("Komi", komiEntry),
}
komiDialog := dialog.NewForm("Set Komi", "OK", "Cancel", formItems, func(ok bool) {
if ok {
komiValue, err := strconv.Atoi(komiEntry.Text)
if err != nil {
g.showError(fmt.Errorf("invalid komi value"))
return
}
g.komi = komiValue
// Save the configuration
if err := g.saveConfig(); err != nil {
g.showError(fmt.Errorf("failed to save config: %v", err))
}
// If engine is attached, send komi command
if g.gtpCmd != nil {
_, err := g.sendGTPCommand(fmt.Sprintf("komi %d", g.komi))
if err != nil {
g.showError(err)
}
}
// Recalculate and display score if in scoring mode
if g.mouseMode == "score" {
g.calculateAndDisplayScore()
}
}
}, g.window)
komiDialog.Show()
}
func (g *Game) showEngineSettings() {
// Create input entries for settings
gtpPathEntry := widget.NewEntry()
gtpPathEntry.SetText(g.gtpPath)
gtpArgsEntry := widget.NewEntry()
gtpArgsEntry.SetText(g.gtpArgs)
gtpColorEntry := widget.NewSelect([]string{"B", "W", "Both"}, func(value string) {})
gtpColorEntry.SetSelected(g.gtpColor)
// Create the "Browse" button for GTP Path
browseButton := widget.NewButton("Browse", func() {
// Open file selector
fileDialog := dialog.NewFileOpen(func(reader fyne.URIReadCloser, err error) {
if err != nil || reader == nil {
return
}
defer reader.Close()
gtpPathEntry.SetText(reader.URI().Path())
}, g.window)
// If g.gtpPath is not a malformed path, set the initial directory
if g.gtpPath != "" {
dir := filepath.Dir(g.gtpPath)
uri := storage.NewFileURI(dir)
listableURI, err := storage.ListerForURI(uri)
if err == nil {
fileDialog.SetLocation(listableURI)
}
}
fileDialog.Show()
})
// Create form items
formItems := []*widget.FormItem{
widget.NewFormItem("GTP Path", browseButton),
widget.NewFormItem("GTP Path", gtpPathEntry),
widget.NewFormItem("GTP Arguments", gtpArgsEntry),
widget.NewFormItem("GTP Color", gtpColorEntry),
}
// Show settings dialog
settingsDialog := dialog.NewForm("Engine Settings", "OK", "Cancel", formItems, func(ok bool) {
if ok {
g.gtpPath = gtpPathEntry.Text
g.gtpArgs = gtpArgsEntry.Text
g.gtpColor = gtpColorEntry.Selected
// Save the configuration
if err := g.saveConfig(); err != nil {
g.showError(fmt.Errorf("failed to save config: %v", err))
}
}
}, g.window)
settingsDialog.Show()
}
func (g *Game) updateEngineBoardState() error {
if g.gtpCmd == nil {
return fmt.Errorf("engine is not attached")
}
// Send "clear_board" to reset the engine's board
if _, err := g.sendGTPCommand("clear_board"); err != nil {
return err
}
// Set komi in case it has changed
if _, err := g.sendGTPCommand(fmt.Sprintf("komi %d", g.komi)); err != nil {
return err
}
// Send "play" commands for each stone on the current board
for y := 0; y < g.sizeY; y++ {
for x := 0; x < g.sizeX; x++ {
stone := g.currentNode.boardState[y][x]
if stone != empty {
coord := g.clientToGTPCoords(x, y)
if _, err := g.sendGTPCommand(fmt.Sprintf("play %s %s", stone, coord)); err != nil {
return err
}
}
}
}
return nil
}
func (g *Game) startSelfPlay() {
if g.selfPlaying {
return // Already self-playing
}
g.selfPlaying = true
g.selfPlayCtx, g.selfPlayCancel = context.WithCancel(context.Background())
g.selfPlayWaitGrp.Add(1)
go func() {
defer g.selfPlayWaitGrp.Done()
player := switchPlayer(g.currentNode.player)
for {
select {
case <-g.selfPlayCtx.Done():
return
default:
// Generate move for current player
engineMove, err := g.sendGTPCommand(fmt.Sprintf("genmove %s", player))
if err != nil {
g.showError(err)
g.detachEngine()
return
}
if engineMove == "pass" || engineMove == "resign" {
// Game over
dialog.ShowInformation("Game Over", fmt.Sprintf("Player %s %s.", player, engineMove), g.window)
return
}
// Update the game state on the main thread
g.handleEngineMove(engineMove)
// Switch player
player = switchPlayer(player)
}
}
}()
}
func (g *Game) stopSelfPlay() {
if g.selfPlaying {
g.selfPlayCancel()
g.selfPlayWaitGrp.Wait()
g.selfPlaying = false
}
}
func (g *Game) attachEngine() {
// Start the GTP engine process
args := strings.Fields(g.gtpArgs)
g.gtpCmd = exec.Command(g.gtpPath, args...)
var err error
g.gtpIn, err = g.gtpCmd.StdinPipe()
if err != nil {
g.showError(err)
return
}
g.gtpOut, err = g.gtpCmd.StdoutPipe()
if err != nil {
g.showError(err)
return
}
if err := g.gtpCmd.Start(); err != nil {
g.showError(err)
return
}
g.gtpReader = bufio.NewReader(g.gtpOut)
// Initialize the engine
if err := g.initializeEngine(); err != nil {
g.showError(err)
g.detachEngine()
} else {
dialog.ShowInformation("Engine Attached", "Successfully attached to the engine.", g.window)
// Check if it's the engine's move
nextPlayer := switchPlayer(g.currentNode.player)
if g.gtpColor == "Both" {
g.startSelfPlay()
} else if g.gtpColor == nextPlayer {
engineMove, err := g.sendGTPCommand(fmt.Sprintf("genmove %s", g.gtpColor))
if err != nil {
g.showError(err)
g.detachEngine()
return
}
g.handleEngineMove(engineMove)
}
}
}
func (g *Game) detachEngine() {
g.stopSelfPlay()
if g.gtpCmd != nil {
// Kill the engine process
err := g.gtpCmd.Process.Kill()
if err != nil {
g.showError(fmt.Errorf("failed to kill engine process: %v", err))
}
// Close stdin pipe
if g.gtpIn != nil {
err := g.gtpIn.Close()
if err != nil {
g.showError(fmt.Errorf("failed to close engine stdin: %v", err))
}
g.gtpIn = nil
}
// Close stdout pipe
if g.gtpOut != nil {
err := g.gtpOut.Close()
if err != nil {
g.showError(fmt.Errorf("failed to close engine stdout: %v", err))
}
g.gtpOut = nil
}
// Wait for the process to exit
err = g.gtpCmd.Wait()
if err != nil && !strings.Contains(err.Error(), "killed") {
g.showError(fmt.Errorf("error while waiting for engine process to exit: %v", err))
}
// Set engine-related variables to nil
g.gtpCmd = nil
g.gtpReader = nil
dialog.ShowInformation("Engine Detached", "Successfully detached from the engine.", g.window)
}
}
func (g *Game) initializeEngine() error {
// Check if the required commands are supported
supportedCommands, err := g.sendGTPCommand("list_commands")
if err != nil {
return err
}
requiredCommands := []string{"boardsize", "komi", "play", "genmove"}
for _, cmd := range requiredCommands {
if !strings.Contains(supportedCommands, cmd) {
return fmt.Errorf("engine does not support required command: %s", cmd)
}
}
// Set board size
if g.sizeX == g.sizeY {
if _, err := g.sendGTPCommand(fmt.Sprintf("boardsize %d", g.sizeX)); err != nil {
return err
}
} else {
// Check if rectangular_boardsize is supported
if strings.Contains(supportedCommands, "rectangular_boardsize") {
if _, err := g.sendGTPCommand(fmt.Sprintf("rectangular_boardsize %d %d", g.sizeX, g.sizeY)); err != nil {
return err
}
} else {
return fmt.Errorf("engine does not support rectangular boards and board is not square")
}
}
// Set komi
if _, err := g.sendGTPCommand(fmt.Sprintf("komi %d", g.komi)); err != nil {
return err
}
// Send the current board state to the engine
for y := 0; y < g.sizeY; y++ {
for x := 0; x < g.sizeX; x++ {
stone := g.currentNode.boardState[y][x]
if stone != empty {
coord := g.clientToGTPCoords(x, y)
if _, err := g.sendGTPCommand(fmt.Sprintf("play %s %s", stone, coord)); err != nil {
return err
}
}
}
}
return nil
}
func (g *Game) sendGTPCommand(command string) (string, error) {
if g.gtpIn == nil || g.gtpReader == nil {
return "", fmt.Errorf("engine is not attached")
}
// Send command
_, err := g.gtpIn.Write([]byte(command + "\n"))
if err != nil {
return "", err
}
fmt.Println("GTP command sent:\n" + command)
// Read response
var responseLines []string
for {
line, err := g.gtpReader.ReadString('\n')
if err != nil {
return "", err
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
if line[0] == '=' || line[0] == '?' {
// Response start
if len(line) > 1 {
responseLines = append(responseLines, strings.TrimSpace(line[1:]))
}
// Read any additional output lines
for {
nextLine, err := g.gtpReader.ReadString('\n')
if err != nil {
return "", err
}
nextLine = strings.TrimSpace(nextLine)
if nextLine == "" {
break
}
responseLines = append(responseLines, nextLine)
}
response := strings.Join(responseLines, "\n")
fmt.Println("GTP response recieved:\n" + response)
if line[0] == '?' {
return response, fmt.Errorf("error from engine: %s", strings.Join(responseLines, "\n"))
}
return response, nil
}
}
}
// GTP coordinates use letters A-H, J-T (I is skipped), and numbers from 1 upwards
func (g *Game) clientToGTPCoords(x, y int) string {
// Convert x to letter