θ―•δΈ€θ―•

#1
by Cran-May - opened
JWorld NLPark org

πŸ˜ƒ: implement snake game using pygame
πŸ€–: You can use Pygame library for implementing Snake Game, here is an example of how you could implement it:

import random   # Importing Python's built-in module 'random'. This will be used to generate the food position on screen randomly in each game loop iteration (FPS).   
from pygame import *     # Imports all modules from Pygame library. We use these for initializing and managing our window, sprites etc., 
init()      # Initializes PyGame module  

# Set up some constants:
WIDTH = 800        # Width of the game screen in pixels (width)   
HEIGHT = 600       # Height of the game screen in pixels (height).    
FPS = 30           # Frames per second, how many times to update our program.  We'll use this for controlling animation speed  
SNAKE_COLOR = [255,178,64]    # RGB color code of the snake in a list format    
FOOD_COLOR =  (0,0,255)      # Food is represented as red.  The food's position will be randomly generated on screen at start  
SNAKE_BLOCKSIZE=10       # Size/length each block of the snake in pixels   
BG_COLOR = [34,67,89]     # Background color is dark blue.  This can also serve as a border around our game area for user interaction  
SPEED = 25           # Speed at which we want to move each frame of the snake in pixels per second (FPS)   
MOVEMENT = [WIDTH/10, HEIGHT/10]  # Direction that player can change. These are multiplied by SPEED for actual movement  
KEYS_PRESS={}         # Dictionary to hold the keys pressed in current frame of game loop    

# Set up our window:   
screen = display.set_mode((WIDTH, HEIGHT))  # Create a new surface with dimensions WIDTH x HEIGHT pixels and return it as an image  
display.set_caption('Snake Game')      # Sets the title for your game's caption bar in Windows OS    
icon=image.load("snake-logo")    # Loading icon file  (This is optional, you can remove this line if not needed)      
display.set_icon(icon)   # Set our window to have an image as the title of your application     
clock = time.Clock()     # Creates a new clock object that will be used for timing in game loop    – This is necessary so we can control how fast or slow things happen (like FPS).      

# Function definitions:  
def draw_block(x, y):      # Draws an individual block of the snake on screen at position x and y.    
        rect = Rect((x*SNAKE_BLOCKSIZE),(y)*SNAKE_BLOCKSIZE,(WIDTH/10), (HEIGHT/10))   # Creates a rectangle object that represents one 'block' of the snake     
        pygame.draw.rect(screen, SNAKE_COLOR , rect)     # Draws this block on screen using our defined color and size    – This is where we actually draw all blocks onto the surface  
        
def move():       # Function to handle movement of snake based upon keys pressed in current frame     
        for i, val in enumerate(MOVEMENT):     # Loops through each key-value pair (key: direction) and moves our block accordingly.  This is the main logic behind how we control where Snake's head goes  
            if KEYS_PRESS[i] == K_UP : MOVEMENT [i] = [-MOVEMENT[(i+2)%4],0 ]    # If up arrow key pressed, move snake in upward direction.  This is the same as moving left or right  
            if KEYS_PRESS[i] == K_DOWN: MOVEMENT [i] = [MOVEMENT[(i+2)%4],0 ]    # If down arrow key pressed, move snake in downward direction.  This is the same as moving left or right  
            if KEYS_PRESS[i] == K_LEFT: MOVEMENT [i] = [0,-MOVEMENT[(i+2)%4]]    # If left arrow key pressed, move snake in to the left direction.  This is same as moving up or down  
            if KEYS_PRESS[i] == K_RIGHT: MOVEMENT [i] = [0,MOVEMENT[(i+2)%4]]    # If right arrow key pressed move snake in to the Right direction.  This is same as moving up or down  
        return sum(x for x in MOVEMENT),sum(y for y in MOVEMENT )     # Returns new position of head after movement, this will be used by draw_block function   
        
def food():      # Function to generate and place the random location (X & Y) where our snake eats.  
        x = int((random.randint(0,(WIDTH/10)-SNAKE_BLOCKSIZE)/2)*2*SNAKE_BLOCKSIZE )  # Generates a new X position for food, this will be the horizontal location of where our snake eats   
        y= ( random.randint((HEIGHT-5)//4 ,(HEIGHT/10)-3)) * SNAKE_BLOCKSIZE   # This generates Y Position at which we want to place Food on screen, this will be the vertical location of where our snake eats   
        return x, y  # Returns X and Y coordinates as a tuple. We use these in draw function for food placement    
        
def game():      # Main Game Loop Function  
            while True:       # Infinite loop that will keep running until the user closes window or press 'X' button on top of it    – This is our main control structure to run program continuously.       
                for event in pygame.event.get():      # Event handling, this handles all events like keypress and mouse click etc  
                    if event.type == QUIT:       # If user closes window or press 'X' button on top of it then exit loop    – This is how we tell the program to stop running    
                        pygame.quit()      # Quit Pygames module and close all windows  
                screen.fill(BG_COLOR)       # Fill our window with background color, this will be used

Sign up or log in to comment