13

Snake Game

First code in Python

Main Function -

 
import pygame 
import numpy as np
import random
import Functions as fun
 
pygame.init()
#inititalizes game 
Score = 0 
 
display_width = 795
display_height = 1000
random.seed(pygame.time.get_ticks()/100)  #seeding random number generator for printing apple 
 
gameDisplay = pygame.display.set_mode((display_width,display_height)) # define surface to disoplay 
pygame.display.set_caption('Snake') 
 
font = pygame.font.SysFont("freesansbold.ttf", 72)
 
 
 
black = (0,0,0)
# set backgroound color
green = (0,250,0)
#sets green color
 
 
clock = pygame.time.Clock()
# defines interanal game clock 
crashed = False
case = 'up'
 
 
snakearr = [[16,16]]  # the array forwhich grid points the snake exists 
 
AppleX = random.randint(0,31)
AppleY = random.randint(0,31)
 
'''
Creates a 3 dimenisonal numpy array such that the 1st plane is for the xcordinates for its 
corresponding location in the display and 2nd plane is for the y cordinates of the pixels that can be displayed
the 3rd plane has a index value for example each corresponding value depicts a certain pixel
if the value is one that means that the corssponding x and y values that are loaction on that position 
on the other planes  
'''
 
xcordinates = []
ycordinates = []
snakecordinates = [[0] * 32] * 32
 
 
for x in range (0,800,25):
     temparray = []
     for y in range(0,800,25):
        temparray.append(y)
     xcordinates.append(temparray)
     
for x in range (0,800,25):  
     temparray = []
     for y in range(0,800,25):
        temparray.append(x)
     ycordinates.append(temparray)     
 
xycordinates = [xcordinates , ycordinates , snakecordinates ] 
xycordinates = np.array(xycordinates)
 
 
'''
creating a 3 dimensional array where the 1 st layer is the y axis and the 2nd layer is x axis 
and the 3 layer is defines the position where objects to be displayed are 
1 is for the segment of the snake
2 is for the head of the snake 
4 is for the apple 
3 denotes that thge snake has intersected itslef and hence will quit 
'''
 
xycordinates[2][16][16] = 2
# Initializes the head of the snake 
xycordinates[2][AppleY][AppleX] = 4
# Initializes the location of the apple 
          
      
            
     
while not crashed:       #GAMELOOP 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:   #check if the we are to close the game display  
            crashed = True         
        if event.type is pygame.KEYDOWN:    # inputs key commands if a key is pressed 
           key = pygame.key.name(event.key)  
        else:
            key = 'none'       
    gameDisplay.fill(black)                    #Fills Display with black background 
    fun.basegrid(xycordinates,gameDisplay)   #Dispalys the white pixel grid 
    
    # Structure for setting for movement case 
    
    if  key == 'w' and case !='down' :
        case = 'up'
    if key == 'a'and case !='right' :
        case = 'left'   
    if key == 's'and case !='up':
      case = 'down'
    if key == 'd' and case !='left':
       case = 'right'   
       
# The following lines of code do the following 
# Finds the postion where the element 2 exists in the matrix and returns a list of the cordinates
# After finding the position for the the element
# based on the key input the 2 that is present will be cleared and the adjacent position in the amtrix will be increased by 2      
# Also if there is n elemnt with 2 in the matrix it would lead to a loss 
# The Snake is also depected by an array of the x,y codrinates that the snake is present
# In this array it is append and poped off evertime a apple is eaten        
       
       
    poshead = np.where(xycordinates == 2) 
    if (len(poshead[1]) !=  0): 
        if case == 'up'  :
            xycordinates[2][int(poshead[1])][int(poshead[2])] -= 2 
            if (int(poshead[1]) > 0):
                xycordinates[2][int(poshead[1])-1][int(poshead[2])] += 2 
            else:
                xycordinates[2][31][int(poshead[2])] += 2 
        if case == 'down'   :
             xycordinates[2][int(poshead[1])][int(poshead[2])] -= 2 
             if (int(poshead[1]) < 31):
                 xycordinates[2][int(poshead[1])+1][int(poshead[2])] += 2 
             else:
                xycordinates[2][0][int(poshead[2])] += 2 
        if case == 'left'   :
             xycordinates[2][int(poshead[1])][int(poshead[2])] -= 2 
             if (int(poshead[2]) > 0):
                 xycordinates[2][int(poshead[1])][int(poshead[2]-1)] += 2
             else:
                xycordinates[2][int(poshead[1])][31] += 2    
        if case == 'right'   :
             xycordinates[2][int(poshead[1])][int(poshead[2])] -= 2 
             if (int(poshead[2]) < 31):
                 xycordinates[2][int(poshead[1])][int(poshead[2]+1)] += 2
             else:
                xycordinates[2][int(poshead[1])][0] += 2 
        snakearr.append([int(poshead[1]),int(poshead[2])])        
    else:
        crashed = 'True'
      
        
