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

Google Startups Funds 2023

  Google for Startups is a global initiative by Google that empowers startups through various programs, resources, and community support. One of the initiatives under this program is the Google for Startups Founders Academy, which aims to provide online training to founders of startups across the world. The Founders Academy is a six-week virtual training program designed to help early-stage startup founders build and grow their businesses. The program covers topics such as product development, user acquisition, fundraising, and team management. The curriculum is designed by Google experts and industry leaders and is tailored to the needs of startups. To apply for the Founders Academy, startup founders must meet certain eligibility criteria. They should be the founders or co-founders of an early-stage startup, which has raised less than $5 million in funding and has been in operation for less than five years. The startup should also be focused on technology or digital products and s...

Google Pixel 7a in coral makes its first appearance in new leak

  A recent leak has emerged, allegedly showcasing the upcoming Google Pixel 7a in the "Coral" colorway. The leaked image reveals a similar design to the Pixel 4a 5G, but with some modifications to the camera module. The leaker who posted the image claims that the Pixel 7a will feature the same camera sensor as the Pixel 5, which could lead to better camera performance compared to its predecessor. The Pixel 7a has been a highly anticipated device among tech enthusiasts and Google fans, as the company is known for producing smartphones with excellent camera capabilities. If the leaked information is accurate, the Pixel 7a could be a game-changer for those who prioritize photography in their smartphone use. However, it's important to note that the leaked information should be taken with a grain of salt until there is official confirmation from Google. It's not uncommon for rumors and leaks to be inaccurate, and it's best to wait for official announcements before maki...

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

Saudi Arabia invests $38bn to establish local gaming industry

Saudi Arabia invests $38bn to establish local gaming industry Saudi Arabia has pledged to invest $3.8 billion to develop a thriving gaming industry within the country. This move is part of the country's wider efforts to diversify its economy and reduce its reliance on oil. The Saudi Arabian General Investment Authority (SAGIA) announced the investment plan, which aims to create a gaming industry capable of generating $3 billion in revenue by 2030. The funds will be used to establish a range of initiatives, including the creation of a gaming academy to train local talent, as well as a dedicated gaming conference and a new gaming studio. how to become a Game streamer The Saudi Arabian government hopes that the investment will help to stimulate economic growth and create new job opportunities, particularly for young people. The gaming industry is one of the fastest-growing sectors in the world, and Saudi Arabia believes that it has the potential to become a major player in the industr...

Trends and Innovations in Information Systems Tech

 In the constantly evolving world of technology, the field of information systems is no exception. With advancements in areas such as artificial intelligence, cloud computing, and data analytics, there are always new trends and innovations emerging. The Importance of Information Systems in Business Operations  In this article, we will explore some of the latest trends and innovations in information systems technology. Artificial Intelligence (AI) and Machine Learning (ML) Artificial intelligence and machine learning have been hot topics in the world of technology for several years now, and their influence is continuing to grow. These technologies are being used to improve processes, increase efficiency, and drive innovation across various industries. In the field of information systems, AI and ML are being used to automate routine tasks, analyze large amounts of data, and create intelligent systems that can learn and adapt over time. Some of the applications of AI and ML in in...

how to approach an investor for funding.

How to approach an investor for the first time.  Approaching an investor for the first time can be a daunting task, but with the right approach, you can increase your chances of success. Here are some tips for how to approach an investor on chat for the first time: Do your research: Before reaching out to an investor, make sure you have thoroughly researched their background and investment interests. This will help you tailor your message to their specific needs and interests. Start with a strong introduction: Begin your message by introducing yourself and your business in a concise and compelling way. Be sure to mention any relevant accomplishments or awards to establish credibility. Explain why you are reaching out: Clearly state why you are interested in speaking with the investor, whether it's to receive funding, get feedback, or establish a relationship. Be specific: Provide specific details about your business, including your product or service, target market, and any tractio...