[Tut] Python Snake Made Easy - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Snake Made Easy (/thread-101022.html) |
[Tut] Python Snake Made Easy - xSicKxBot - 04-25-2023 Python Snake Made Easy <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{"align":"left","id":"1315485","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","legendonly":"","readonly":"","score":"5","starsonly":"","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","title":"Python Snake Made Easy","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}'> <div class="kksr-stars"> <div class="kksr-stars-inactive"> <div class="kksr-star" data-star="1" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="2" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="3" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="4" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="5" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> <div class="kksr-stars-active" style="width: 142.5px;"> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> </div> <div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div> </p></div> <p>This code creates a simple Snake game using the Pygame library in Python. </p> <p>The game starts with a small snake moving around the screen, controlled by arrow keys, eating randomly placed food items. Each time the snake eats food, it grows longer, and the game gets faster. </p> <p>The game ends if the snake collides with itself or the screen borders, and the player’s goal is to keep the snake growing as long as possible.</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pygame import sys import random # Initialize pygame pygame.init() # Set screen dimensions WIDTH = 640 HEIGHT = 480 CELL_SIZE = 20 # Colors WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # Create the game screen screen = pygame.display.set_mode((WIDTH, HEIGHT)) # Set the game clock clock = pygame.time.Clock() def random_food_position(): return (random.randint(0, (WIDTH-CELL_SIZE)//CELL_SIZE) * CELL_SIZE, random.randint(0, (HEIGHT-CELL_SIZE)//CELL_SIZE) * CELL_SIZE) def draw_snake(snake_positions): for pos in snake_positions: pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], CELL_SIZE, CELL_SIZE)) def draw_food(food_position): pygame.draw.rect(screen, RED, pygame.Rect(food_position[0], food_position[1], CELL_SIZE, CELL_SIZE)) def main(): snake_positions = [(100, 100), (80, 100), (60, 100)] snake_direction = (20, 0) food_position = random_food_position() game_speed = 10 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and snake_direction != (0, 20): snake_direction = (0, -20) elif event.key == pygame.K_DOWN and snake_direction != (0, -20): snake_direction = (0, 20) elif event.key == pygame.K_LEFT and snake_direction != (20, 0): snake_direction = (-20, 0) elif event.key == pygame.K_RIGHT and snake_direction != (-20, 0): snake_direction = (20, 0) new_head = (snake_positions[0][0] + snake_direction[0], snake_positions[0][1] + snake_direction[1]) if new_head in snake_positions or new_head[0] < 0 or new_head[0] >= WIDTH or new_head[1] < 0 or new_head[1] >= HEIGHT: break snake_positions.insert(0, new_head) if new_head == food_position: food_position = random_food_position() game_speed += 1 else: snake_positions.pop() screen.fill(WHITE) draw_snake(snake_positions) draw_food(food_position) pygame.display.update() clock.tick(game_speed) if __name__ == "__main__": main() </pre> <p>This simple implementation of the classic Snake game uses the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pygame-on-pycharm/" data-type="post" data-id="35078" target="_blank">Pygame library</a> in Python — here’s how I quickly lost in the game:</p> <div class="wp-block-image"> <figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="634" height="506" src="https://blog.finxter.com/wp-content/uploads/2023/04/snake_py.gif" alt="" class="wp-image-1315513"/></figure> </div> <p>Here’s a brief explanation of each part of the code:</p> <ol> <li>Import libraries: <ul> <li><code>pygame</code> for creating the game window and handling events, </li> <li><code>sys</code> for system-specific parameters and functions, and </li> <li><code>random</code> for generating random numbers.</li> </ul> </li> <li>Initialize <code>pygame</code> with <code>pygame.init()</code>.</li> <li>Set screen dimensions and cell size. The <code>WIDTH</code>, <code>HEIGHT</code>, and <code>CELL_SIZE</code> constants define the game window size and the size of each cell (both snake segments and food).</li> <li>Define color constants <code>WHITE</code>, <code>GREEN</code>, and <code>RED</code> as RGB tuples.</li> <li>Create the game screen with <code>pygame.display.set_mode((WIDTH, HEIGHT))</code>.</li> <li>Set the game clock with <code>pygame.time.Clock()</code> to control the game’s frame rate.</li> <li>Define the <code>random_food_position()</code> function to generate a random food position on the grid, ensuring it’s aligned with the <code>CELL_SIZE</code>.</li> <li>Define <code>draw_snake(snake_positions)</code> function to draw the snake’s body segments at their respective positions using green rectangles.</li> <li>Define <code>draw_food(food_position)</code> function to draw the food as a red rectangle at its position.</li> <li>Define the <code>main()</code> function, which contains the main game loop and logic. <ul> <li>Initialize the snake’s starting position, direction, food position, and game speed.</li> <li>The <code>while True</code> loop is the main game loop that runs indefinitely until the snake collides with itself or the screen borders.</li> <li>Handle events like closing the game window or changing the snake’s direction using arrow keys.</li> <li>Update the snake’s position based on its current direction.</li> <li>Check for collisions with itself or the screen borders, breaking the loop if a collision occurs.</li> <li>If the snake’s head is at the food position, generate a new food position and increase the game speed. Otherwise, remove the last snake segment.</li> <li>Update the game display by filling the screen with a white background, drawing the snake and food, and updating the display.</li> <li>Control the game speed using <code>clock.tick(game_speed)</code>.</li> </ul> </li> <li>Run the <code>main()</code> function when the script is executed by checking if <code>__name__ == "__main__"</code>.</li> </ol> </div> https://www.sickgaming.net/blog/2023/04/24/python-snake-made-easy/ |