# Checks for colison where the head is added to the apple and hence is dentoed by the number 6 in the array
# If there is a colison the location off the colision is set to 2 for snake head and the Apple cordinates are randomized        
# IF there is no colisiohn the we pop of the snake arrray        
 
    colision =  np.where(xycordinates == 6)
    if len(colision[1]) != 0 :
            xycordinates[2][int(colision[1])][int(colision[2])] -= 4
            AppleX,AppleY =  fun.Set_cordinates(xycordinates)
            xycordinates[2][AppleY][AppleX] = 4
            Score += 1
    elif len(colision[1]) == 0   :
            tail = snakearr.pop(0) 
 
# The below code will set the values of the snake array in the amatrix to 1            
         
    if (len(snakearr) > 1):    
            for i in range(0,len(snakearr)):
                x = snakearr[i][0]
                y = snakearr[i][1]
                if (xycordinates[2][x][y] == 0):
                  xycordinates[2][x][y] +=1
                xycordinates[2][tail[0]][tail[1]] = 0   
 
                
    fun.Scoredisplay(font,gameDisplay,Score)  #Displays the Score
    fun.Snakehead(xycordinates,gameDisplay)       #Displays the Snake 
    fun.Snake(xycordinates,gameDisplay)       #Displays the Snake 
    fun.Apple(xycordinates,gameDisplay)       #Displays the Apple 
    pygame.display.update()  
    clock.tick(20)
pygame.quit()
quit()
 
 
# Functions - 
import pygame 
import numpy as np
import random
 
black = (0,0,0)
# set backgroound color
green = (0,250,0)
 
blank = pygame.image.load('Blank.png') 
# imports image for the base white grid 
 
 
snakehead = pygame.image.load('Snakehead.png') 
# imports image for the green snake 
 
snake = pygame.image.load('Snake.png') 
# imports image for the green snake 
 
apple = pygame.image.load('Apple.png') 
# imports image for the appple red pixels 
 
 
display_width = 795
 
def Set_cordinates(xycordinates):  # Chosses random Cordinates to displaythe apple 
    random.seed(pygame.time.get_ticks()/100)   
    Y = random.randint(0,31)
    X = random.randint(0,31)
    if (xycordinates[2][Y][X] != 0 ):  #In case random number choosen in the grid are not blank it reacalls the itself 
      Set_cordinates(xycordinates) 
    return X,Y
'''
The bellow functions are used to display the snake, Appple, Score and grid 
 
'''
def Snake(xycordinates,gameDisplay): 
    pos = np.where((xycordinates == 1))   
    for i in range(0, len(pos[1])):
        y =  xycordinates[1][int(pos[1][i])][int(pos[2][i])]
        x =  xycordinates[0][int(pos[1][i])][int(pos[2][i])]
        gameDisplay.blit(snake,(x,y))
 
def Snakehead(xycordinates,gameDisplay): 
    pos = np.where((xycordinates == 2))   
    for i in range(0, len(pos[1])):
        y =  xycordinates[1][int(pos[1][i])][int(pos[2][i])]
        x =  xycordinates[0][int(pos[1][i])][int(pos[2][i])]
        gameDisplay.blit(snakehead,(x,y))    
    
def Apple(xycordinates,gameDisplay): 
    pos = np.where(xycordinates == 4)
    if len(pos[1]) != 0:
        y =  xycordinates[1][int(pos[1])][int(pos[2])]
        x =  xycordinates[0][int(pos[1])][int(pos[2])]
        gameDisplay.blit(apple,(x,y))
 
def basegrid(xycordinates,gameDisplay): 
    for x in range (0,800,25):
        for y in range(0,800,25):
          gameDisplay.blit(blank,(x,y))
          
def Scoredisplay(font,gameDisplay,Score):
    
    text = font.render(f'Score {Score}', True, green, black)    
    textRect = text.get_rect()  
    textRect.center = (display_width // 2, 900) 
    gameDisplay.blit(text,textRect)