Skip to main content

The Future of Transportation: Self-Driving Cars Revolutionizing the Way We Travel

Snake Game Python Code




 Snake game is a classic game that has been enjoyed by generations. It's a simple game that involves controlling a snake to eat food while avoiding obstacles such as walls and the snake's own body. In this article, we will take a closer look at the Python code that can be used to create a snake game.


The Code


The snake game in Python can be created using the Pygame library, which is a set of Python modules designed for game development. Here's the basic code for creating a snake game in Python:


import pygame

import random


pygame.init()


# Create game window

window_width = 600

window_height = 400

window = pygame.display.set_mode((window_width, window_height))

pygame.display.set_caption("Snake Game")


# Define colors

black = (0, 0, 0)

white = (255, 255, 255)

green = (0, 255, 0)

red = (255, 0, 0)


# Set up snake

snake_block = 10

snake_speed = 15


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


def message(msg, color):

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

    window.blit(message, [window_width/6, window_height/3])


def gameLoop():

    game_over = False

    game_close = False


    # Set initial snake position

    x1 = window_width / 2

    y1 = window_height / 2

    x1_change = 0

    y1_change = 0


    # Generate food location

    foodx = round(random.randrange(0, window_width - snake_block) / 10.0) * 10.0

    foody = round(random.randrange(0, window_height - snake_block) / 10.0) * 10.0


    while not game_over:

        while game_close == True:

            window.fill(white)

            message("You Lost! Press Q-Quit or C-Play Again", red)

            pygame.display.update()


            for event in pygame.event.get():

                if event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_q:

                        game_over = True

                        game_close = False

                    if event.key == pygame.K_c:

                        gameLoop()


        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                game_over = 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


        # Check for boundaries and collisions with snake body

        if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:

            game_close = True

        x1 += x1_change

        y1 += y1_change

        window.fill(black)

        pygame.draw.rect(window, green, [foodx, foody, snake_block, snake_block])

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

        pygame.display.update()


        # Check if snake has eaten food

        if x1 == foodx and y1 == foody:

            print("Yummy!!")

        pygame.display.update()


        # Set snake speed


Comments

Popular posts from this blog

Introducing chatgpt and whisper Api

In recent years, the field of artificial intelligence has made significant advancements, with natural language processing (NLP) being one of the most prominent. OpenAI is one of the leading organizations in this field, and it has developed some of the most advanced language models available, including ChatGPT and Whisper API. ChatGPT is an NLP model that uses the Generative Pre-trained Transformer 3 (GPT-3) architecture to generate human-like responses to user inputs. It is a large-scale language model that has been trained on a massive amount of text data from various sources, including websites, books, and other online content. The model has the capability to understand natural language queries and generate appropriate responses in real-time. One of the primary uses of ChatGPT is to power chatbots and virtual assistants that can help customers with their queries and concerns. With ChatGPT, businesses can create personalized experiences for their customers by tailoring res...

Top 10 tips for Starting a Print on Demand Business

Print on demand (POD) is a relatively new and popular business model that allows entrepreneurs to sell custom-designed products without having to invest in inventory. With POD, products are created and shipped only when a customer orders them. This means that you can start a business with little upfront cost and no inventory risk. Here are ten tips to help you get started with your own POD business: Choose a niche: Your success in POD largely depends on your ability to identify and target a specific niche market. Look for an underserved market or a group of people with a common interest, and tailor your product offerings to their needs. Identify your products: The next step is to identify the types of products you want to sell. POD businesses can sell a variety of products such as t-shirts, mugs, phone cases, and more. Choose products that are easy to produce and have high profit margins. Research suppliers: Once you know what products you want to sell, it's time to research suppli...