-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDotsAndBoxesExamen_DeSmetTim.jl
1607 lines (1514 loc) · 44 KB
/
DotsAndBoxesExamen_DeSmetTim.jl
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
#######################<---Dots And Boxes--->#######################
"""
1 7777777 555555
111 777 55
11 777 555555
11 777 5555
111 777 555555
Created by: Tim De Smet, Tomas Oostvogels
Last edit: 10/06/2021 @0850
--------------------------------------------------------------------
IDEAS
- Startup menu: choose between which mode, REPL or GameZero
- Normal mode, level of difficulty
- (Then cooler modes: square, triangle, hexagon, ..., easy/mediocre/hard..., choice mode (check if possible))
- Timer
- Output of score/game overview to text file
- Cool visuals, interface design
- Ctrl-z undo move -> Save moves to a dictionary? + print next to grid the history of moves?
- Ctrl-s save game to file
"""
#using BenchmarkTools
#using CPUTime
#using GameZero
#using Colors
#using CSV
#using DataFrames
using DelimitedFiles # Part of standard library, way faster than combo csv/dataframes
global SETTINGS = Dict() # Settings to import from csv file on startup
global BUFFER # Keyboard input handling
global const GRID = Array{Int}
struct ANSIColor
red::Function
bright_red::Function
green::Function
blue::Function
bright_blue::Function
yellow::Function
magenta::Function
cyan::Function
white::Function
black::Function
rgb::Function
ANSIColor() = new(
c -> "\e[31m$c\e[0m", # Red
c -> "\e[31;1m$c\e[0m", # Bright red
c -> "\e[32m$c\e[0m", # Green
c -> "\e[34m$c\e[0m", # Blue
c -> "\e[34;1m$c\e[0m", # Bright blue
c -> "\e[33m$c\e[0m", # Yellow
c -> "\e[35m$c\e[0m", # Magenta
c -> "\e[36m$c\e[0m", # Cyan
c -> "\e[37m$c\e[0m", # White
c -> "\e[40m$c\e[0m", # Black
c -> "\x1b[38;2;55;223;206m" #test RGB
)
end
global const ANSI = ANSIColor()
# Keyboard Input
global const KEY_ESC = "ESC"
global const KEY_ENTER = "Enter"
global const KEY_Q = "q"
global const KEY_Z = "z"
global const KEY_S = "s"
global const KEY_D = "d"
global const KEY_R = "r"
global const esc_codes = Dict([
"[A" => "Up",
"[B" => "Down",
"[C" => "Right",
"[D" => "Left",
"[F" => "End",
"[H" => "Pos1",
"[2~" => "Ins",
"[3~" => "Del",
"[5~" => "PgUp",
"[6~" => "PdDown",
"OP" => "F1",
"[[A" => "F1",
"OQ" => "F2",
"[[B" => "F2",
"OR" => "F3",
"[[C" => "F3",
"OS" => "F4",
"[[D" => "F4",
"[15~" => "F5",
"[[E" => "F5",
"[17~" => "F6",
"[[F" => "F6",
"[18~" => "F7",
"[[G" => "F7",
"[19~" => "F8",
"[[H" => "F8",
"[20~" => "F9",
"[[I" => "F9",
"[21~" => "F10",
"[[J" => "F10",
"[23~" => "F11",
"[[K" => "F11",
"[24~" => "F12",
"[[L" => "F12",
"\e" => "ESC"
])
global const ctrl_codes = Dict([
0 => "Ctrl-2",
1 => "Ctrl-A",
2 => "Ctrl-B",
3 => "Ctrl-C",
4 => "Ctrl-D",
5 => "Ctrl-E",
6 => "Ctrl-F",
7 => "Ctrl-G",
8 => "Backspace",
9 => "Tab",
10 => "Ctrl-J",
11 => "Ctrl-K",
12 => "Ctrl-L",
13 => "Enter",
14 => "Ctrl-N",
15 => "Ctrl-O",
16 => "Ctrl-P",
17 => "Ctrl-Q",
18 => "Ctrl-R",
19 => "Ctrl-S",
20 => "Ctrl-T",
21 => "Ctrl-U",
22 => "Ctrl-V",
23 => "Ctrl-W",
24 => "Ctrl-X",
25 => "Ctrl-Y",
26 => "Ctrl-Z",
27 => "Ctrl-3",
29 => "Ctrl-5",
30 => "Ctrl-6",
31 => "Ctrl-7"
])
# Settings Handling
function converttoarray(sarr)
sarr = sarr[2:end-1]
sarr = split(sarr, ",")
sarr = parse.(Int, sarr)
return sarr
end
function ImportSettings()
d = Dict()
filename = joinpath(@__DIR__, "Settings.dnb")
if isfile(filename)
df = readdlm(filename, ':')
for i in 1:size(df, 1)
if !(df[i, 1] in keys(d)) # todo: haskey()
d[df[i,1]] = df[i, 2]
end
end
return d
else
CreateSettings(filename)
df = readdlm(filename, ':')
for i in 1:size(df, 1)
if !(df[i, 1] in keys(d))
d[df[i,1]] = df[i, 2]
end
end
return d
end
end
function updateSettings(updateSett::Array)
filename = joinpath(@__DIR__, "Settings.dnb")
s = sortslices(updateSett, dims=1)
open(filename, "w") do io
writedlm(io, s, ':')
end
end
function allowedSettings()
# TODO
# gridwidth, gridheight >= 2
# player one or two
# readline for char/strings
# array: startco
# spacingx: name has to be shorter than distance!!
# if some setting is not possible: show it to the player
end
function CreateSettings(filename::String)
BaseSettings = Dict([
"GRID_WIDTH" => 4,
"GRID_HEIGHT" => 4,
"PLAYERSIGN1" => "Player1",
"PLAYERSIGN2" => "Player2",
"PLAYSFIRST" => 1, # Put one or two here (1 corresponds to playersign 1)
"STARTCO" => [1, 2],
"SPACINGX" => 18,
"GRIDPOINT" => "+",
"HORZLINE" => "-",
"VERTLINE" => "|",
"CURSORCHAR" => '0',
"BOT_ON" => false
])
Setting = []
Value = []
for key in keys(BaseSettings)
push!(Setting, key)
push!(Value, BaseSettings[key])
end
# Sort array? -> yes
s = sortslices([Setting Value], dims=1)
open(filename, "w") do io
writedlm(io, s, ':')
end
end
function fixsettings()
global SETTINGS
function converttochar(s)
if isa(s, Int) || isa(s, Float64)
s = string(s)
end
s = collect(s)
return s[1]
end
SETTINGS["CURSORCHAR"] = converttochar(SETTINGS["CURSORCHAR"])
SETTINGS["STARTCO"] = converttoarray(SETTINGS["STARTCO"])
SETTINGS["GRIDPOINT"] = string(SETTINGS["GRIDPOINT"])
end
# Keyboard Input
function Initiate_Keyboard_Input()
# https://discourse.julialang.org/t/wait-for-a-keypress/20218/4
# https://docs.julialang.org/en/v1/manual/calling-c-and-fortran-code/#Calling-C-and-Fortran-Code
# https://stackoverflow.com/questions/56888266/how-to-read-keyboard-inputs-at-every-keystroke-in-julia
global BUFFER
ccall(:jl_tty_set_mode, Int32, (Ptr{Cvoid}, Int32), stdin.handle, true)
BUFFER = Channel{Char}(100)
@async while true
put!(BUFFER, read(stdin, Char))
end
end
function readinput()
global BUFFER
global ctrl_codes
global esc_codes
if isready(BUFFER)
s = take!(BUFFER)
if s == '\e' # Escape
esc_s = ""
while isempty(esc_s) || !(esc_s[end] in ['A','B','C','D','F','H','P','Q','R','S','~', '\e'])
esc_s *= take!(BUFFER)
end
if haskey(esc_codes, esc_s)
return esc_codes[esc_s]
end
elseif Int(s) in 0:31
return ctrl_codes[Int(s)]
else
return string(s)
end
end
end
# REPL Graphics Stuff
# Cursor
mutable struct CursorStruct
x::Int
y::Int
CursorStruct(x, y) = new(x, y)
end
hidecursor() = print("\e[?25l") # Or \x1b[?25l
showcursor() = println("\e[?25h")
function clearscreen()
# Move cursor to beginning, then clear to end then again begin
#println("\x1b[42m")
println("\33[H")
println("\33[J")
println("\33[H")
hidecursor()
end
########<---- Game Logic and stuff ---->#############
mutable struct GameState
gw::Int # Grid width
gh::Int # Grid height
grid::GRID # Grid itself
gameover::Bool
player::Int # Player turn, 1 or 2
score::Array # Score[playerone, playertwo]
bot::Int
GameState( gw = SETTINGS["GRID_WIDTH"],
gh = SETTINGS["GRID_HEIGHT"],
grid = resetGrid(gw, gh),
gameover = false,
player = SETTINGS["PLAYSFIRST"],
score = [0, 0],
bot = 0
) = new(gw, gh, grid, gameover, player, score, bot)
end
function resetGrid(gw::Int, gh::Int)
return zeros(Int, 2*gh-1, 2*gw-1)
end
function InitiateGrid(grid::GRID)
for y in 1:size(grid, 1)
if y%2 != 0
for x in 1:size(grid, 2)
if x%2 != 0
grid[y, x] = -1 # Dots
end
end
else
for x in 1:size(grid, 2)
if x%2 == 0
grid[y, x] = -2 # Midpoints (to be used by algorithm/bot)
end
end
end
end
end
function botSettings(state::GameState)
global SETTINGS
if SETTINGS["BOT_ON"]
if SETTINGS["PLAYERSIGN1"] == "BOT"
state.bot = 1
elseif SETTINGS["PLAYERSIGN2"] == "BOT"
state.bot = 2
end
else
state.bot = 0
end
end
function CellsAround(x,y)
Arr = [[x, y-1],
[x+1, y],
[x, y+1],
[x-1, y]
]
return Arr
end
function checkAround(grid::GRID)
around = 0
for y in 1:size(grid, 1)
for x in 1:size(grid, 2)
around = 0
if grid[y, x] == -2
# Up-Down Left-Right
for dy in -1:2:1
if !(grid[y+dy, x] == 0 || grid[y+dy, x] == 8)
around+=1
end
end
for dx in -1:2:1
if !(grid[y, x+dx] == 0 || grid[y, x+dx] == 8)
around+=1
end
end
if around == 3
for dy in -1:2:1
if grid[y+dy, x] == 0
grid[y+dy, x] = 8 # Randomly chosen, >=5
end
end
for dx in -1:2:1
if grid[y, x+dx] == 0
grid[y, x+dx] = 8
end
end
elseif around == 4
for dy in -1:2:1
if grid[y+dy, x] == 6
grid[y, x] = 20
# grid[y+dy, x] = 2 do not change yet! See next for loop
elseif grid[y+dy, x] == 7
grid[y, x] = 10
# grid[y+dy, x] = 1 do not change yet!
end
end
for dx in -1:2:1
if grid[y, x+dx] == 6
grid[y, x] = 20
# grid[y, x+dx] = 2 do not change yet!
elseif grid[y, x+dx] == 7
grid[y, x] = 10
# grid[y, x+dx] = 1 do not change yet!
end
end
end
end
end
end
# Fix the lines taken, give them to the player who took them
for y in 1:size(grid, 1)
for x in 1:size(grid, 2)
if grid[y, x] == 10
for dy in -1:2:1
if grid[y+dy, x] == 7
grid[y+dy, x] = 1 # Player one
end
end
for dx in -1:2:1
if grid[y, x+dx] == 7
grid[y, x+dx] = 1
end
end
elseif grid[y, x] == 20
for dy in -1:2:1
if grid[y+dy, x] == 6
grid[y+dy, x] = 2 # Player two
end
end
for dx in -1:2:1
if grid[y, x+dx] == 6
grid[y, x+dx] = 2
end
end
end
end
end
return grid # Only needed when minimax algorithm needs this function
end
# Give box to the player who took it
function Difference(grid::GRID, oldgrid::GRID)
change = oldgrid - grid # Pointwise
for y in 1:size(grid, 1)
for x in 1:size(grid, 2)
if change[y, x] > 5
grid[y, x] = change[y, x]
end
end
end
checkAround(grid)
end
function changeTurns(state::GameState, diffscore::Array)
for i in diffscore
if i != 0
return false
end
end
return true
end
###
function score(checkgrid::GRID)
scores = [0, 0]
for y in 2:2:size(checkgrid, 1)
for x in 2:2:size(checkgrid, 2)
if checkgrid[y, x] == 10
scores[1] += 1
elseif checkgrid[y, x] == 20
scores[2] += 1
end
end
end
return scores
end
function available(checkgrid::GRID)
availablemoves = []
for y in 1:size(checkgrid, 1)
for x in 1:size(checkgrid, 2)
if checkgrid[y, x] == 0 || checkgrid[y, x] == 8
push!(availablemoves, [y, x])
end
end
end
return availablemoves
end
function checkWinner(checkgrid::GRID)
scores = score(checkgrid)
if scores[1] > scores[2]
return 1
elseif scores[1] < scores[2]
return 2
else
return 0
end
end
##### BOT stuff #####
#### Everything chains
function CleanDict(dict)
for i in keys(dict)
if dict[i] == []
delete!(dict,i)
end
end
end
function ChainsInGame(grid::GRID)
Chains = Dict([]) # To keep track of chains
History = [] # To keep track of places checked
function InGrid(co)
if co[1] > 0 && co[2] > 0 && co[1] <= size(grid, 2) && co[2] <= size(grid, 1)
return true
else
return false
end
end
function IsPartOfChain(co)
# Other method to look around
x = co[1] # For demonstrative purposes
y = co[2]
CellsAround = [
(x, y-1),
(x+1, y),
(x, y+1),
(x-1, y)]
n_around = 0
for cell in CellsAround
if InGrid(cell)
if grid[cell[2],cell[1]] == 1 || grid[cell[2],cell[1]] == 2
n_around += 1
end
end
end
if n_around == 2 || n_around == 3
return true
else
return false
end
end
function Around(co, startco)
x = co[1] # For demonstrative purposes
y = co[2]
# Array of arrays (tuples are immutable)
CellsAround = [
[x,y],
[x, y-1],
[x+1, y],
[x, y+1],
[x-1, y]]
for cell in CellsAround
if InGrid(cell)
if grid[cell[2],cell[1]] == 0 || grid[cell[2],cell[1]] == 8 || grid[cell[2],cell[1]] == -2
if cell == CellsAround[1]
if !IsPartOfChain(cell)
push!(History,cell)
continue
elseif !(cell in History)
push!(History,cell)
end
elseif cell == CellsAround[2]
cell[2] -= 1 # Move up
if !InGrid(cell)
continue
else
if !IsPartOfChain(cell)
push!(History,cell)
continue
elseif !(cell in History)
push!(Chains["$(startco)"],cell) # Tie current coordinate to array in dictionary - make chain of coordinates
end
if !(cell in History)
push!(History,cell)
Around(cell, startco)
end
end
elseif cell == CellsAround[3]
cell[1] += 1
if !InGrid(cell)
continue
else
if !IsPartOfChain(cell)
push!(History,cell)
continue
elseif !(cell in History)
push!(Chains["$(startco)"],cell)
end
if !(cell in History)
push!(History,cell)
Around(cell, startco)
end
end
elseif cell == CellsAround[4]
cell[2] += 1
if !InGrid(cell)
continue
else
if !IsPartOfChain(cell)
push!(History,cell)
continue
elseif !(cell in History)
push!(Chains["$(startco)"],cell)
end
if !(cell in History)
push!(History,cell)
Around(cell, startco)
end
end
elseif cell == CellsAround[5]
cell[1] -= 1
if !InGrid(cell)
continue
else
if !IsPartOfChain(cell)
push!(History,cell)
continue
elseif !(cell in History)
push!(Chains["$(startco)"],cell)
end
if !(cell in History)
push!(History,cell)
Around(cell, startco)
end
end
end
end
end
end
end
for y in 1:size(grid, 1)
for x in 1:size(grid, 2)
if grid[y,x] == -2 && IsPartOfChain([x,y]) && !([x,y] in History)
Chains["$([x,y])"] = []
Around([x,y], [x,y])
end
end
end
return Chains # return dictionary of current chains found (only >=2)
end
function CheckChains(Chains::Dict)
n_LongChains = 0
Lengths = []
maxLength = 20 # todo length fix
for i in 1:maxLength # todo length fix
push!(Lengths,i)
end
LengthChainDict = Dict([(key,[]) for key in Lengths])
for i in keys(Chains)
if length(Chains[i]) in 1:maxLength-1
push!(LengthChainDict[length(Chains[i])+1],i)
end
end
for i in keys(LengthChainDict)
if i >= 3
n_LongChains += length(LengthChainDict[i])
end
end
CleanDict(LengthChainDict)
return n_LongChains,LengthChainDict
end
function CompleteableChain(state::GameState,Chains::Dict)
completeablechainsArr = []
Almost = [] # dont open this chain
CompletableBox =[]
for i in keys(Chains)
n_around = 0
start = converttoarray(i)
for k in CellsAround(start[1],start[2])
if state.grid[k[2],k[1]] == 1 || state.grid[k[2],k[1]] == 2
n_around += 1
end
end
for j in Chains[i]
for k in CellsAround(j[1],j[2])
if state.grid[k[2],k[1]] == 1 || state.grid[k[2],k[1]] == 2
n_around += 1
end
end
end
n_around
if n_around >= (length(Chains[i])+1)*2+1 && n_around > 3 # completeable criterium
push!(completeablechainsArr, i)
end
if n_around == (length(Chains[i])+1)*2 && n_around >= 6 # dont open this, otherwise loser
push!(Almost, i)
end
if n_around == 3 && length(Chains[i]) == 0
push!(CompletableBox,i)
end
end
return [completeablechainsArr,Almost, CompletableBox]
end
function CompleteChain(state::GameState,Chains::Dict, Chainranks::Array)
Completable = Chainranks[1]
element = 0
for i in Completable
element+=1
if length(Chains[i]) == 1
deleteat!(Completable,element)
insert!(Completable,1, i)
end
end
Almost = Chainranks[2]
CompletableBox = Chainranks[3]
availablemoves = available(state.grid)
if length(CompletableBox) > 0 # alone standing box -> take it
for i in CompletableBox
cell = converttoarray(i)
for j in CellsAround(cell[2], cell[1])
if j in availablemoves
state.grid[j[1],j[2]] = state.player
state.grid[cell[2],cell[1]] = state.player*10
end
end
end
end
if length(Completable) == 0
@show return false
end
if length(Almost) == 0
for i in Completable
cell = converttoarray(i)
for j in CellsAround(cell[2], cell[1])
if j in availablemoves
state.grid[j[1],j[2]] = state.player
state.grid[cell[2],cell[1]] = state.player*10
end
end
for j in Chains[i]
for k in CellsAround(j[2], j[1])
if k in availablemoves
state.grid[k[1],k[2]] = state.player
state.grid[j[2],j[1]] = state.player*10
end
end
end
end
end
if length(Almost) != 0 && length(Completable) > 1
for i in Completable[1:end-1]
cell = converttoarray(i)
for j in CellsAround(cell[2], cell[1])
if j in availablemoves
state.grid[j[1],j[2]] = state.player
state.grid[cell[2],cell[1]] = state.player*10
end
end
for j in Chains[i]
for k in CellsAround(j[2], j[1])
if k in availablemoves
state.grid[k[1],k[2]] = state.player
state.grid[j[2],j[1]] = state.player*10
end
end
end
end
elseif length(Almost) != 0
for i in Completable
cell = converttoarray(i)
for j in CellsAround(cell[2], cell[1])
if j in availablemoves
state.grid[j[1],j[2]] = state.player
state.grid[cell[2],cell[1]] = state.player*10
end
end
for j in Chains[i]
for k in CellsAround(j[2], j[1])
if k in availablemoves
state.grid[k[1],k[2]] = state.player
state.grid[j[2],j[1]] = state.player*10
end
end
end
if length(Chains[i]) > 1
zeroCo = (Chains[i][end-1] + Chains[i][end]).÷2
state.grid[zeroCo[2],zeroCo[1]] = 0
state.grid[Chains[i][end-1][2], Chains[i][end-1][1]] = -2
state.grid[Chains[i][end][2], Chains[i][end][1]] = -2
if state.player == 1
state.player = 2
elseif state.player == 2
state.player = 1
end
else
zeroCo = (cell + Chains[i][end]).÷2
state.grid[zeroCo[2],zeroCo[1]] = 0
state.grid[cell[2], cell[1]] = -2
state.grid[Chains[i][end][2], Chains[i][end][1]] = -2
end
end
end
@show return true
end
function AllChains(LengthChainDict::Dict, Chains::Dict, state::GameState, Chainranks::Array)
counter = 0
for i in keys(LengthChainDict)
for j in LengthChainDict[i]
counter += i # key is length of element
end
end
counter += length(Chainranks[3]) #completeable boxes
counter += state.score[1] + state.score[2] #completed boxes
if counter >= (state.gh-1)*(state.gw-1) # starting criterium for this bot
return true
else
return false
end
end
##### Everything minimax #####
# Minimax specific -> TODO
global initialplayertop = 0
global counter = 0
function statEval(checkstate::GameState)
global initialplayertop
# Factor Score (amount of boxes)
scores = score(checkstate.grid)
otherplayer = 0
if initialplayertop == 1
otherplayer = 2
else
otherplayer = 1
end
factorscore = scores[initialplayertop] - scores[otherplayer]
# Factor Chains (amount of chains) -> todo
# Sum dots + number of chains = even -> player 1 controls
"""
Chains = ChainsInGame(checkstate.grid)
checkChains = CheckChains(Chains)
n_longchains = checkChains[1]
factorchains = 0
if checkstate.bot == 1 # the bot
if (n_longchains + checkstate.gw*checkstate.gh)%2 == 0
# Player one has control
factorchains += 3
else
# Other player has control
factorchains -= 3
end
else
if (n_longchains + checkstate.gw*checkstate.gh)%2 == 0
end
"""
return factorscore
end
function minimax(checkstate::GameState, depth::Int, isMax::Bool, prevgrid::GRID, prevplayer::Int)
global counter
availableMoves = available(checkstate.grid)
if depth == 0 || length(availableMoves) == 0 # don't search any further, game is over
counter += 1
return statEval(checkstate)
elseif isMax
# Maximizing player
maxEval = -Inf
currEval = -Inf
initialplayer1 = deepcopy(checkstate.player) # Bot
initialgrid = deepcopy(checkstate.grid)
for move in eachindex(availableMoves)
checkstate.grid[availableMoves[move][1], availableMoves[move][2]] = checkstate.player
Difference(checkstate.grid, prevgrid)
diffscore = score(checkstate.grid) - score(prevgrid)
if changeTurns(checkstate, diffscore)
prevplayer = deepcopy(checkstate.player)
if checkstate.player == 1
checkstate.player = 2
elseif checkstate.player == 2
checkstate.player = 1
end
prevgrid = deepcopy(checkstate.grid)
currEval = minimax(checkstate, depth-1, false, prevgrid, prevplayer)
else
prevgrid = deepcopy(checkstate.grid)
currEval = minimax(checkstate, depth-1, true, prevgrid, prevplayer)
end
checkstate.grid = deepcopy(initialgrid) # Undo Move
prevgrid = deepcopy(initialgrid)
checkstate.player = deepcopy(initialplayer1)
maxEval = Int(max(maxEval, currEval))
#@show maxEval
end
return maxEval
else
# Minimizing player
minEval = Inf
currEval = Inf
initialplayer1 = deepcopy(checkstate.player) # Bot
initialgrid = deepcopy(checkstate.grid)
k = deepcopy(checkstate.player)
for move in eachindex(availableMoves)
checkstate.grid[availableMoves[move][1], availableMoves[move][2]] = checkstate.player
Difference(checkstate.grid, prevgrid)
diffscore = score(checkstate.grid) - score(prevgrid)
if changeTurns(checkstate, diffscore)
prevplayer = deepcopy(checkstate.player)
if checkstate.player == 1
checkstate.player = 2
elseif checkstate.player == 2
checkstate.player = 1
end
prevgrid = deepcopy(checkstate.grid)
currEval = minimax(checkstate, depth-1, true, prevgrid, prevplayer)
else
prevgrid = deepcopy(checkstate.grid)
currEval = minimax(checkstate, depth-1, false, prevgrid, prevplayer)
end
checkstate.grid = deepcopy(initialgrid) # Undo Move
prevgrid = deepcopy(initialgrid)
checkstate.player = deepcopy(initialplayer1)
minEval = Int(min(minEval, currEval))
#@show minEval
end
return minEval
end
end
function minimaxMove(checkstate::GameState)
global initialplayertop
bestScore = -Inf
bestMove = []
currscore = -Inf
initialplayertop = deepcopy(checkstate.player) # Bot
initialgridtop = deepcopy(checkstate.grid)
prevplayer = initialplayertop
prevgrid = deepcopy(checkstate.grid)
availableMoves = available(checkstate.grid)
#@show length(availableMoves)
for move in eachindex(availableMoves)
#@show "newstartmove"
checkstate.grid[availableMoves[move][1], availableMoves[move][2]] = checkstate.player # Bot makes initial move
# todo: code refactoring
Difference(checkstate.grid, prevgrid)
diffscore = score(checkstate.grid) - score(prevgrid)
if changeTurns(checkstate, diffscore)
if checkstate.player == 1
checkstate.player = 2
elseif checkstate.player == 2
checkstate.player = 1
end
end
prevgrid = deepcopy(checkstate.grid)
if checkstate.player == prevplayer
currscore = minimax(checkstate, 3, true, prevgrid, prevplayer) # than it is still the bots' turn
else
currscore = minimax(checkstate, 3, false, prevgrid, prevplayer)
end
checkstate.grid = deepcopy(initialgridtop) # Undo move
prevgrid = deepcopy(initialgridtop)
checkstate.player = deepcopy(initialplayertop) # Again, bot to start
if currscore > bestScore
bestScore = currscore
bestMove = availableMoves[move]
end
#@show bestMove
#@show bestScore
end
return bestMove
end
function BOT1(state::GameState)
global counter
counter = 0
checkstate = deepcopy(state)
move = minimaxMove(checkstate)
state.grid[move[1], move[2]] = state.player
end
function BOT2(state::GameState)
Chains = ChainsInGame(state.grid)
checkChains = CheckChains(Chains)
n_longchains = checkChains[1] #number of long chains
LengthChainDict = checkChains[2] #Chains sorted by length
Chainranks = CompleteableChain(state, Chains) #[Completable Chains, Almost Completable chains, Completable boxes]
if AllChains(LengthChainDict,Chains,state, Chainranks)
println("AllChains")
if CompleteChain(state,Chains, Chainranks)
return true #bot made move
else
return false
end
else
println("NotAllChains")
return false
end
end
# Output Handling
function savegame(state::GameState)
# TODO: write board to file
# Other ideas:
filename = joinpath(@__DIR__, "GameHistory.dnb")
if isfile(filename)
df = readdlm(filename, ':')
else
#CreateSettings(filename)
end
end