-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathtetris.sh
executable file
·583 lines (507 loc) · 17 KB
/
tetris.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
#!/bin/bash
# Tetris game written in pure bash
#
# I tried to mimic as close as possible original tetris game
# which was implemented on old soviet DVK computers (PDP-11 clones)
#
# Videos of this tetris can be found here:
#
# http://www.youtube.com/watch?v=O0gAgQQHFcQ
# http://www.youtube.com/watch?v=iIQc1F3UuV4
#
# This script was created on ubuntu 13.04 x64 and bash 4.2.45(1)-release.
# It was not tested on other unix like operating systems.
#
# Enjoy :-)!
#
# Author: Kirill Timofeev <[email protected]>
#
# Localized Support: Rojen Zaman <[email protected]> | lang/README.md
#
# This program is free software. It comes without any warranty, to the extent
# permitted by applicable law. You can redistribute it and/or modify it under
# the terms of the Do What The Fuck You Want To Public License, Version 2, as
# published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
set -u # non initialized variable is an error
script_dir=$(dirname $(readlink -f $0)) # define script location
# show usage when given -h argument
usage() {
local available_languages=$(ls -I README.md $script_dir/lang/ 2>/dev/null | cut -d. -f1) # show available languages
echo "usage: $0 [-h] [-l language]"
if [ -z "$available_languages" ] ; then
echo "This script supports localization via language files that can be put into $script_dir/lang"
echo "Please see https://github.com/kt97679/tetris/blob/master/lang/README.md for more details"
else
echo "available languages:"
( echo "english (default)" && echo "$available_languages") | sort
fi
exit 0
}
# BEGIN OF LANGUAGE LINES
# if you want see or add other languages, visit $script_dir/lang/ dir and read $script_dir/lang/README.md
# default localized values english:
i18n_lines_completed="Lines completed: "
i18n_level="Level: "
i18n_score="Score: "
i18n_use_cursor_keys=" Use cursor keys"
i18n_or=" or"
i18n_rotate=" s: rotate"
i18n_left_right="a: left, d: right"
i18n_drop=" space: drop"
i18n_quit=" q: quit"
i18n_toggle_color=" c: toggle color"
i18n_toggle_show_next="n: toggle show next"
i18n_toggle_this_help="h: toggle this help"
i18n_game_over="Game over!"
while getopts ":l:h" opt; do
case ${opt} in
l )
user_lang=${OPTARG}
[ "$user_lang" != "english" ] && { # check if user give english
[ -r "$script_dir/lang/$user_lang.sh" ] || { # check if language file is exist
echo "$script_dir/lang/$user_lang.sh doesn't exist"
exit 1
}
. $script_dir/lang/$user_lang.sh || { # load language file
echo "Failed to load $script_dir/lang/$user_lang.sh"
exit 1
}
}
;;
h ) usage ;;
: )
echo -e "Missing option argument for -$OPTARG\n" # if value of -l not given
usage
exit 1
;;
esac
done
# END OF LANGUAGE LINES
# Those are commands sent to controller by key press processing code
# In controller they are used as index to retrieve actual functuon from array
QUIT=0
RIGHT=1
LEFT=2
ROTATE=3
DOWN=4
DROP=5
TOGGLE_HELP=6
TOGGLE_NEXT=7
TOGGLE_COLOR=8
DELAY=1000 # initial delay between piece movements (milliseconds)
DELAY_FACTOR="8/10" # this value controls delay decrease for each level up
# color codes
RED=1
GREEN=2
YELLOW=3
BLUE=4
FUCHSIA=5
CYAN=6
WHITE=7
# Location and size of playfield, color of border
PLAYFIELD_W=10
PLAYFIELD_H=20
PLAYFIELD_X=30
PLAYFIELD_Y=1
BORDER_COLOR=$YELLOW
# Location and color of score information
SCORE_X=1
SCORE_Y=2
SCORE_COLOR=$GREEN
# Location and color of help information
HELP_X=58
HELP_Y=1
HELP_COLOR=$CYAN
# Next piece location
NEXT_X=14
NEXT_Y=11
# Location of "game over" in the end of the game
GAMEOVER_X=1
GAMEOVER_Y=$((PLAYFIELD_H + 3))
# Intervals after which game level (and game speed) is increased
LEVEL_UP=20
colors=($RED $GREEN $YELLOW $BLUE $FUCHSIA $CYAN $WHITE)
use_color=1 # 1 if we use color, 0 if not
empty_cell=" ." # how we draw empty cell
filled_cell="[]" # how we draw filled cell
score=0 # score variable initialization
level=1 # level variable initialization
lines_completed=0 # completed lines counter initialization
# screen_buffer is variable, that accumulates all screen changes
# this variable is printed in controller once per game cycle
screen_buffer=""
puts() {
screen_buffer+=${1}
}
flush_screen() {
echo -ne "$screen_buffer"
screen_buffer=""
}
# move cursor to (x,y) and print string
# (1,1) is upper left corner of the screen
xyprint() {
puts "\e[${2};${1}H${3}"
}
show_cursor() {
echo -ne "\e[?25h"
}
hide_cursor() {
echo -ne "\e[?25l"
}
# foreground color
set_fg() {
((use_color)) && puts "\e[3${1}m"
}
# background color
set_bg() {
((use_color)) && puts "\e[4${1}m"
}
reset_colors() {
puts "\e[0m"
}
set_bold() {
puts "\e[1m"
}
# playfield is an array, each row is represented by integer
# each cell occupies 3 bits (empty if 0, other values encode color)
redraw_playfield() {
local x y color
for ((y = 0; y < PLAYFIELD_H; y++)) {
xyprint $PLAYFIELD_X $((PLAYFIELD_Y + y)) ""
for ((x = 0; x < PLAYFIELD_W; x++)) {
((color = ((playfield[y] >> (x * 3)) & 7)))
if ((color == 0)) ; then
puts "$empty_cell"
else
set_fg $color
set_bg $color
puts "$filled_cell"
reset_colors
fi
}
}
}
update_score() {
# Arguments: 1 - number of completed lines
((lines_completed += $1))
# Unfortunately I don't know scoring algorithm of original tetris
# Here score is incremented with squared number of lines completed
# this seems reasonable since it takes more efforts to complete several lines at once
((score += ($1 * $1)))
if (( score > LEVEL_UP * level)) ; then # if level should be increased
((level++)) # increment level
kill -SIGUSR1 $ticker_pid # and send SIGUSR1 signal to ticker process (please see ticker() function for more details)
fi
set_bold
set_fg $SCORE_COLOR
xyprint $SCORE_X $SCORE_Y "$i18n_lines_completed$lines_completed"
xyprint $SCORE_X $((SCORE_Y + 1)) "$i18n_level$level"
xyprint $SCORE_X $((SCORE_Y + 2)) "$i18n_score$score"
reset_colors
}
help=(
"$i18n_use_cursor_keys"
"$i18n_or"
"$i18n_rotate"
"$i18n_left_right"
"$i18n_drop"
"$i18n_quit"
"$i18n_toggle_color"
"$i18n_toggle_show_next"
"$i18n_toggle_this_help"
)
help_on=1 # if this flag is 1 help is shown
draw_help() {
local i s
set_bold
set_fg $HELP_COLOR
for ((i = 0; i < ${#help[@]}; i++ )) {
# ternary assignment: if help_on is 1 use string as is, otherwise substitute all characters with spaces
((help_on)) && s="${help[i]}" || s="${help[i]//?/ }"
xyprint $HELP_X $((HELP_Y + i)) "$s"
}
reset_colors
}
toggle_help() {
((help_on ^= 1))
draw_help
}
# this array holds all possible pieces that can be used in the game
# each piece consists of 4 cells numbered from 0x0 to 0xf:
# 0123
# 4567
# 89ab
# cdef
# each string is sequence of cells for different orientations
# depending on piece symmetry there can be 1, 2 or 4 orientations
# relative coordinates are calculated as follows:
# x=((cell & 3)); y=((cell >> 2))
piece_data=(
"1256" # square
"159d4567" # line
"45120459" # s
"01561548" # z
"159a845601592654" # l
"159804562159a654" # inverted l
"1456159645694159" # t
)
draw_piece() {
# Arguments:
# 1 - x, 2 - y, 3 - type, 4 - rotation, 5 - cell content
local i x y c
# loop through piece cells: 4 cells, each has 2 coordinates
for ((i = 0; i < 4; i++)) {
c=0x${piece_data[$3]:$((i + $4 * 4)):1}
# relative coordinates are retrieved based on orientation and added to absolute coordinates
((x = $1 + (c & 3) * 2))
((y = $2 + (c >> 2)))
xyprint $x $y "$5"
}
}
next_piece=0
next_piece_rotation=0
next_piece_color=0
next_on=1 # if this flag is 1 next piece is shown
draw_next() {
# Argument: 1 - visibility (0 - no, 1 - yes), if this argument is skipped $next_on is used
local s="$filled_cell" visible=${1:-$next_on}
((visible)) && {
set_fg $next_piece_color
set_bg $next_piece_color
} || {
s="${s//?/ }"
}
draw_piece $NEXT_X $NEXT_Y $next_piece $next_piece_rotation "$s"
reset_colors
}
toggle_next() {
draw_next $((next_on ^= 1))
}
draw_current() {
# Arguments: 1 - string to draw single cell
# factor 2 for x because each cell is 2 characters wide
draw_piece $((current_piece_x * 2 + PLAYFIELD_X)) $((current_piece_y + PLAYFIELD_Y)) $current_piece $current_piece_rotation "$1"
}
show_current() {
set_fg $current_piece_color
set_bg $current_piece_color
draw_current "${filled_cell}"
reset_colors
}
clear_current() {
draw_current "${empty_cell}"
}
new_piece_location_ok() {
# Arguments: 1 - new x coordinate of the piece, 2 - new y coordinate of the piece
# test if piece can be moved to new location
local i c x y x_test=$1 y_test=$2
for ((i = 0; i < 4; i++)) {
c=0x${piece_data[$current_piece]:$((i + current_piece_rotation * 4)):1}
# new x and y coordinates of piece cell
((y = (c >> 2) + y_test))
((x = (c & 3) + x_test))
((y < 0 || y >= PLAYFIELD_H || x < 0 || x >= PLAYFIELD_W )) && return 1 # check if we are out of the play field
((((playfield[y] >> (x * 3)) & 7) != 0 )) && return 1 # check if location is already ocupied
}
return 0
}
get_random_next() {
# next piece becomes current
current_piece=$next_piece
current_piece_rotation=$next_piece_rotation
current_piece_color=$next_piece_color
# place current at the top of play field, approximately at the center
((current_piece_x = (PLAYFIELD_W - 4) / 2))
((current_piece_y = 0))
# check if piece can be placed at this location, if not - game over
new_piece_location_ok $current_piece_x $current_piece_y || exit
show_current
draw_next 0
# now let's get next piece
((next_piece = RANDOM % ${#piece_data[@]}))
((next_piece_rotation = RANDOM % (${#piece_data[$next_piece]} / 4)))
((next_piece_color = colors[RANDOM % ${#colors[@]}]))
draw_next
}
draw_border() {
local i x1 x2 y
set_bold
set_fg $BORDER_COLOR
((x1 = PLAYFIELD_X - 2)) # 2 here is because border is 2 characters thick
((x2 = PLAYFIELD_X + PLAYFIELD_W * 2)) # 2 here is because each cell on play field is 2 characters wide
for ((i = 0; i < PLAYFIELD_H + 1; i++)) {
((y = i + PLAYFIELD_Y))
xyprint $x1 $y "<|"
xyprint $x2 $y "|>"
}
((y = PLAYFIELD_Y + PLAYFIELD_H))
for ((i = 0; i < PLAYFIELD_W; i++)) {
((x1 = i * 2 + PLAYFIELD_X)) # 2 here is because each cell on play field is 2 characters wide
xyprint $x1 $y '=='
xyprint $x1 $((y + 1)) "\/"
}
reset_colors
}
redraw_screen() {
draw_next
update_score 0
draw_help
draw_border
redraw_playfield
show_current
}
toggle_color() {
((use_color ^= 1))
redraw_screen
}
init() {
local i
# playfield is initialized with -1s (empty cells)
for ((i = 0; i < PLAYFIELD_H; i++)) {
playfield[$i]=0
}
clear
hide_cursor
get_random_next
get_random_next
redraw_screen
flush_screen
}
# this function updates occupied cells in playfield array after piece is dropped
flatten_playfield() {
local i c x y
for ((i = 0; i < 4; i++)) {
c=0x${piece_data[$current_piece]:$((i + current_piece_rotation * 4)):1}
((y = (c >> 2) + current_piece_y))
((x = (c & 3) + current_piece_x))
((playfield[y] |= (current_piece_color << (x * 3))))
}
}
# this function takes row number as argument and checks if has empty cells
line_full() {
local row=${playfield[$1]} x
for ((x = 0; x < PLAYFIELD_W; x++)) {
((((row >> (x * 3)) & 7) == 0)) && return 1
}
return 0
}
# this function goes through playfield array and eliminates lines without empty cells
process_complete_lines() {
local y complete_lines=0
for ((y = PLAYFIELD_H - 1; y > -1; y--)) {
line_full $y && {
unset playfield[$y]
((complete_lines++))
}
}
for ((y = 0; y < complete_lines; y++)) {
playfield=(0 ${playfield[@]})
}
return $complete_lines
}
process_fallen_piece() {
flatten_playfield
process_complete_lines && return
update_score $?
redraw_playfield
}
move_piece() {
# arguments: 1 - new x coordinate, 2 - new y coordinate
# moves the piece to the new location if possible
if new_piece_location_ok $1 $2 ; then # if new location is ok
clear_current # let's wipe out piece current location
current_piece_x=$1 # update x ...
current_piece_y=$2 # ... and y of new location
show_current # and draw piece in new location
return 0 # nothing more to do here
fi # if we could not move piece to new location
(($2 == current_piece_y)) && return 0 # and this was not horizontal move
process_fallen_piece # let's finalize this piece
get_random_next # and start the new one
return 1
}
cmd_right() {
move_piece $((current_piece_x + 1)) $current_piece_y
}
cmd_left() {
move_piece $((current_piece_x - 1)) $current_piece_y
}
cmd_rotate() {
local available_rotations old_rotation new_rotation
available_rotations=$((${#piece_data[$current_piece]} / 4)) # number of orientations for this piece
old_rotation=$current_piece_rotation # preserve current orientation
new_rotation=$(((old_rotation + 1) % available_rotations)) # calculate new orientation
current_piece_rotation=$new_rotation # set orientation to new
if new_piece_location_ok $current_piece_x $current_piece_y ; then # check if new orientation is ok
current_piece_rotation=$old_rotation # if yes - restore old orientation
clear_current # clear piece image
current_piece_rotation=$new_rotation # set new orientation
show_current # draw piece with new orientation
else # if new orientation is not ok
current_piece_rotation=$old_rotation # restore old orientation
fi
}
cmd_down() {
move_piece $current_piece_x $((current_piece_y + 1))
}
cmd_drop() {
# move piece all way down
# this is example of do..while loop in bash
# loop body is empty
# loop condition is done at least once
# loop runs until loop condition would return non zero exit code
while move_piece $current_piece_x $((current_piece_y + 1)) ; do : ; done
}
stty_g=$(stty -g) # let's save terminal state ...
at_exit() {
kill $ticker_pid # let's kill ticker process ...
xyprint $GAMEOVER_X $GAMEOVER_Y "$i18n_game_over"
echo -e "$screen_buffer" # ... print final message ...
show_cursor
stty $stty_g # ... and restore terminal state
}
# this function runs in separate process
# it sends SIGUSR1 signals to the main process with appropriate delay
ticker() {
# on SIGUSR1 delay should be decreased, this happens during level ups
trap 'DELAY=$(($DELAY * $DELAY_FACTOR))' SIGUSR1
trap exit TERM
while sleep $((DELAY / 1000)).$(printf "%03d" $((DELAY % 1000))); do kill -SIGUSR1 $1 || exit; done 2>/dev/null
}
do_tick() {
$tick_blocked && tick_scheduled=true && return
cmd_down
flush_screen
}
main() {
local -u key a='' b='' esc_ch=$'\x1b'
local cmd
# commands is associative array, which maps pressed keys to commands, sent to controller
local -A commands=([A]=cmd_rotate [C]=cmd_right [D]=cmd_left
[_S]=cmd_rotate [_A]=cmd_left [_D]=cmd_right
[_]=cmd_drop [_Q]=exit [_H]=toggle_help [_N]=toggle_next [_C]=toggle_color)
trap at_exit EXIT
trap do_tick SIGUSR1
init
ticker $$ &
ticker_pid=$!
tick_blocked=false
tick_scheduled=false
while read -s -n 1 key ; do
case "$a$b$key" in
"${esc_ch}["[ACD]) cmd=${commands[$key]} ;; # cursor key
*${esc_ch}${esc_ch}) cmd=exit ;; # exit on 2 escapes
*) cmd=${commands[_$key]:-} ;; # regular key. If space was pressed $key is empty
esac
a=$b # preserve previous keys
b=$key
[ -n "$cmd" ] && {
tick_blocked=true
$cmd
tick_blocked=false
$tick_scheduled && tick_scheduled=false && do_tick
flush_screen
}
done
}
main