Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Make A Snake Game Using Python and Pygame

# importing libraries
import pygame
import time
import random
 
snake_speed = 15
 
# Window size
window_x = 720
window_y = 480
 
# defining colors
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
 
# Initialising pygame
pygame.init()
 
# Initialise game window
pygame.display.set_caption('GeeksforGeeks Snakes')
game_window = pygame.display.set_mode((window_x, window_y))
 
# FPS (frames per second) controller
fps = pygame.time.Clock()
 
# defining snake default position
snake_position = [100, 50]
 
# defining first 4 blocks of snake body
snake_body = [[100, 50],
              [90, 50],
              [80, 50],
              [70, 50]
              ]
# fruit position
fruit_position = [random.randrange(1, (window_x//10)) * 10,
                  random.randrange(1, (window_y//10)) * 10]
 
fruit_spawn = True
 
# setting default snake direction towards
# right
direction = 'RIGHT'
change_to = direction
 
# initial score
score = 0
 
# displaying Score function
def show_score(choice, color, font, size):
   
    # creating font object score_font
    score_font = pygame.font.SysFont(font, size)
     
    # create the display surface object
    # score_surface
    score_surface = score_font.render('Score : ' + str(score), True, color)
     
    # create a rectangular object for the text
    # surface object
    score_rect = score_surface.get_rect()
     
    # displaying text
    game_window.blit(score_surface, score_rect)
 
# game over function
def game_over():
   
    # creating font object my_font
    my_font = pygame.font.SysFont('times new roman', 50)
     
    # creating a text surface on which text
    # will be drawn
    game_over_surface = my_font.render(
        'Your Score is : ' + str(score), True, red)
     
    # create a rectangular object for the text
    # surface object
    game_over_rect = game_over_surface.get_rect()
     
    # setting position of the text
    game_over_rect.midtop = (window_x/2, window_y/4)
     
    # blit will draw the text on screen
    game_window.blit(game_over_surface, game_over_rect)
    pygame.display.flip()
     
    # after 2 seconds we will quit the program
    time.sleep(2)
     
    # deactivating pygame library
    pygame.quit()
     
    # quit the program
    quit()
 
 
# Main Function
while True:
     
    # handling key events
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                change_to = 'UP'
            if event.key == pygame.K_DOWN:
                change_to = 'DOWN'
            if event.key == pygame.K_LEFT:
                change_to = 'LEFT'
            if event.key == pygame.K_RIGHT:
                change_to = 'RIGHT'
 
    # If two keys pressed simultaneously
    # we don't want snake to move into two
    # directions simultaneously
    if change_to == 'UP' and direction != 'DOWN':
        direction = 'UP'
    if change_to == 'DOWN' and direction != 'UP':
        direction = 'DOWN'
    if change_to == 'LEFT' and direction != 'RIGHT':
        direction = 'LEFT'
    if change_to == 'RIGHT' and direction != 'LEFT':
        direction = 'RIGHT'
 
    # Moving the snake
    if direction == 'UP':
        snake_position[1] -= 10
    if direction == 'DOWN':
        snake_position[1] += 10
    if direction == 'LEFT':
        snake_position[0] -= 10
    if direction == 'RIGHT':
        snake_position[0] += 10
 
    # Snake body growing mechanism
    # if fruits and snakes collide then scores
    # will be incremented by 10
    snake_body.insert(0, list(snake_position))
    if snake_position[0] == fruit_position[0] and snake_position[1] == fruit_position[1]:
        score += 10
        fruit_spawn = False
    else:
        snake_body.pop()
         
    if not fruit_spawn:
        fruit_position = [random.randrange(1, (window_x//10)) * 10,
                          random.randrange(1, (window_y//10)) * 10]
         
    fruit_spawn = True
    game_window.fill(black)
     
    for pos in snake_body:
        pygame.draw.rect(game_window, green,
                         pygame.Rect(pos[0], pos[1], 10, 10))
    pygame.draw.rect(game_window, white, pygame.Rect(
        fruit_position[0], fruit_position[1], 10, 10))
 
    # Game Over conditions
    if snake_position[0] < 0 or snake_position[0] > window_x-10:
        game_over()
    if snake_position[1] < 0 or snake_position[1] > window_y-10:
        game_over()
 
    # Touching the snake body
    for block in snake_body[1:]:
        if snake_position[0] == block[0] and snake_position[1] == block[1]:
            game_over()
 
    # displaying score countinuously
    show_score(1, white, 'times new roman', 20)
 
    # Refresh game screen
    pygame.display.update()
 
    # Frame Per Second /Refresh Rate
    fps.tick(snake_speed)
Comment

python snake game

import turtle
from random import randint
from time import sleep

#create screen

scr = turtle.Screen()
scr.bgcolor('black')
scr.title("Snake Game")
scr.setup(width=600, height=600)
scr.listen()
scr.tracer(0)


#create snake turtle
snake = turtle.Turtle()
snake.shape('square')
snake.color('green')
#user defined property
snake.direction = "stop"
snake.speed(0)
snake.up()

#create fruit turtle
fruit = turtle.Turtle()
fruit.shape('circle')
fruit.color('red')
fruit.shapesize(0.6)
fruit.up()
fruit.goto(50,100)
fruit.speed(0)

#create writer turtle
writer = turtle.Turtle()
writer.color('white')
writer.speed(0)
writer.hideturtle()
writer.up()
writer.score = 0
writer.highscore = 0

#variables
#score = 0
#highscore = 0

# snake body
body_parts = []


def write_score() :
    writer.goto(-250,200)
    writer.write(f'score : {writer.score}',font=("Comic Sans MS",15,"normal"))
    writer.goto(100,200)
    writer.write(f'High Score : {writer.highscore}',font=("Comic Sans MS",15,"normal"))

write_score()

def move():
    if snake.direction == "up":
        snake.sety(snake.ycor() + 20)
    if snake.direction == "down":
        snake.sety(snake.ycor() - 20)
    if snake.direction == "right":
        snake.setx(snake.xcor() + 20)
    if snake.direction == "left":
        snake.setx(snake.xcor() - 20)

def move_right():
    if snake.direction != "left":
        snake.direction = "right"
def move_left():
    if snake.direction != "right":
        snake.direction = "left"
def move_up():
    if snake.direction != "down":
        snake.direction = "up"
def move_down():
    if snake.direction != "up":
        snake.direction = "down"



#declaration or definition
def control_score():
    if snake.distance(fruit) < 16 :
        fruit.goto(randint(-250,250),randint(-220,220))
        writer.clear()
        writer.score += 10
        if writer.score > writer.highscore:
            writer.highscore = writer.score
        write_score()

        # Adding segments
        new_part = turtle.Turtle()
        new_part.speed(0)
        new_part.color("Red")
        new_part.shape("square")
        new_part.pu()
        body_parts.append(new_part)

def border_collission():
    if snake.xcor()>285 or snake.xcor()<-285 or snake.ycor()>285 or snake.ycor()<-285:
            sleep(1)
            snake.goto(0,0)
            snake.direction = "stop"
            writer.clear()
            writer.score = 0
            write_score()
            last_index = len(body_parts) -1
            for i in range(last_index, -1, -1):
                body_parts[i].hideturtle()
            body_parts.clear()

# Snake Body control
def snake_body():
    last_index = len(body_parts) - 1
    for i in range(last_index, 0, -1):
        x = body_parts[i -1].xcor()
        y = body_parts[i -1].ycor()
        body_parts[i].goto(x, y)
    if len(body_parts) > 0:
        body_parts[0].goto(snake.xcor(), snake.ycor())


def body_collision():
    for i in body_parts:
        if snake.distance(i) < 20:
            sleep(1)
            snake.goto(0,0)
            snake.direction = "stop"
            writer.clear()
            writer.score = 0
            write_score()
            last_index = len(body_parts) -1
            for i in range(last_index, -1, -1):
                body_parts[i].hideturtle()
            body_parts.clear()

scr.onkey(move_right,"Right")
scr.onkey(move_left,"Left")
scr.onkey(move_up,"Up")
scr.onkey(move_down,"Down")

game_mode = True
while game_mode:
    scr.update()
    sleep(0.1)
    control_score()
    snake_body()
    move()
    border_collission()
    body_collision()
Comment

PREVIOUS NEXT
Code Example
Python :: scanning 2d array in python 
Python :: ModuleNotFoundError: No module named ‘click’ 
Python :: How to Create a Pie Chart in Seaborn 
Python :: read binary file python 
Python :: bs4 table examples python 
Python :: how to read a .exe file in python 
Python :: How to create a hyperlink with a Label in Tkinter 
Python :: get information about dataframe 
Python :: how to install python libraries 
Python :: parcourir une liste par la fin python 
Python :: bar plot fix lenthgy labels matplot 
Python :: plot confidence interval matplotlib 
Python :: python async threading 
Python :: split list in 3 part 
Python :: fastapi upload image PIL 
Python :: scikit learn split data set 
Python :: import random py 
Python :: get first element list of tuples python 
Python :: text to pandas 
Python :: Parameter Grid python 
Python :: find duplicate in dataset python 
Python :: dataframe delete row 
Python :: pandas load dataframe without header 
Python :: how to slicing dataframe using two conditions 
Python :: how to remove duplicate files from folder with python 
Python :: empty directory if not empty python 
Python :: numpy arrays equality 
Python :: how to make an object set once python 
Python :: python index of last occurrence in string 
Python :: python read column data from text file 
ADD CONTENT
Topic
Content
Source link
Name
2+8 =