-
Notifications
You must be signed in to change notification settings - Fork 2
/
tic-tac-toe.sh
124 lines (98 loc) · 2.39 KB
/
tic-tac-toe.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
#!/bin/bash
#The real trick to emulate 2-d array is associative array, wherein string '1,2' becomes the index of array - matrix[1,2]
declare -A matrix
rows=3
cols=3
function print_matrix(){
for ((i=0; i<rows; i++ )) do
echo
for (( j=0; j<cols; j++ )) do
if [ "${matrix[$i,$j]}" = "1" ]; then
printf "%5s" "x"
elif [ "${matrix[$i,$j]}" = "0" ]; then
printf "%5s" "o"
else
printf "%5s" "${matrix[$i,$j]}"
fi
done
done
echo
}
#Check if either player is winner or the game is draw
function check_gameover(){
flag=0
for((i=0; i<rows; i++)){
if [[ ${matrix[$i,0]} != -1 && ${matrix[$i,0]} == ${matrix[$i,1]} && ${matrix[$i,0]} == ${matrix[$i,2]} ]]; then
flag=1
fi
}
for((j=0; j<cols; j++)){
if [[ ${matrix[0,$j]} != -1 && ${matrix[0,$j]} == ${matrix[1,$j]} && ${matrix[0,$j]} == ${matrix[2,$j]} ]]; then
flag=1
fi
}
if [[ ${matrix[0,0]} != -1 && ${matrix[0,0]} == ${matrix[1,1]} && ${matrix[0,0]} == ${matrix[2,2]} ]]; then
flag=1
fi
if [[ ${matrix[0,2]} != -1 && ${matrix[0,2]} == ${matrix[1,1]} && ${matrix[0,2]} == ${matrix[2,0]} ]]; then
flag=1
fi
if [ "$flag" == "1" ]; then
echo "Game over!!!!"
exit 0
fi
draw=1
for ((i=0; i<rows; i++ )) do
for (( j=0; j<cols; j++ )) do
if [ ${matrix[$i,$j]} == -1 ]; then
draw=0
fi
done
done
if [ "$draw" == "1" ]; then
echo "It's draw!!!"
exit 0
fi
}
#Initialize the matrix with -1 to indicate empty positions
for ((i=0; i<rows; i++ )) do
for (( j=0; j<cols; j++ )) do
matrix[$i,$j]=-1
done
done
echo "Initial state : "
print_matrix
echo
echo "Note : -1 means the position is still empty."
echo
echo "Game begins now..."
echo
while true;
do
while true;
do
echo -n "1st player (row column): "
read x y
if [ ${matrix[$x,$y]} == -1 ]; then
matrix[$x,$y]=0
break
fi
echo "Position already filled!! Re-enter valid position."
done
print_matrix
echo
check_gameover
while true;
do
echo -n "2nd player (row column): "
read x y
if [ ${matrix[$x,$y]} == -1 ]; then
matrix[$x,$y]=1
break
fi
echo "Position already filled!! Re-enter valid position."
done
print_matrix
echo
check_gameover
done