DEV Community

Beta Shorts
Beta Shorts

Posted on

How to Build a Snake Game in Bash (Yes, Really!)

Most people use Bash for automation, scripting, and server management—but have you ever thought about using it to build a game?

At first, it sounds impossible. Bash lacks graphics support and isn't designed for real-time interactivity. But with clever workarounds, you can create a fully playable Snake game right in your terminal.

Let's break down the core logic behind a Bash-based Snake game and how you can start building it yourself.


Can You Really Code a Game in Bash?

Yes, but it’s a challenge.

Unlike Python or C, Bash has no built-in game libraries. You need to manually control input, timing, and rendering using simple shell commands.

Here’s what makes it work:

  • Real-time input handling (using read in raw mode)
  • Game loop simulation (using while true; do ...; sleep x; done)
  • Terminal-based rendering (using tput and printf)

Step 1: Setting Up the Game Grid

Bash doesn’t have a GUI, so the game board is represented using characters.

Basic Board Representation

Imagine a 10x10 grid in the terminal:

##########
#        #
#        #
#   @    #
#        #
##########
Enter fullscreen mode Exit fullscreen mode

Here’s a basic script to draw a static grid:

clear
for i in {1..10}; do
    for j in {1..10}; do
        if [[ $i -eq 1 || $i -eq 10 || $j -eq 1 || $j -eq 10 ]]; then
            echo -n "#"
        else
            echo -n " "
        fi
    done
    echo
done
Enter fullscreen mode Exit fullscreen mode

🔹 What’s happening?

  • Loops create rows and columns
  • Borders (#) are drawn at the edges
  • Spaces (" ") are the playable area

Step 2: Moving the Snake

Handling real-time input is tricky in Bash. You can’t just use read because it waits for input. Instead, we use:

stty -echo -icanon time 0 min 0
Enter fullscreen mode Exit fullscreen mode

This puts the terminal in raw mode, letting us read one key at a time.

Now, we can move the snake using key presses:

while true; do
    read -n 1 input
    case "$input" in
        w) direction="UP" ;;
        s) direction="DOWN" ;;
        a) direction="LEFT" ;;
        d) direction="RIGHT" ;;
    esac
done
Enter fullscreen mode Exit fullscreen mode

🔹 Why it works:

  • read -n 1 reads one character at a time
  • case changes the direction variable based on input

Step 3: Making the Snake Grow

Each time the snake eats food, we increase its length. Instead of storing a graphical representation, we store coordinates:

snake=("3 5" "3 6" "3 7")  # List of x,y positions
Enter fullscreen mode Exit fullscreen mode

Every time it moves:

  1. Add a new head
  2. Remove the tail (unless it eats food)

Here’s an example update logic:

new_head="$((x+dx)) $((y+dy))"
snake=("$new_head" "${snake[@]:0:${#snake[@]}-1}")  
Enter fullscreen mode Exit fullscreen mode

🔹 Why it works:

  • Moves head forward by modifying coordinates
  • Removes the last piece (tail) to keep the length constant

Step 4: Collision Detection (Don’t Crash!)

The game ends if the snake crashes into itself or the wall.

To check for self-collision:

if [[ " ${snake[@]} " =~ " $new_head " ]]; then
    echo "Game Over!"
    exit 0
fi
Enter fullscreen mode Exit fullscreen mode

🔹 Why it works:

  • Converts snake[@] to a string and checks if new_head exists inside it.

For wall collision, add a check:

if [[ $x -le 1 || $x -ge 10 || $y -le 1 || $y -ge 10 ]]; then
    echo "Crashed into the wall!"
    exit 0
fi
Enter fullscreen mode Exit fullscreen mode

🔹 Why it works:

  • If x or y reaches the grid boundary, the game ends.

Step 5: Adding Food and Score

A random food spawn looks like this:

food_x=$(( RANDOM % 8 + 2 ))
food_y=$(( RANDOM % 8 + 2 ))
Enter fullscreen mode Exit fullscreen mode

When the snake’s head reaches the food:

  1. Increase the length
  2. Generate new food
if [[ "$new_head" == "$food_x $food_y" ]]; then
    snake+=("$new_head")  # Grow the snake
    food_x=$(( RANDOM % 8 + 2 ))
    food_y=$(( RANDOM % 8 + 2 ))
fi
Enter fullscreen mode Exit fullscreen mode

🔹 Why it works:

  • Food respawns in a random location
  • Snake grows by adding a new segment

Challenges and Enhancements

If you’ve followed along, you have the logic for a simple Bash Snake game. But here are some challenges to improve it:

Add a scoring system

Make the snake move continuously

Increase speed as the game progresses

Store high scores in a file


Is Bash the Best Choice for a Snake Game?

🚀 Yes, for a challenge.

  • Bash wasn’t designed for games, but it’s a great way to learn scripting logic.

🛑 No, for complex games.

  • Bash struggles with real-time interaction. Python or C is better for performance.

Final Thoughts: Can You Build Games in Bash?

Bash isn’t made for game development, but that’s what makes it fun.

  • If you love problem-solving, this is a great exercise.
  • If you want high-performance, Bash isn’t the best option.

🎯 Challenge: Try building your own Snake game in Bash! Drop a comment if you get it working!


🚀 Master Bash Faster with This Cheat Book!

Want to boost your productivity and avoid Googling the same Bash commands over and over? My Bash Scripting Cheat Book is the ultimate quick-reference guide for everyday tasks like:

  • File handling, process management, and networking
  • Regex, text manipulation, and troubleshooting techniques
  • Essential Bash utilities (jq, find, grep, awk) explained concisely

👉 Get the Bash Cheat Sheet for just $3.99

What’s Inside?

✔️ Structured reference of 100+ essential Bash commands

✔️ Clear explanations with practical use cases

✔️ Formatted PDF for easy offline use


Top comments (0)