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

The Basics of Information Systems: What They Are and How They Work

 In today's digital age, information systems are the backbone of businesses and organizations of all sizes. From managing data to streamlining processes, information systems play a critical role in ensuring smooth operations and success. But what exactly are information systems, and how do they work? Let's take a closer look. What are Information Systems? An information system is a set of interconnected components that work together to collect, store, process, and distribute information. These components include hardware, software, data, procedures, and people. Information systems can be used for a variety of purposes, including decision-making, data analysis, communication, and automation. The Importance of Information Systems in Business Operations There are four main types of information systems: Transaction Processing Systems (TPS): These systems are used to process and record transactions, such as sales or purchases, in real-time. Management Information Systems (MIS): MIS ...

How to start an eSports Business

eSports, also known as competitive video gaming, has grown rapidly in popularity over the past few years. With millions of people tuning in to watch their favorite games and players compete, it's no surprise that many entrepreneurs are interested in starting their own eSports businesses. However, the world of eSports can be daunting, especially if you're new to the scene. In this article, we'll walk you through the steps of starting your own eSports business. Conduct Market Research Before you start an eSports business, it's essential to conduct market research to determine if there's a demand for your product or service. You can start by researching the most popular games, teams, and tournaments in your region or country. Find out what type of events are currently being held and how they're being marketed. Additionally, research the demographics of the eSports audience, such as their age, gender, and income. Choose Your Niche There are several diffe...

How to Start a Mobile Device Production Business

Mobile devices are essential in today's world, with millions of people around the globe relying on them for communication, entertainment, and productivity. If you're interested in creating your own mobile device production company, there are several key steps you'll need to take to get started. In this article, we'll walk you through the process of creating a mobile device production company. Conduct Market Research Before you start a mobile device production company, it's important to conduct market research to determine if there's a demand for your product. You'll need to research the competition, identify gaps in the market, and determine what features and specifications are most important to your target audience. Develop a Business Plan Once you've conducted your market research, you'll need to develop a business plan. Your business plan should outline your company's goals, target market, marketing strategy, and financial projecti...

The Importance of Information Systems in Business

  In today's fast-paced and technology-driven world, information systems play a crucial role in the success of businesses of all sizes. Information systems, which include hardware, software, and data management tools, are essential for collecting, storing, and analyzing data, making informed decisions, and optimizing business operations. In this article, we'll explore the importance of information systems in business operations and why every business needs to invest in them. Trends and Innovations in Information Systems Technology Streamline Processes and Increase Efficiency Information systems help businesses streamline processes, automate repetitive tasks, and increase operational efficiency. For example, inventory management systems can track stock levels, orders, and deliveries, reducing the risk of stockouts and overstocks. Similarly, customer relationship management (CRM) software can centralize customer data, enabling businesses to personalize marketing, sales, and suppo...

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...