-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathchessba.sh
executable file
·1846 lines (1769 loc) · 49.5 KB
/
chessba.sh
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
#!/usr/bin/env bash
#
# Chess Bash
# a simple chess game written in an inappropriate language :)
#
# Copyright (c) 2015 by Bernhard Heinloth <[email protected]>
# Copyright (c) 2021 by Igor Le Masson
#
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Bash version test
if ((BASH_VERSINFO[0] < 4)); then
echo "Sorry, it is required at least bash-4.0 to run $0." >&2
exit 1
fi
# Default values
strength=3
namePlayerA="Player"
namePlayerB="AI"
color=true
colorPlayerA=4
colorPlayerB=1
colorHover=4
colorHelper=true
colorFill=true
ascii=false
warnings=false
computer=-1
mouse=true
guiconfig=false
cursor=true
sleep=2
cache=""
cachecompress=false
unicodelabels=true
port=12433
# internal values
timestamp=$( date +%s%N )
fifopipeprefix="/tmp/chessbashpipe"
selectedX=-1
selectedY=-1
selectedNewX=-1
selectedNewY=-1
remote=0
remoteip=127.0.0.1
remotedelay=0.1
remotekeyword="remote"
aikeyword="ai"
aiPlayerA="Marvin"
aiPlayerB="R2D2"
A=-1
B=1
originY=4
originX=7
hoverX=0
hoverY=0
hoverInit=false
labelX=-2
labelY=9
type stty >/dev/null 2>&1 && useStty=true || useStty=false
# version build number
build="0.41"
# Choose unused color for hover
while (( colorHover == colorPlayerA || colorHover == colorPlayerB )) ; do
(( colorHover++ ))
done
# Check Unicode availbility
# We do this using a trick: printing a special zero-length unicode char (http://en.wikipedia.org/wiki/Combining_Grapheme_Joiner) and retrieving the cursor position afterwards.
# If the cursor position is at beginning, the terminal knows unicode. Otherwise it has printed some replacement character.
echo -en "\e7\e[s\e[H\r\xcd\x8f\e[6n" && read -r -sN6 -t0.1 x
if [[ "${x:4:1}" == "1" ]] ; then
ascii=false
unicodelabels=true
else
ascii=true
unicodelabels=false
fi
echo -e "\e[u\e8\e[2K\r\e[0m\nWelcome to \e[1mChessBa.sh\e[0m - a Chess game written in Bash \e[2mby Bernhard Heinloth, 2015\e[0m\n"
# Print version information
function version() {
echo ChessBash $build
}
# Wait for key press
# no params/return
function anyKey(){
$useStty && stty echo
echo -e "\e[2m(Press any key to continue)\e[0m"
read -r -sN1
$useStty && stty -echo
}
# Error message, p.a. on bugs
# Params:
# $1 message
# (no return value, exit game)
function error() {
if $color ; then
echo -e "\e[0;1;41m $1 \e[0m\n\e[3m(Script exit)\e[0m" >&2
else
echo -e "\e[0;1;7m $1 \e[0m\n\e[3m(Script exit)\e[0m" >&2
fi
anyKey
exit 1
}
# Check prerequisits (additional executables)
# taken from an old script of mine (undertaker-tailor)
# Params:
# $1 name of executable
function require() {
type "$1" >/dev/null 2>&1 ||
{
echo "This requires $1 but it is not available on your system. Aborting." >&2
exit 1
}
}
# Validate a number string
# Params:
# $1 String with number
# Return 0 if valid, 1 otherwise
function validNumber() {
if [[ "$1" =~ ^[0-9]+$ ]] ; then
return 0
else
return 1
fi
}
# Validate a port string
# Must be non privileged (>1023)
# Params:
# $1 String with port number
# Return 0 if valid, 1 otherwise
function validPort() {
if validNumber "$1" && (( 1 < 65536 && 1 > 1023 )) ; then
return 0
else
return 1
fi
}
# Validate an IP v4 or v6 address
# source: http://stackoverflow.com/a/9221063
# Params:
# $1 IP address to validate
# Return 0 if valid, 1 otherwise
function validIP() {
if [[ "$1" =~ ^(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))))$ ]] ; then
return 0
else
return 1
fi
}
# Named ANSI colors
declare -a colors=( "black" "red" "green" "yellow" "blue" "magenta" "cyan" "white" )
# Retrieve ANSI color code from string
# Black and white are ignored!
# Params:
# $1 Color string
# Return Color code or 0 if not a valid
function getColor() {
local c
for (( c=1; c<7; c++ )) ; do
local v=${colors[$c]:0:1}
local i=${1:0:1}
if [[ "${v^^}" == "${i^^}" || "$c" -eq "$i" ]] ; then
return "$c"
fi
done
return 0
}
# Check if ai player
# Params:
# $1 player
# Return status code 0 if ai player
function isAI() {
if (( $1 < 0 )) ; then
if [[ "${namePlayerA,,}" == "${aikeyword,,}" ]] ; then
return 0
else
return 1
fi
else
if [[ "${namePlayerB,,}" == "${aikeyword,,}" ]] ; then
return 0
else
return 1
fi
fi
}
# Help message
# Writes text to stdout
function help {
echo
echo -e "\e[1mChess Bash\e[0m - a small chess game written in Bash"
echo
echo -e "\e[4mUsage:\e[0m $0 [options]"
echo
echo -e "\e[4mConfiguration options\e[0m"
echo " -g Use a graphical user interface (instead of more parameters)"
echo
echo -e "\e[4mGame options\e[0m"
echo -e " -a \e[2mNAME\e[0m Name of first player, \"$aikeyword\" for computer controlled or the"
echo " IP address of remote player (Default: $namePlayerA)"
echo -e " -b \e[2mNAME\e[0m Name of second player, \"$aikeyword\" for computer controlled or"
echo -e " \"$remotekeyword\" for another player (Default: \e[2m$namePlayerB\e[0m)"
echo -e " -s \e[2mNUMBER\e[0m Strength of computer (Default: \e[2m$strength\e[0m)"
echo -e " -w \e[2mNUMBER\e[0m Waiting time for messages in seconds (Default: \e[2m$sleep\e[0m)"
echo
echo -e "\e[4mNetwork settings for remote gaming\e[0m"
echo -e " -P \e[2mNUMBER\e[0m Set port for network connection (Default: \e[2m$port\e[0m)"
echo -e "\e[1;33mAttention:\e[0;33m On a network game the person controlling the first player / A"
echo -e "(using \"\e[2;33m-b $remotekeyword\e[0;33m\" as parameter) must start the game first!\e[0m"
echo
echo -e "\e[4mCache management\e[0m"
echo -e " -c \e[2mFILE\e[0m Makes cache permanent - load and store calculated moves"
echo " -z Compress cache file (only to be used with -c, requires gzip)"
echo -e " -t \e[2mSTEPS\e[0m Exit after STEPS ai turns and print time (for benchmark)"
echo
echo -e "\e[4mOutput control\e[0m"
echo " -h This help message"
echo " -v Version information"
echo " -V Disable VT100 cursor movement (for partial output changes)"
echo " -M Disable terminal mouse support"
echo " -i Enable verbose input warning messages"
echo " -l Board labels in ASCII (instead of Unicode)"
echo " -p Plain ascii output (instead of cute unicode figures)"
echo " This implies ASCII board labels (\"-l\")"
echo " -d Disable colors (only black/white output)"
echo -e " \e[4mFollowing options will have no effect while colors are disabled:\e[0m"
echo -e " -A \e[2mNUMBER\e[0m Color code of first player (Default: \e[2m$colorPlayerA\e[0m)"
echo -e " -B \e[2mNUMBER\e[0m Color code of second player (Default: \e[2m$colorPlayerB\e[0m)"
echo " -n Use normal (instead of color filled) figures"
echo " -m Disable color marking of possible moves"
echo
echo -e "\e[2m(Default values/options should suit most systems - only if you encounter a"
echo -e "problem you should have a further investigation of these script parameters."
echo -e "Or just switch to a real chess game with great graphics and ai! ;)\e[0m"
echo
}
# Parse command line arguments
while getopts ":a:A:b:B:c:P:s:t:w:dghilmMnpvVz" options; do
case $options in
a ) if [[ -z "$OPTARG" ]] ; then
echo "No valid name for first player specified!" >&2
exit 1
# IPv4 && IPv6 validation, source: http://stackoverflow.com/a/9221063
elif validIP "$OPTARG" ; then
remote=-1
remoteip="$OPTARG"
else
namePlayerA="$OPTARG"
fi
;;
A ) if ! getColor "$OPTARG" ; then
colorPlayerA=$?
else
echo "'$OPTARG' is not a valid color!" >&2
exit 1
fi
;;
b ) if [[ -z "$OPTARG" ]] ; then
echo "No valid name for second player specified!" >&2
exit 1
elif [[ "${OPTARG,,}" == "$remotekeyword" ]] ; then
remote=1
else
namePlayerB="$OPTARG"
fi
;;
B ) if ! getColor "$OPTARG" ; then
colorPlayerB=$?
else
echo "'$OPTARG' is not a valid color!" >&2
exit 1
fi
;;
s ) if validNumber "$OPTARG" ; then
strength=$OPTARG
else
echo "'$OPTARG' is not a valid strength!" >&2
exit 1
fi
;;
P ) if validPort "$OPTARG" ; then
port=$OPTARG
else
echo "'$OPTARG' is not a valid gaming port!" >&2
exit 1
fi
;;
w ) if validNumber "$OPTARG" ; then
sleep=$OPTARG
else
echo "'$OPTARG' is not a valid waiting time!" >&2
exit 1
fi
;;
c ) if [[ -z "$OPTARG" ]] ; then
echo "No valid path for cache file!" >&2
exit 1
else
cache="$OPTARG"
fi
;;
t ) if validNumber "$OPTARG" ; then
computer=$OPTARG
else
echo "'$OPTARG' is not a valid number for steps!" >&2
exit 1
fi
;;
d ) color=false
;;
g ) guiconfig=true
;;
l ) unicodelabels=false
;;
n ) colorFill=false
;;
m ) colorHelper=false
;;
M ) mouse=false
;;
p ) ascii=true
unicodelabels=false
LC_ALL=C
;;
i ) warnings=true
;;
v ) version
exit 0
;;
V ) cursor=false
;;
z ) require gzip
require zcat
cachecompress=true
;;
h ) help
exit 0
;;
\?)
echo -e "Invalid option: -$OPTARG\nFor help, run ./$0 -h" >&2
exit 1
;;
esac
done
# get terminal dimension
echo -en '\e[18t'
if read -r -d "t" -s -t 1 tmp ; then
termDim=("${tmp//;/ }")
termWidth=${termDim[2]}
else
termWidth=80
fi
# gui config
if $guiconfig ; then
# find a dialog system
if type gdialog >/dev/null 2>&1 ; then
dlgtool="gdialog"
dlgh=0
dlgw=100
elif type dialog >/dev/null 2>&1 ; then
dlgtool="dialog"
dlgh=0
dlgw=0
elif type whiptail >/dev/null 2>&1 ; then
dlgtool="whiptail"
dlgh=0
dlgw=$(( termWidth-10 ))
else
dlgtool=""
error "The graphical configuration requires gdialog/zenity, dialog or at least whiptail - but none of them was found on your system. You have to use the arguments to configure the game unless you install one of the required tools..."
fi
# Output the type of the first player in a readable string
function typeOfPlayerA() {
if [[ "$remote" -eq "-1" ]] ; then
echo "Connect to $remoteip (Port $port)"
return 2
elif isAI $A ; then
echo "Artificial Intelligence (with strength $strength)"
return 1
else
echo "Human named $namePlayerA"
return 0
fi
}
# Output the type of the second player in a readable string
function typeOfPlayerB() {
if [[ "$remote" -eq "1" ]] ; then
echo "Host server at port $port"
return 2
elif isAI $B ; then
echo "Artificial Intelligence (with strength $strength)"
return 1
else
echo "Human named $namePlayerB"
return 0
fi
}
# Execute a dialog
# Params: Dialog params (variable length)
# Prints: Dialog output seperated by new lines
# Returns the dialog program return or 255 if no dialog tool available
function dlg() {
if [[ -n "$dlgtool" ]] ; then
$dlgtool --backtitle "ChessBash" "$@" 3>&1 1>&2 2>&3 | sed -e "s/|/\n/g" | sort -u
return "${PIPESTATUS[0]}"
else
return 255
fi
}
# Print a message box with a warning/error message
# Params:
# $1 Message
function dlgerror() {
#TODO: normal error
dlg --msgbox "$1" $dlgh $dlgw
}
# Start the dialog configuration
# Neither params nor return, this is just a function for hiding local variables!
function dlgconfig() {
local option_mainmenu_playerA="First Player"
local option_mainmenu_playerB="Second Player"
local option_mainmenu_settings="Game settings"
local dlg_on="ON"
local dlg_off="OFF"
declare -a option_player=( "Human" "Computer" "Network" )
declare -a option_settings=( "Color support" "Unicode support" "Verbose Messages" "Mouse support" "AI Cache" )
local dlg_main
while dlg_main=$(dlg --ok-button "Edit" --cancel-button "Start Game" --menu "New Game" $dlgh $dlgw 0 "$option_mainmenu_playerA" "$(typeOfPlayerA || true)" "$option_mainmenu_playerB" "$(typeOfPlayerB || true )" "$option_mainmenu_settings" "Color, Unicode, Mouse & AI Cache") ; do
case "$dlg_main" in
# Player A settings
"$option_mainmenu_playerA" )
typeOfPlayerA > /dev/null
local type=$?
local dlg_player
dlg_player=$(dlg --nocancel --default-item "${option_player[$type]}" --menu "$option_mainmenu_playerA" $dlgh $dlgw 0 "${option_player[0]}" "$( isAI $A && echo "$option_mainmenu_playerA" || echo "$namePlayerA" )" "${option_player[1]}" "with AI (of strength $strength)" "${option_player[2]}" "Connect to Server $remoteip" )
case "$dlg_player" in
# Human --> get Name
*"${option_player[0]}"* )
[[ "$remote" -eq "-1" ]] && remote=0
local dlg_namePlayer
dlg_namePlayer=$(dlg --inputbox "Name of $option_mainmenu_playerA" $dlgh $dlgw "$( isAI $A && echo "$option_mainmenu_playerA" || echo "$namePlayerA" )") && namePlayerA="$dlg_namePlayer"
;;
# Computer --> get Strength
*"${option_player[1]}"* )
[[ "$remote" -eq "-1" ]] && remote=0
namePlayerA=$aikeyword
local dlg_strength
if dlg_strength=$(dlg --inputbox "Strength of Computer" $dlgh $dlgw "$strength") ; then
if validNumber "$dlg_strength" ; then
strength=$dlg_strength
else
dlgerror "Your input '$dlg_strength' is not a valid number!"
fi
fi
;;
# Network --> get Server and Port
*"${option_player[2]}"* )
local dlg_remoteip
if dlg_remoteip=$(dlg --inputbox "IP(v4 or v6) address of Server" $dlgh $dlgw "$remoteip") ; then
if validIP "$dlg_remoteip" ; then
remote=-1
remoteip="$dlg_remoteip"
local dlg_networkport
if dlg_networkport=$(dlg --inputbox "Server Port (non privileged)" $dlgh $dlgw "$port") ; then
if validPort "$dlg_networkport" ; then
port=$dlg_networkport
else
dlgerror "Your input '$dlg_remoteip' is not a valid Port!"
fi
fi
else
dlgerror "Your input '$dlg_remoteip' is no valid IP address!"
continue
fi
fi
;;
esac
# Player color
if $color ; then
local colorlist=""
local c
for (( c=1; c<7; c++ )) ; do
colorlist+=" ${colors[$c]^} figures"
done
local dlg_player_color
if dlg_player_color=$(dlg --nocancel --default-item "${colors[$colorPlayerA]^}" --menu "Color of $option_mainmenu_playerA" $dlgh $dlgw 0 "$colorlist") ; then
getColor "$dlg_player_color" || colorPlayerA=$?
fi
fi
;;
# Player B settings
"$option_mainmenu_playerB" )
typeOfPlayerB > /dev/null
local type=$?
local dlg_player
dlg_player=$(dlg --nocancel --default-item "${option_player[$type]}" --menu "$option_mainmenu_playerB" $dlgh $dlgw 0 "${option_player[0]}" "$( isAI $B && echo "$option_mainmenu_playerB" || echo "$namePlayerB" )" "${option_player[1]}" "with AI (of strength $strength)" "${option_player[2]}" "Wait for connections on port $port" )
case "$dlg_player" in
# Human --> get Name
*"${option_player[0]}"* )
[[ "$remote" -eq "1" ]] && remote=0
local dlg_namePlayer
dlg_namePlayer=$(dlg --inputbox "Name of $option_mainmenu_playerB" $dlgh $dlgw "$( isAI $B && echo "$option_mainmenu_playerB" || echo "$namePlayerB" )") && namePlayerA="$dlg_namePlayer"
;;
# Computer --> get Strength
*"${option_player[1]}"* )
[[ "$remote" -eq "1" ]] && remote=0
namePlayerB=$aikeyword
local dlg_strength
if dlg_strength=$(dlg --inputbox "Strength of Computer" $dlgh $dlgw "$strength") ; then
if validNumber "$dlg_strength" ; then
strength=$dlg_strength
else
dlgerror "Your input '$dlg_strength' is not a valid number!"
fi
fi
;;
# Network --> get Server and Port
*"${option_player[2]}"* )
remote=1
local dlg_networkport
if dlg_networkport=$(dlg --inputbox "Server Port (non privileged)" $dlgh $dlgw "$port") ; then
if validPort "$dlg_networkport" ; then
port=$dlg_networkport
else
dlgerror "Your input '$dlg_remoteip' is not a valid Port!"
fi
fi
;;
esac
# Player color
if $color ; then
local colorlist=""
local c
for (( c=1; c<7; c++ )) ; do
colorlist+=" ${colors[$c]^} figures"
done
local dlg_player_color
if dlg_player_color=$(dlg --nocancel --default-item "${colors[$colorPlayerB]^}" --menu "Color of $option_mainmenu_playerB" $dlgh $dlgw 0 "$colorlist") ; then
getColor "$dlg_player_color" || colorPlayerB=$?
fi
fi
;;
# Game settings
"$option_mainmenu_settings" )
if dlg_settings=$(dlg --separate-output --checklist "$option_mainmenu_settings" $dlgh $dlgw $dlgw "${option_settings[0]}" "with movements and figures" "$($color && echo $dlg_on || echo $dlg_off)" "${option_settings[1]}" "optional including board labels" "$($ascii && echo $dlg_off || echo $dlg_on)" "${option_settings[2]}" "be chatty" "$($warnings && echo $dlg_on || echo $dlg_off)" "${option_settings[3]}" "be clicky" "$($mouse && echo $dlg_on || echo $dlg_off)" "${option_settings[4]}" "in a regluar file" "$([[ -n "$cache" ]] && echo $dlg_on || echo $dlg_off)" ) ; then
# Color support
if [[ "$dlg_settings" == *"${option_settings[0]}"* ]] ; then
color=true
dlg --yesno "Enable movement helper (colorize possible move)?" $dlgh $dlgw && colorHelper=true || colorHelper=false
dlg --yesno "Use filled (instead of outlined) figures for both player?" $dlgh $dlgw && colorFill=true || colorFill=false
else
color=false
colorFill=false
colorHelper=false
fi
# Unicode support
if [[ "$dlg_settings" == *"${option_settings[1]}"* ]] ; then
ascii=false
( dlg --yesno "Use Unicode for board labels?" $dlgh $dlgw ) && unicodelabels=true || unicodelabels=false
else
ascii=true
unicodelabels=false
fi
# Verbose messages
[[ "$dlg_settings" == *"${option_settings[2]}"* ]] && warnings=true || warnings=false
# Mouse support
[[ "$dlg_settings" == *"${option_settings[3]}"* ]] && mouse=true || mouse=false
# AI Cache
local dlg_cache
if [[ "$dlg_settings" == *"${option_settings[4]}"* ]] && dlg_cache=$(dlg --inputbox "Cache file:" $dlgh $dlgw "$([[ -z "$cache" ]] && echo "$(pwd)/chessbash.cache" || echo "$cache")") && [[ -n "$dlg_cache" ]] ; then
cache="$dlg_cache"
type gzip >/dev/null 2>&1 && type zcat >/dev/null 2>&1 && dlg --yesno "Use GZip compression for Cache?" $dlgh $dlgw && cachecompress=true || cachecompress=false
else
cache=""
fi
# Waiting time (ask always)
local dlg_sleep
if dlg_sleep=$(dlg --inputbox "How long should every message be displayed (in seconds)?" $dlgh $dlgw "$sleep") ; then
if validNumber "$dlg_sleep" ; then
sleep=$dlg_sleep
else
dlgerror "Your input '$dlg_sleep' is not a valid number!"
fi
fi
fi
;;
# Other --> exit (gdialog)
* )
break
;;
esac
done
}
# start config dialog
dlgconfig
fi
# Save screen
if $cursor ; then
echo -e "\e7\e[s\e[?47h\e[?25l\e[2J\e[H"
fi
# lookup tables
declare -A cacheLookup
declare -A cacheFlag
declare -A cacheDepth
# associative arrays are faster than numeric ones and way more readable
declare -A redraw
if $cursor ; then
for (( y=0; y<10; y++ )) ; do
for (( x=-2; x<8; x++ )) ; do
redraw[$y,$x]=""
done
done
fi
# array to set and get the piece type per coordinates [y,x]
declare -A field
# board start position
# initialize setting - first row
declare -a initline=( 4 2 3 5 6 3 2 4 )
for (( x=0; x<8; x++ )) ; do
# set pieces at row 1
field[0,$x]=${initline[$x]}
# set pawns at row 2
field[1,$x]=1
# set empty squares from row 3 up to row 6
for (( y=2; y<6; y++ )) ; do
field[$y,$x]=0
done
# set pawns at row 7
field[6,$x]=-1
# set pieces at row 8
field[7,$x]=$(( (-1) * ${initline[$x]} ))
done
# readable figure names
declare -a figNames=( "(empty)" "pawn" "knight" "bishop" "rook" "queen" "king" )
# ascii figure names (for ascii output)
declare -a asciiNames=( "k" "q" "r" "b" "n" "p" " " "P" "N" "B" "R" "Q" "K" )
# Evaluaton
# References:
# https://www.chessprogramming.org/Evaluation
# https://www.chessprogramming.org/Point_Value
# https://en.wikipedia.org/wiki/Chess_piece_relative_value
#
# Point value basic evaluation:
# figure weight (for heuristic)
#declare -a figValues=( 0 1 5 5 6 17 42 )
declare -a figValues=( 0 1 3 3 5 9 42 )
#declare -a figValues=( 0 100 320 330 500 900 10000 )
# Warning message on invalid moves (Helper)
# Params:
# $1 message
# (no return value)
function warn() {
message="\e[41m\e[1m$1\e[0m\n"
draw
}
# Readable coordinates
# Params:
# $1 row / rank position
# $2 column / file position
# Writes coordinates to stdout
function coord() {
#echo -en "\x$((41 + $2))$((8 - $1))" # uppercase
echo -en "\x$((61 + $2))$((8 - $1))" # lowercase
}
# Get name of player
# Params:
# $1 player
# Writes name to stdout
function namePlayer() {
if (( $1 < 0 )) ; then
if $color ; then
echo -en "\e[3${colorPlayerA}m"
fi
if isAI "$1" ; then
echo -n "$aiPlayerA"
else
echo -n "$namePlayerA"
fi
else
if $color ; then
echo -en "\e[3${colorPlayerB}m"
fi
if isAI "$1" ; then
echo -n "$aiPlayerB"
else
echo -n "$namePlayerB"
fi
fi
if $color ; then
echo -en "\e[0m"
fi
}
# Get name of figure
# Params:
# $1 figure
# Writes name to stdout
function nameFigure() {
if (( $1 < 0 )) ; then
echo -n "${figNames[$1*(-1)]}"
else
echo -n "${figNames[$1]}"
fi
}
# Check win/loose position
# (player has king?)
# Params:
# $1 player
# Return status code 1 if no king
function hasKing() {
local player=$1;
local x
local y
for (( y=0;y<8;y++ )) ; do
for (( x=0;x<8;x++ )) ; do
if (( ${field[$y,$x]} * player == 6 )) ; then
return 0
fi
done
done
return 1
}
# Check validity of a concrete single movement
# Params:
# $1 origin Y position
# $2 origin X position
# $3 target Y position
# $4 target X position
# $5 current player
# Returns status code 0 if move is valid
function canMove() {
local fromY=$1
local fromX=$2
local toY=$3
local toX=$4
local player=$5
local i
if (( fromY < 0 || fromY >= 8 || fromX < 0 || fromX >= 8 || toY < 0 || toY >= 8 || toX < 0 || toX >= 8 || ( fromY == toY && fromX == toX ) )) ; then
return 1
fi
local from=${field[$fromY,$fromX]}
local to=${field[$toY,$toX]}
local fig=$(( from * player ))
if (( from == 0 || from * player < 0 || to * player > 0 || player * player != 1 )) ; then
return 1
# pawn
elif (( fig == 1 )) ; then
if (( fromX == toX && to == 0 && ( toY - fromY == player || ( toY - fromY == 2 * player && ${field["$((player + fromY)),$fromX"]} == 0 && fromY == ( player > 0 ? 1 : 6 ) ) ) )) ; then
return 0
else
return $(( ! ( (fromX - toX) * (fromX - toX) == 1 && toY - fromY == player && to * player < 0 ) ))
fi
# queen, rook and bishop
elif (( fig == 5 || fig == 4 || fig == 3 )) ; then
# rook - and queen
if (( fig != 3 )) ; then
if (( fromX == toX )) ; then
for (( i = ( fromY < toY ? fromY : toY ) + 1 ; i < ( fromY > toY ? fromY : toY ) ; i++ )) ; do
if (( ${field[$i,$fromX]} != 0 )) ; then
return 1
fi
done
return 0
elif (( fromY == toY )) ; then
for (( i = ( fromX < toX ? fromX : toX ) + 1 ; i < ( fromX > toX ? fromX : toX ) ; i++ )) ; do
if (( ${field[$fromY,$i]} != 0 )) ; then
return 1
fi
done
return 0
fi
fi
# bishop - and queen
if (( fig != 4 )) ; then
if (( ( fromY - toY ) * ( fromY - toY ) != ( fromX - toX ) * ( fromX - toX ) )) ; then
return 1
fi
for (( i = 1 ; i < ( fromY > toY ? fromY - toY : toY - fromY) ; i++ )) ; do
if (( ${field[$((fromY + i * (toY - fromY > 0 ? 1 : -1 ) )),$(( fromX + i * (toX - fromX > 0 ? 1 : -1 ) ))]} != 0 )) ; then
return 1
fi
done
return 0
fi
# nothing found? wrong move.
return 1
# knight
elif (( fig == 2 )) ; then
return $(( ! ( ( ( fromY - toY == 2 || fromY - toY == -2) && ( fromX - toX == 1 || fromX - toX == -1 ) ) || ( ( fromY - toY == 1 || fromY - toY == -1) && ( fromX - toX == 2 || fromX - toX == -2 ) ) ) ))
# king
elif (( fig == 6 )) ; then
return $(( !( ( ( fromX - toX ) * ( fromX - toX ) ) <= 1 && ( ( fromY - toY ) * ( fromY - toY ) ) <= 1 ) ))
# invalid figure
else
error "Invalid figure '$from'!"
exit 1
fi
}
# minimax (game theory) algorithm for evaluate possible movements
# (the heart of your computer enemy)
# currently based on negamax with alpha/beta pruning and transposition tables liked described in
# http://en.wikipedia.org/wiki/Negamax#NegaMax_with_Alpha_Beta_Pruning_and_Transposition_Tables
# Params:
# $1 current search depth
# $2 alpha (for pruning)
# $3 beta (for pruning)
# $4 current moving player
# $5 preserves the best move (for ai) if true
# Returns best value as status code
# negamax "$strength" 0 255 "$player" true
function negamax() {
LC_ALL=C
local depth=$1
local a=$2
local b=$3
local player=$4
local save=$5
# transposition table
local aSave=$a
local hash
hash="$player ${field[*]}"
if ! $save && test "${cacheLookup[$hash]+set}" && (( ${cacheDepth[$hash]} >= depth )) ; then
local value=${cacheLookup[$hash]}
local flag=${cacheFlag[$hash]}
if (( flag == 0 )) ; then
return "$value"
elif (( flag == 1 && value > a )) ; then
a=$value
elif (( flag == -1 && value < b )) ; then
b=$value
fi
if (( a >= b )) ; then
return "$value"
fi
fi
# lost own king?
if ! hasKing "$player" ; then
cacheLookup[$hash]=$(( strength - depth + 1 ))
cacheDepth[$hash]=$depth
cacheFlag[$hash]=0
return $(( strength - depth + 1 ))
# use heuristics in depth
elif (( depth <= 0 )) ; then
local values=0
for (( y=0; y<8; y++ )) ; do
for (( x=0; x<8; x++ )) ; do
local fig=${field[$y,$x]}
if (( ${field[$y,$x]} != 0 )) ; then
local figPlayer=$(( fig < 0 ? -1 : 1 ))
# a more simple heuristic would be values=$(( $values + $fig ))
# figPlayer: white=1, black =-1
# fig: piece number identifier
# figValues: material piece value
# ${figValues[$fig]} * figPlayer = material total value
#(( values += ${figValues[$fig]} * figPlayer ))
(( values += ${figValues[$fig * $figPlayer]} * figPlayer ))
# pawns near to end are better
if (( fig == 1 )) ; then
if (( figPlayer > 0 )) ; then
(( values += ( y - 1 ) / 2 ))
else
(( values -= ( 6 + y ) / 2 ))
fi
fi
fi
done
done
values=$(( 127 + ( player * values ) ))
# ensure valid bash return range [0-255]
if (( values > 253 - strength )) ; then
values=$(( 253 - strength ))
elif (( values < 2 + strength )) ; then
values=$(( 2 + strength ))
fi
cacheLookup[$hash]=$values
cacheDepth[$hash]=0
cacheFlag[$hash]=0
return $values
# calculate best move
else
local bestVal=0
local fromY
local fromX
local toY
local toX
local i
local j
for (( fromY=0; fromY<8; fromY++ )) ; do
for (( fromX=0; fromX<8; fromX++ )) ; do
local fig=$(( ${field[$fromY,$fromX]} * ( player ) ))
# precalc possible fields (faster then checking every 8*8 again)
local targetY=()
local targetX=()
local t=0
# empty or enemy
if (( fig <= 0 )) ; then
continue
# pawn
elif (( fig == 1 )) ; then
targetY[$t]=$(( player + fromY ))
targetX[$t]=$(( fromX ))
(( t += 1 ))
targetY[$t]=$(( 2 * player + fromY ))
targetX[$t]=$(( fromX ))
(( t += 1 ))
targetY[$t]=$(( player + fromY ))
targetX[$t]=$(( fromX + 1 ))
(( t += 1 ))
targetY[$t]=$(( player + fromY ))
targetX[$t]=$(( fromX - 1 ))
(( t += 1 ))
# knight
elif (( fig == 2 )) ; then
for (( i=-1 ; i<=1 ; i=i+2 )) ; do
for (( j=-1 ; j<=1 ; j=j+2 )) ; do
targetY[$t]=$(( fromY + 1 * i ))
targetX[$t]=$(( fromX + 2 * j ))
(( t + 1 ))
targetY[$t]=$(( fromY + 2 * i ))
targetX[$t]=$(( fromX + 1 * j ))
(( t + 1 ))
done
done
# king
elif (( fig == 6 )) ; then
for (( i=-1 ; i<=1 ; i++ )) ; do
for (( j=-1 ; j<=1 ; j++ )) ; do
targetY[$t]=$(( fromY + i ))
targetX[$t]=$(( fromX + j ))
(( t += 1 ))
done
done
else
# bishop or queen
if (( fig != 4 )) ; then
for (( i=-8 ; i<=8 ; i++ )) ; do
if (( i != 0 )) ; then
# can be done nicer but avoiding two loops!
targetY[$t]=$(( fromY + i ))
targetX[$t]=$(( fromX + i ))
(( t += 1 ))
targetY[$t]=$(( fromY - i ))
targetX[$t]=$(( fromX - i ))
(( t += 1 ))
targetY[$t]=$(( fromY + i ))
targetX[$t]=$(( fromX - i ))
(( t += 1 ))