Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Snake Made Easy

#1
Python Snake Made Easy

5/5 – (1 vote)

This code creates a simple Snake game using the Pygame library in Python.

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.

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.

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()

This simple implementation of the classic Snake game uses the Pygame library in Python — here’s how I quickly lost in the game:


Here’s a brief explanation of each part of the code:

  1. Import libraries:
    • pygame for creating the game window and handling events,
    • sys for system-specific parameters and functions, and
    • random for generating random numbers.
  2. Initialize pygame with pygame.init().
  3. Set screen dimensions and cell size. The WIDTH, HEIGHT, and CELL_SIZE constants define the game window size and the size of each cell (both snake segments and food).
  4. Define color constants WHITE, GREEN, and RED as RGB tuples.
  5. Create the game screen with pygame.display.set_mode((WIDTH, HEIGHT)).
  6. Set the game clock with pygame.time.Clock() to control the game’s frame rate.
  7. Define the random_food_position() function to generate a random food position on the grid, ensuring it’s aligned with the CELL_SIZE.
  8. Define draw_snake(snake_positions) function to draw the snake’s body segments at their respective positions using green rectangles.
  9. Define draw_food(food_position) function to draw the food as a red rectangle at its position.
  10. Define the main() function, which contains the main game loop and logic.
    • Initialize the snake’s starting position, direction, food position, and game speed.
    • The while True loop is the main game loop that runs indefinitely until the snake collides with itself or the screen borders.
    • Handle events like closing the game window or changing the snake’s direction using arrow keys.
    • Update the snake’s position based on its current direction.
    • Check for collisions with itself or the screen borders, breaking the loop if a collision occurs.
    • 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.
    • Update the game display by filling the screen with a white background, drawing the snake and food, and updating the display.
    • Control the game speed using clock.tick(game_speed).
  11. Run the main() function when the script is executed by checking if __name__ == "__main__".


https://www.sickgaming.net/blog/2023/04/...made-easy/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python IndexError: Tuple Index Out of Range [Easy Fix] xSicKxBot 0 1,947 08-22-2023, 09:07 AM
Last Post: xSicKxBot
  [Tut] Python ? Put Legend Outside Plot ? – Easy Guide xSicKxBot 0 1,463 04-22-2023, 11:08 PM
Last Post: xSicKxBot
  [Tut] Easy Way to Update a Python Package with Pip Upgrade xSicKxBot 0 1,378 03-19-2023, 12:16 PM
Last Post: xSicKxBot
  [Tut] I Created My First DALL·E Image in Python OpenAI Using Four Easy Steps xSicKxBot 0 1,275 03-10-2023, 03:46 PM
Last Post: xSicKxBot
  [Tut] EzpzShell: An Easy-Peasy Python Script That Simplifies Revshell Creation xSicKxBot 0 1,342 02-11-2023, 10:30 AM
Last Post: xSicKxBot
  [Tut] Two Easy Ways to Encrypt and Decrypt Python Strings xSicKxBot 0 1,308 02-02-2023, 12:29 PM
Last Post: xSicKxBot
  [Tut] I Used These 3 Easy Steps to Create a Bitcoin Wallet in Python (Public/Private) xSicKxBot 0 1,220 01-29-2023, 02:51 AM
Last Post: xSicKxBot
  [Tut] OpenAI API – or How I Made My Python Code Intelligent xSicKxBot 0 1,277 01-25-2023, 06:53 AM
Last Post: xSicKxBot
  [Tut] Spectacular Titles: An Easy Python Project Generating Catchy Titles xSicKxBot 0 1,191 01-01-2023, 12:21 PM
Last Post: xSicKxBot
  [Tut] Python Generate HTML – 3 Easy Ways xSicKxBot 0 1,178 12-31-2022, 02:12 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016