-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoxo_logic.sh
executable file
·446 lines (369 loc) · 12.9 KB
/
oxo_logic.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
#!/usr/bin/env bash
# ########################################
# Traditional Noughts and Crosses
#
# - 3x3 board with 2 players
# - player 1 is human
# - player 2 can be human or computer
# - Any full diagonal or horizontal wins
# - First player starts with x always
#
# ########################################
# ########################################
# GLOBALS and UTILS
# ########################################
declare -r square_side=3
declare -r board_size=$(( ${square_side} * ${square_side} ))
declare -r TRUE=0
declare -r FALSE=1
to_indices() {
local array_size=${1}
printf "%s " $(seq 0 $(( ${array_size} - 1)))
}
if which spd-say > /dev/null
then voice_prompter='spd-say -e -r 10'
is_voice_active=${TRUE}
elif which say > /dev/null
then voice_prompter='say -r 10 -f -'
is_voice_active=${TRUE}
else voice_prompter='tee /dev/null'
is_voice_active=${FALSE}
fi && declare -r voice_prompter is_voice_active
prompt() {
cat <<<"${@}" | $voice_prompter
}
# ########################################
# BOARD DESIGN
#
# All oxo boards are squares, and the board state is an array of:
# empty = - (hyphen)
# cross = X (upper case x)
# nought = O (upper case o)
#
# ########################################
declare -a board_state
declare -a positions=($(to_indices ${board_size}))
# We expect players to visually locate board positions on the game board,
# and mark the desired positions by Row-Column pair <character><integer>,
# such as a1, a3, b2, c1.
declare -a col_labels=($(seq ${square_side}))
declare -a row_labels=($(head -n ${square_side} <(printf "%s\n" {a..z})))
declare -a pos_labels=($(for r in ${row_labels[*]}
do for c in ${col_labels[*]}
do printf "%s%s " ${r} ${c}
done
done))
# Given player input, we need to reverse-lookup the corresponding index
# position in the array that stores the board's state.
declare -A pos_lookup_table &&
for pos in ${positions[*]}
do pos_lookup_key="${pos_labels[$pos]}"
pos_lookup_val="${positions[$pos]}"
pos_lookup_table[${pos_lookup_key}]=${pos_lookup_val}
done &&
unset array_idx pos_lookup_key pos_lookup_val # don't pollute global vars
# Pre-calculate indices for diagonal positions stored in the board state array.
# We will need to check state of diagonals for scoring purposes.
declare -a diagonal_left &&
for i in $(to_indices ${square_side})
do diagonal_left[${i}]=$(( (${square_side} * ${i}) + ${i} ))
done &&
declare -r diagonal_left
declare -a diagonal_right &&
for i in $(to_indices ${square_side})
do diagonal_right[${i}]=$(( (${square_side} * (${i} + 1 )) - (${i} + 1) ))
done &&
declare -r diagonal_right
# ########################################
# BOARD STATE AND DISPLAY MANIPULATION UTILITIES
# ########################################
set_pos_to_val() {
local pos=${1}
local val=${2}
board_state[${pos}]=${val}
}
reset_board() {
for i in $(to_indices ${board_size});
do set_pos_to_val ${i} "-";
done
}
fit_val_to_square_grid() {
printf "%s%s" ${1} ' '
}
fit_board_to_square_grid() {
for pos in $(to_indices ${board_size})
do if [[ $(( ($pos + 1) % $square_side )) == 0 ]]
then printf "%s \n" $(fit_val_to_square_grid ${board_state[${pos}]})
else fit_val_to_square_grid ${board_state[${pos}]}
fi
done
}
transpose_board() {
local board=$(cat ${@})
__transpose_col() { cut -d ' ' -f ${1} | paste -d ' ' -s; }
for col_num in $(seq ${square_side})
do printf "%s \n" "$(printf "%s" "${board}" | __transpose_col ${col_num})"
done
}
# We display based on the square grid
display_oxo_board() {
printf "\n"
printf "\t\t%s\n\n" "$(printf "%s " ${col_labels[*]})"
paste <(printf "\t%s\n" ${row_labels[*]}) \
<(fit_board_to_square_grid)
printf "\n"
}
# ##################################################
# RANDOM Player support
# ##################################################
__get_random_pos() {
printf "$(( ${RANDOM} % ${1} ))"
}
__get_labels_for_empty_pos() {
for pos in $(to_indices ${board_size})
do if [[ ${board_state[${pos}]} == "-" ]]
then printf "%s " ${pos_labels[${pos}]}
fi
done
}
get_label_for_random_empty_pos() {
local labels_for_empty_pos=($(__get_labels_for_empty_pos))
local num_empty_pos=${#labels_for_empty_pos[*]}
local empty_pos_labels_rand_idx=$(__get_random_pos ${num_empty_pos})
# lookup and emit label for randomly picked empty position, such that
# which we can pass it into regular gameplay, as computer's choice
printf "%s" ${labels_for_empty_pos[${empty_pos_labels_rand_idx}]}
}
# ########################################
# SCORING LOGIC
#
# Base it on a regular, well-formatted, grid layout of the game state,
# so we can have some fun exploiting the text processing power of bash.
#
# We have three victory scenarios that we can test as follows.
#
# Row Victory:
#
# - A player wins a game if the pattern of _any row_ is "X X X " or
# "O O O " in our scheme of things. This is simply a strict grep that
# succeeds (exit code 0) against our grid view:
#
# grep -E "^X[[:space:]]X[[:space:]]X[[:space:]]$"
#
# Column Victory:
#
# - If we transpose the board (columns -> rows), then we can reuse the
# same grid-based grep-check to see if a player has won a column.
#
# Diagonal Victory:
#
# - And finally, if we extract diagonal items from the game state array
# into a grid-formatted row (say items 1,5,9), then we can again use
# the exact same grep test.
#
# ########################################
__all_crosses() {
local all_Xs_pattern="$(printf "^(X[[:space:]]){%s}$" ${square_side})"
grep -E "${all_Xs_pattern}" > /dev/null
}
__all_noughts() {
local all_Os_pattern="$(printf "^(O[[:space:]]){%s}$" ${square_side})"
grep -E "${all_Os_pattern}" > /dev/null
}
__player_move_available() {
fit_board_to_square_grid | grep '-' > /dev/null
}
__player_wins_grid_row() {
local player_win_func=${1}
fit_board_to_square_grid | $player_win_func
}
__player_wins_grid_col() {
local player_win_func=${1}
fit_board_to_square_grid | transpose_board | $player_win_func
}
__extract_this_diagonal() {
local diagonal=${1}
for board_pos in ${diagonal}
do fit_val_to_square_grid ${board_state[${board_pos}]}
done
}
__player_wins_grid_left_diagonal() {
local player_win_func=${1}
__extract_this_diagonal "${diagonal_left[*]}" | $player_win_func
}
__player_wins_grid_right_diagonal() {
local player_win_func=${1}
__extract_this_diagonal "${diagonal_right[*]}" | $player_win_func
}
__player_wins_grid() {
local player_win_func=${1}
if __player_wins_grid_row $player_win_func \
|| __player_wins_grid_col $player_win_func \
|| __player_wins_grid_left_diagonal $player_win_func \
|| __player_wins_grid_right_diagonal $player_win_func
then true
else false
fi
}
crosses_win() {
__player_wins_grid __all_crosses
}
noughts_win() {
__player_wins_grid __all_noughts
}
its_a_draw() {
if crosses_win \
|| noughts_win \
|| __player_move_available
then false
else true
fi
}
# ########################################
# PLAYER ACTIONS
#
# - The only thing a player can do is point to the position they
# want filled with their assigned symbol X or O.
#
# - Only an empty position may be overwritten with legal X/O values.
#
# - Once an X or an O is written to a position, it may never be overwritten.
#
# ########################################
pos_is_empty() {
local position="${1}"
[[ ${board_state[${position}]} == '-' ]]
}
set_pos_to_X() {
local position="${1}"
if pos_is_empty ${position}
then set_pos_to_val ${position} 'X'
else false
fi
}
set_pos_to_O() {
local position="${1}"
if pos_is_empty ${position}
then set_pos_to_val ${position} 'O'
else false
fi
}
# ########################################
# GAME LOOP
#
# - On each move, check if noughts won, or crosses won
#
# ########################################
animate_loading_symbol() {
local loop_count=${1:-1}
local char_sequence=('.' 'o' 'O' 'X' 'x' '.')
local char_times_to_print=3
local sleep_sec="0.075"
for _ in $(seq ${loop_count})
do for c in ${char_sequence[*]}
do for _ in $(seq ${char_times_to_print})
do printf "%s" "${c}"
sleep ${sleep_sec}
done
for _ in $(seq ${char_times_to_print})
do printf "\b"
done
done
done
}
game_loop() {
local computer_opponent=${1:-${FALSE}} # init game for 2 player by default
local game_is_afoot=${TRUE} # the game is always afoot!
local player_X_turn=${TRUE} # X always plays first when the game begins
local player_O_turn=${FALSE}
local player_choice player_prompt # define variables for use below
__display_header() {
cat <<EOF
xoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxo
THE GAME IS AFOOT!
Choose position (e.g. a1 or b3 or c2) | (Q)uit
xoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxo
EOF
}
__display_player_prompt() {
if [[ ${player_X_turn} == ${TRUE} ]]
then prompt "Player X's choice: "
else prompt "Player O's choice: "
fi
}
__toggle_player() {
if [[ ${player_X_turn} == ${TRUE} ]]
then player_O_turn=${TRUE}
player_X_turn=${FALSE}
else player_X_turn=${TRUE}
player_O_turn=${FALSE}
fi
}
while [[ ${game_is_afoot} == ${TRUE} ]] ; do
# ##################################################
# Repaint display
# ##################################################
clear
__display_header
display_oxo_board
# ##################################################
# Loop only while the game can still legally go on
# ##################################################
if noughts_win
then player_choice="Q" # Hook into "quit" case, handled below
prompt "$(printf "\n%s\n" "GAME OVER... NOUGHTS WON!")"
elif crosses_win
then player_choice="Q" # Hook into "quit" case, handled below
prompt "$(printf "\n%s\n" "GAME OVER... CROSSES WON!")"
elif its_a_draw
then player_choice="Q" # Hook into "quit" case, handled below
prompt "$(printf "\n%s\n" "GAME OVER... IT'S A DRAW!")"
elif [[ ${computer_opponent} == ${TRUE} && ${player_O_turn} == ${TRUE} ]]
then # Get the computer to make its move
player_choice="$(get_label_for_random_empty_pos)"
__display_player_prompt
printf "Computer is thinking... "
animate_loading_symbol
prompt "Computer chose ${player_choice}"
sleep 2
else # Accept player input, handled below
read -p "$(__display_player_prompt)" player_choice
fi
# ##################################################
# Handle player choice
# ##################################################
case "${player_choice}" in
q|Q )
# ##################################################
# Terminate the game and cleanup any runtime stuff
# ##################################################
prompt "$(printf "\n%s\n\n" "Thank you for playing; bye bye!")"
game_is_afoot=${FALSE}
;;
[${row_labels[0]}-${row_labels[-1]}][${col_labels[0]}-${col_labels[-1]}] )
# ##################################################
# Safe-set the matched position for the current player
# ##################################################
#
# NOTE: Bash does NOT perform quote removal for patterns, so trying
# to generate a pattern as follows does NOT work as hoped:
#
# $(printf "%s|" ${pos_labels[*]} | sed -E 's;\|$;;') ) list ;;
#
# # produces a1|a2|a3|b1|b2|b3|c1|c2|c3 which _looks_ like a
# # pattern, but is effectively a single string that DOES NOT
# # get further stripped into a case match _pattern_.
#
[[ ${player_X_turn} == ${TRUE} ]] \
&& set_pos_to_X ${pos_lookup_table[${player_choice}]} \
&& __toggle_player # cause toggle IFF position is set by player successfully
[[ ${player_O_turn} == ${TRUE} ]] \
&& set_pos_to_O ${pos_lookup_table[${player_choice}]} \
&& __toggle_player # cause toggle IFF position is set by player successfully
;;
* ) prompt "BAD CHOICE. Please retry. "
sleep 1
;;
esac
done
}