python code for snake game

 Here is an example of a simple snake game implemented in Python using the Pygame library:


python

Copy code

import pygame

import time


# Initialize pygame

pygame.init()


# Set the size of the screen (width, height).

size = (700, 500)

screen = pygame.display.set_mode(size)


pygame.display.set_caption("My Snake Game")


# Loop until the user clicks the close button.

done = False


# Used to manage how fast the screen updates

clock = pygame.time.Clock()


# Initialize the snake's starting position and speed

snake_block = 10

snake_speed = 30

snake_list = []

snake_length = 1


# Define colors

black = (0,0,0)

white = (255, 255, 255)

red = (255, 0, 0)


# Initialize the snake's starting position

x1 = 300

y1 = 300

x1_change = 0

y1_change = 0


font_style = pygame.font.SysFont(None, 50)


def message(msg,color):

    mesg = font_style.render(msg, True, color)

    screen.blit(mesg, [300,250])


# Main game loop

while not done:

    # --- Main event loop

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            done = True

        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_LEFT:

                x1_change = -snake_block

                y1_change = 0

            elif event.key == pygame.K_RIGHT:

                x1_change = snake_block

                y1_change = 0

            elif event.key == pygame.K_UP:

                y1_change = -snake_block

                x1_change = 0

            elif event.key == pygame.K_DOWN:

                y1_change = snake_block

                x1_change = 0

    # --- Game logic should go here

    x1 += x1_change

    y1 += y1_change

    screen.fill(black)

    pygame.draw.rect(screen, white, [x1, y1, snake_block, snake_block])

    pygame.display.update()


    clock.tick(snake_speed)


# Close the window and quit.

pygame.quit()

This code creates a window with the size of (700,500) using the pygame.display.set_mode() function, then a snake is created as a white rectangle using the pygame.draw.rect() function and its position is updated based on the arrow keys using the pygame.event.get() function.


This is just a basic example of a snake game, you can add more functionalities like collision detection, eating food, increasing the snake's length, and adding a scoring system.

Comments

Popular posts from this blog

fibonacci series in python

python code for calculator

prime number program in python