I've already done some code, like I have a grid where I can freely move. But the behavior I want is to make the "road" move by itself while the "car" can move freely on the board to avoid some "rocks" placed randomly.
I want to create some kind of slot machine effect, when the start of the row is connected to it's end and it just endlessly scrolls. The move_up and move_down functions are supposed to be some kind of acceleration, but for now, it's just a simple rewrite from other movement functions.
I would appreciate your help, and if you can, please explain how exactly you achieved that results. Here is my code:
#!/bin/bash
# Constants
declare -A GRID
GRID_WIDTH=21
GRID_HEIGHT=15
CAR="▲"
ROCK="*"
CLEAR_SCREEN='\033[H\033[J' # Clear the screen
# Initialize game variables
car_x=$((GRID_WIDTH / 2))
car_y=$((GRID_HEIGHT - 2))
init_grid() {
# Initialize the grid
for ((i=0; i < GRID_HEIGHT; i++)); do
for ((j=0; j < GRID_WIDTH; j++)); do
GRID[$i,$j]=" "
done
done
GRID[0,0]="+"
GRID[0,$((GRID_WIDTH-1))]="+"
GRID[$((GRID_HEIGHT-1)),0]="+"
GRID[$((GRID_HEIGHT-1)),$((GRID_WIDTH-1))]="+"
GRID[$((GRID_HEIGHT-2)),$car_x]=$CAR
GRID[5,5]=$ROCK
for ((i=1; i < GRID_HEIGHT-1; i++)); do
GRID[$i,0]="|"
GRID[$i,$((GRID_WIDTH-1))]="|"
done
for ((i=1; i < GRID_WIDTH-1; i++)); do
GRID[0,$i]="-"
GRID[$((GRID_HEIGHT-1)),$i]="-"
done
}
draw_grid() {
# Draw the grid
echo -e "$CLEAR_SCREEN"
for ((i=0; i < GRID_HEIGHT; i++)); do
for ((j=0; j < GRID_WIDTH; j++)); do
printf "%s" "${GRID[$i,$j]}"
done
printf "\n"
done
}
scroll_grid() {
# Scroll the grid
for ((i=1; i < GRID_HEIGHT-1; i++)); do
for ((j=1; j < GRID_WIDTH-1; j++)); do
GRID[$((i-1)),$j]=${GRID[$i,$j]}
done
done
}
move_left() {
if ((car_x > 1)); then
GRID[$car_y,$car_x]=" "
((car_x--))
GRID[$car_y,$car_x]=$CAR
fi
}
move_right() {
if ((car_x < GRID_WIDTH-2)); then
GRID[$car_y,$car_x]=" "
((car_x++))
GRID[$car_y,$car_x]=$CAR
fi
}
move_up() {
if ((car_y > 1)); then
GRID[$car_y,$car_x]=" "
((car_y--))
GRID[$car_y,$car_x]=$CAR
fi
}
move_down() {
if ((car_y < GRID_HEIGHT-2)); then
GRID[$car_y,$car_x]=" "
((car_y++))
GRID[$car_y,$car_x]=$CAR
fi
}
init_grid
while true; do
draw_grid
# sleep 0.5
# scroll_grid
read -rsn1 move
case "$move" in
"a") move_left ;;
"d") move_right ;;
"w") move_up ;;
"s") move_down ;;
"q") exit ;;
esac
done