-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path2048.sh
executable file
·155 lines (137 loc) · 2 KB
/
2048.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
#!/bin/bash
# Copyright: Maxim Norin, (c)2016
# Game "2048" written in pure bash with size 2048 (including this text)
# http://mnorin.com
# E-mail: [email protected]
M=()
L=()
align(){
for i in {1..3}
{
for j in {1..3}
{
[ "${L[$j]}" != "" ] && [ "${L[$j-1]}" == "" ] && L[$j-1]=${L[$j]} && L[$j]=""
}
}
}
sum(){
for i in {1..3}
{
[ "${L[$i]}" == "${L[$i-1]}" ] && [ "${L[$i]}" != "" ] && L[$i-1]=$(( ${L[$i]} * 2 )) && L[$i]=""
}
}
sumup(){
align
sum
align
}
left(){
for n in 0 4 8 12
{
L=( ${M[$n]} ${M[$n+1]} ${M[$n+2]} ${M[$n+3]} )
sumup
M[$n]=${L[0]}
M[$n+1]=${L[1]}
M[$n+2]=${L[2]}
M[$n+3]=${L[3]}
}
}
right(){
for n in 0 4 8 12
{
L=( ${M[$n+3]} ${M[$n+2]} ${M[$n+1]} ${M[$n]} )
sumup
M[$n+3]=${L[0]}
M[$n+2]=${L[1]}
M[$n+1]=${L[2]}
M[$n]=${L[3]}
}
}
up(){
for n in 0 1 2 3
{
L=( ${M[$n]} ${M[$n+4]} ${M[$n+8]} ${M[$n+12]} )
sumup
M[$n]=${L[0]}
M[$n+4]=${L[1]}
M[$n+8]=${L[2]}
M[$n+12]=${L[3]}
}
}
down(){
for n in 0 1 2 3
{
L=( ${M[$n+12]} ${M[$n+8]} ${M[$n+4]} ${M[$n]} )
sumup
M[$n+12]=${L[0]}
M[$n+8]=${L[1]}
M[$n+4]=${L[2]}
M[$n]=${L[3]}
}
}
board(){
D="---------------------"
S="%s\n|%4s|%4s|%4s|%4s|\n"
clear
p=printf
echo 2048.bash
echo
$p $S $D ${M[0]:-"."} ${M[1]:-"."} ${M[2]:-"."} ${M[3]:-"."}
$p $S $D ${M[4]:-"."} ${M[5]:-"."} ${M[6]:-"."} ${M[7]:-"."}
$p $S $D ${M[8]:-"."} ${M[9]:-"."} ${M[10]:-"."} ${M[11]:-"."}
$p $S $D ${M[12]:-"."} ${M[13]:-"."} ${M[14]:-"."} ${M[15]:-"."}
echo $D
echo
echo "Moves: w,a,s,d, Quit: q"
}
a2(){
n=$(($RANDOM % 16))
while [ "${M[$n]}" != "" ]
do
n=$(($RANDOM % 16))
done
M[$n]=2
}
setup(){
for i in {0..15}; do M[$i]=""; done
a2
a2
board
}
check(){
F=1
for i in {0..15}
{
[ "${M[$i]}" == "" ] && F=0
}
return $F
}
game.over(){
while [ "$REPLY" != "y" ] && [ "$REPLY" != "n" ]
do
read -n 1 -p "GAME OVER! Play again? (y/n)"
done
case $REPLY in
y) setup; return 1 ;;
n) exit ;;
esac
}
RANDOM=12345
setup
while :
do
read -n 1 -s
case $REPLY in
w) up ;;
a) left ;;
s) down ;;
d) right ;;
q) exit ;;
*) continue ;;
esac
check || game.over || continue
board
sleep 1
a2
board
done