{"id":82602,"date":"2026-03-16T18:51:22","date_gmt":"2026-03-16T15:51:22","guid":{"rendered":"https:\/\/cloudspinx.com\/?p=82602"},"modified":"2026-03-16T18:51:22","modified_gmt":"2026-03-16T15:51:22","slug":"how-to-create-snake-game-in-python","status":"publish","type":"post","link":"https:\/\/computingforgeeks.com\/how-to-create-snake-game-in-python\/","title":{"rendered":"How To Create Snake Game in Python"},"content":{"rendered":"\n<p>In this short guide we will show you how to make a snake game for playing in your terminal using Python. The main prerequisites for this is Python installation in the system. At the end of the tutorial, the application should run without any additional steps.<\/p>\n\n\n\n<p>To begin, verify that <a href=\"https:\/\/computingforgeeks.com\/?s=install+Python\" target=\"_blank\" rel=\"noreferrer noopener\">Python is installed<\/a> and functioning correctly:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ <mark style=\"background-color:rgba(0, 0, 0, 0);color:#ff6900\" class=\"has-inline-color\">python3 --version<\/mark>\nPython 3.13.1<\/code><\/pre>\n\n\n\n<p>Now let&#8217;s create a directory for our snake game<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mkdir -p ~\/snake_game &amp;&amp; cd ~\/snake_game<\/code><\/pre>\n\n\n\n<p>Now we&#8217;ll create a snake game implementation using Python&#8217;s<a href=\"https:\/\/docs.python.org\/3\/howto\/curses.html\" target=\"_blank\" rel=\"noreferrer noopener\"> curses library<\/a>. The game will include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Snake movement using arrow keys<\/li>\n\n\n\n<li>Food generation<\/li>\n\n\n\n<li>Score tracking<\/li>\n\n\n\n<li>Game over conditions<\/li>\n\n\n\n<li>Simple UI<\/li>\n<\/ul>\n\n\n\n<p>The game will be terminal-based and include features like arrow key movement, score display, random food generation, collision detection, and game restart capabilities.<\/p>\n\n\n\n<p>To start, add a <code>snake_game.py<\/code> file to the <em>snake_game<\/em> folder created earlier.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>vim <span style=\"background-color: initial; text-align: initial; font-weight: inherit;\">snake_game.py<\/span><\/code><\/pre>\n\n\n\n<p>Paste the following contents into the file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/env python3\nimport curses\nimport random\nimport time\n\ndef main(stdscr):\n    # Setup initial game state\n    curses.curs_set(0)  # Hide cursor\n    stdscr.timeout(100)  # Set input timeout (controls game speed)\n    \n    # Get terminal dimensions\n    height, width = stdscr.getmaxyx()\n    \n    # Check if terminal is large enough\n    if height &lt; 10 or width &lt; 30:\n        stdscr.clear()\n        stdscr.addstr(0, 0, \"Terminal too small. Please resize.\")\n        stdscr.refresh()\n        stdscr.getch()\n        return\n    \n    # Create color pairs\n    curses.start_color()\n    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)  # Snake\n    curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)    # Food\n    curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK) # Score\n    \n    # Game boundaries (leave space for borders and score)\n    game_height = height - 2\n    game_width = width - 2\n    \n    # Display welcome message and instructions\n    show_instructions(stdscr)\n    \n    while True:\n        # Game variables\n        snake = &#91;&#91;game_height \/\/ 2, game_width \/\/ 4]]  # Start with a single segment\n        direction = curses.KEY_RIGHT\n        food = generate_food(snake, game_height, game_width)\n        score = 0\n        \n        # Draw initial game state\n        draw_game(stdscr, snake, food, score, game_height, game_width)\n        \n        game_over = False\n        while not game_over:\n            # Get user input\n            key = stdscr.getch()\n            \n            # Process key press\n            if key == ord('q'):\n                return  # Quit game\n            elif key in &#91;curses.KEY_UP, curses.KEY_DOWN, curses.KEY_LEFT, curses.KEY_RIGHT]:\n                # Prevent 180-degree turns\n                if (key == curses.KEY_UP and direction != curses.KEY_DOWN) or \\\n                   (key == curses.KEY_DOWN and direction != curses.KEY_UP) or \\\n                   (key == curses.KEY_LEFT and direction != curses.KEY_RIGHT) or \\\n                   (key == curses.KEY_RIGHT and direction != curses.KEY_LEFT):\n                    direction = key\n            \n            # Calculate new head position\n            head = snake&#91;0].copy()\n            if direction == curses.KEY_UP:\n                head&#91;0] -= 1\n            elif direction == curses.KEY_DOWN:\n                head&#91;0] += 1\n            elif direction == curses.KEY_LEFT:\n                head&#91;1] -= 1\n            elif direction == curses.KEY_RIGHT:\n                head&#91;1] += 1\n            \n            # Add new head\n            snake.insert(0, head)\n            \n            # Check if snake eats food\n            if snake&#91;0] == food:\n                food = generate_food(snake, game_height, game_width)\n                score += 10\n                # Speed up game slightly after eating (decrease timeout value)\n                new_timeout = max(50, 100 - (score \/\/ 20))\n                stdscr.timeout(new_timeout)\n            else:\n                # Remove tail if no food eaten\n                snake.pop()\n            \n            # Check for collisions with boundaries\n            if (snake&#91;0]&#91;0] &lt;= 0 or snake&#91;0]&#91;0] >= game_height or \n                snake&#91;0]&#91;1] &lt;= 0 or snake&#91;0]&#91;1] >= game_width):\n                game_over = True\n            \n            # Check for collisions with self\n            if snake&#91;0] in snake&#91;1:]:\n                game_over = True\n            \n            # Draw game state\n            draw_game(stdscr, snake, food, score, game_height, game_width)\n        \n        # Game over screen\n        if show_game_over(stdscr, score) == ord('r'):\n            continue  # Restart game\n        else:\n            break  # Exit game\n\ndef draw_game(stdscr, snake, food, score, height, width):\n    \"\"\"Draw the game state on the screen\"\"\"\n    stdscr.clear()\n    \n    # Draw borders\n    for i in range(width + 1):\n        stdscr.addch(0, i, '#')\n        stdscr.addch(height, i, '#')\n    for i in range(height + 1):\n        stdscr.addch(i, 0, '#')\n        stdscr.addch(i, width, '#')\n    \n    # Draw snake\n    for i, segment in enumerate(snake):\n        char = '@' if i == 0 else 'O'  # Different char for head\n        stdscr.attron(curses.color_pair(1))\n        stdscr.addch(segment&#91;0], segment&#91;1], char)\n        stdscr.attroff(curses.color_pair(1))\n    \n    # Draw food\n    stdscr.attron(curses.color_pair(2))\n    stdscr.addch(food&#91;0], food&#91;1], '*')\n    stdscr.attroff(curses.color_pair(2))\n    \n    # Draw score\n    score_text = f\"Score: {score}\"\n    stdscr.attron(curses.color_pair(3))\n    stdscr.addstr(0, width - len(score_text) - 1, score_text)\n    stdscr.attroff(curses.color_pair(3))\n    \n    stdscr.refresh()\n\ndef generate_food(snake, height, width):\n    \"\"\"Generate food at a random position not occupied by the snake\"\"\"\n    while True:\n        food = &#91;random.randint(1, height - 1), random.randint(1, width - 1)]\n        if food not in snake:\n            return food\n\ndef show_instructions(stdscr):\n    \"\"\"Display game instructions to the player\"\"\"\n    stdscr.clear()\n    height, width = stdscr.getmaxyx()\n    \n    title = \"SNAKE GAME\"\n    stdscr.attron(curses.A_BOLD)\n    stdscr.addstr(height \/\/ 4, (width - len(title)) \/\/ 2, title)\n    stdscr.attroff(curses.A_BOLD)\n    \n    instructions = &#91;\n        \"Use arrow keys to move the snake\",\n        \"Eat food (*) to grow and increase your score\",\n        \"Avoid hitting the walls or yourself\",\n        \"Press 'q' to quit at any time\",\n        \"Press 'r' to restart after game over\",\n        \"\",\n        \"Press any key to start...\"\n    ]\n    \n    for i, line in enumerate(instructions):\n        stdscr.addstr(height \/\/ 3 + i + 1, (width - len(line)) \/\/ 2, line)\n    \n    stdscr.refresh()\n    stdscr.getch()\n\ndef show_game_over(stdscr, score):\n    \"\"\"Display game over screen and return key pressed\"\"\"\n    stdscr.clear()\n    height, width = stdscr.getmaxyx()\n    \n    game_over_text = \"GAME OVER\"\n    stdscr.attron(curses.A_BOLD)\n    stdscr.addstr(height \/\/ 3, (width - len(game_over_text)) \/\/ 2, game_over_text)\n    stdscr.attroff(curses.A_BOLD)\n    \n    score_text = f\"Your score: {score}\"\n    stdscr.addstr(height \/\/ 3 + 2, (width - len(score_text)) \/\/ 2, score_text)\n    \n    restart_text = \"Press 'r' to restart or 'q' to quit\"\n    stdscr.addstr(height \/\/ 3 + 4, (width - len(restart_text)) \/\/ 2, restart_text)\n    \n    stdscr.refresh()\n    \n    # Wait for 'r' or 'q' key\n    while True:\n        key = stdscr.getch()\n        if key in &#91;ord('r'), ord('q')]:\n            return key\n\nif __name__ == \"__main__\":\n    # Initialize curses and start game\n    try:\n        curses.wrapper(main)\n    except KeyboardInterrupt:\n        # Handle Ctrl+C gracefully\n        pass\n    finally:\n        # Ensure terminal is reset properly\n        curses.endwin()\n        print(\"Thanks for playing Snake Game!\")<\/code><\/pre>\n\n\n\n<p>Make the file executable:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>chmod +x ~\/snake_game\/snake_game.py<\/code><\/pre>\n\n\n\n<p>The game is ready! It includes the following features:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Arrow key controls<\/li>\n\n\n\n<li>Score tracking<\/li>\n\n\n\n<li>Food collection<\/li>\n\n\n\n<li>Collision detection<\/li>\n\n\n\n<li>Color display<\/li>\n\n\n\n<li>Game over screen with restart option<\/li>\n\n\n\n<li>Clear instructions<\/li>\n<\/ul>\n\n\n\n<p>Here\u2019s how you can play it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>~\/snake_game\/snake_game.py<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use arrow keys (<strong>\u2191,\u2193,\u2190,\u2192<\/strong>) to control the snake<\/li>\n\n\n\n<li>Collect the red &#8216;<strong>*<\/strong>&#8216; symbols to grow and increase your score<\/li>\n\n\n\n<li>Avoid hitting the walls or your own tail<\/li>\n\n\n\n<li>Press &#8216;<strong>q<\/strong>&#8216; to quit at any time<\/li>\n\n\n\n<li>If you lose, press &#8216;<strong>r<\/strong>&#8216; to restart or &#8216;<strong>q<\/strong>&#8216; to quit<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"600\" src=\"https:\/\/computingforgeeks.com\/wp-content\/uploads\/2025\/05\/snake-game-scaled-1-1024x600.png\" alt=\"\" class=\"wp-image-82624\" title=\"\" srcset=\"https:\/\/computingforgeeks.com\/wp-content\/uploads\/2025\/05\/snake-game-scaled-1-1024x600.png 1024w, https:\/\/computingforgeeks.com\/wp-content\/uploads\/2025\/05\/snake-game-scaled-1-300x176.png 300w, https:\/\/computingforgeeks.com\/wp-content\/uploads\/2025\/05\/snake-game-scaled-1-768x450.png 768w, https:\/\/computingforgeeks.com\/wp-content\/uploads\/2025\/05\/snake-game-scaled-1-1536x899.png 1536w, https:\/\/computingforgeeks.com\/wp-content\/uploads\/2025\/05\/snake-game-scaled-1-2048x1199.png 2048w, https:\/\/computingforgeeks.com\/wp-content\/uploads\/2025\/05\/snake-game-scaled-1-717x420.png 717w, https:\/\/computingforgeeks.com\/wp-content\/uploads\/2025\/05\/snake-game-scaled-1-696x408.png 696w, https:\/\/computingforgeeks.com\/wp-content\/uploads\/2025\/05\/snake-game-scaled-1-1068x625.png 1068w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>On quitting you will get the message:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Thanks for playing Snake Game!<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>In this short guide we will show you how to make a snake game for playing in your terminal using Python. The main prerequisites for this is Python installation in the system. At the end of the tutorial, the application should run without any additional steps. To begin, verify that Python is installed and functioning &#8230; <a title=\"How To Create Snake Game in Python\" class=\"read-more\" href=\"https:\/\/computingforgeeks.com\/how-to-create-snake-game-in-python\/\" aria-label=\"Read more about How To Create Snake Game in Python\">Read more<\/a><\/p>\n","protected":false},"author":3,"featured_media":82628,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[690,299],"tags":[],"class_list":["post-82602","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dev","category-how-to"],"_links":{"self":[{"href":"https:\/\/computingforgeeks.com\/wp-json\/wp\/v2\/posts\/82602","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/computingforgeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/computingforgeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/computingforgeeks.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/computingforgeeks.com\/wp-json\/wp\/v2\/comments?post=82602"}],"version-history":[{"count":0,"href":"https:\/\/computingforgeeks.com\/wp-json\/wp\/v2\/posts\/82602\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/computingforgeeks.com\/wp-json\/wp\/v2\/media\/82628"}],"wp:attachment":[{"href":"https:\/\/computingforgeeks.com\/wp-json\/wp\/v2\/media?parent=82602"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/computingforgeeks.com\/wp-json\/wp\/v2\/categories?post=82602"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/computingforgeeks.com\/wp-json\/wp\/v2\/tags?post=82602"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}