avatarWajiha Urooj

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

15546

Abstract

class="hljs-number">0</span> elif event.<span class="hljs-built_in">key</span> == pygame.K_RIGHT: x1_change = snake_block y1_change = <span class="hljs-number">0</span> elif event.<span class="hljs-built_in">key</span> == pygame.K_UP: y1_change = -snake_block x1_change = <span class="hljs-number">0</span> elif event.<span class="hljs-built_in">key</span> == pygame.K_DOWN: y1_change = snake_block x1_change = <span class="hljs-number">0</span>

<span class="hljs-keyword">if</span> x1 &gt;= dis_width <span class="hljs-keyword">or</span> x1 &lt; <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> y1 &gt;= dis_height <span class="hljs-keyword">or</span> y1 &lt; <span class="hljs-number">0</span>:
    game_over = True

x1 += x1_change
y1 += y1_change
dis.fill(white)
pygame.<span class="hljs-built_in">draw</span>.rect(dis, black, [x1, y1, snake_block, snake_block])

pygame.<span class="hljs-built_in">display</span>.update()

clock.tick(snake_speed)

message(<span class="hljs-string">"You lost"</span>,red) pygame.<span class="hljs-built_in">display</span>.update() <span class="hljs-built_in">time</span>.sleep(<span class="hljs-number">2</span>)

pygame.<span class="hljs-built_in">quit</span>() <span class="hljs-built_in">quit</span>()</pre></div><p id="dbae"><b>OUTPUT:</b></p><figure id="976b"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*XlTtOlqJHo41OSEn3gE1uA.png"><figcaption></figcaption></figure><h1 id="19b9">Adding the Food:</h1><p id="5745">Here, I will be adding some food for the snake and when the snake crosses over that food, I will have a message saying “Yummy!!”. Also, I will be making a small change wherein I will include the options to quit the game or to play again when the player loses.</p><div id="3821"><pre>import pygame import <span class="hljs-built_in">time</span> import <span class="hljs-built_in">random</span>

pygame.init()

white = (<span class="hljs-number">255</span>, <span class="hljs-number">255</span>, <span class="hljs-number">255</span>) black = (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>) red = (<span class="hljs-number">255</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>) blue = (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">255</span>)

dis_width = <span class="hljs-number">800</span> dis_height = <span class="hljs-number">600</span>

dis = pygame.<span class="hljs-built_in">display</span>.set_mode((dis_width, dis_height)) pygame.<span class="hljs-built_in">display</span>.set_caption('Snake Game by Edureka')

clock = pygame.<span class="hljs-built_in">time</span>.Clock()

snake_block = <span class="hljs-number">10</span> snake_speed = <span class="hljs-number">30</span>

font_style = pygame.<span class="hljs-built_in">font</span>.SysFont(None, <span class="hljs-number">30</span>)

def message(msg, <span class="hljs-built_in">color</span>): mesg = font_style.render(msg, True, <span class="hljs-built_in">color</span>) dis.blit(mesg, [dis_width/<span class="hljs-number">3</span>, dis_height/<span class="hljs-number">3</span>])

def gameLoop(): # creating a function game_over = False game_close = False

x1 = dis_width / <span class="hljs-number">2</span>
y1 = dis_height / <span class="hljs-number">2</span>

x1_change = <span class="hljs-number">0</span>
y1_change = <span class="hljs-number">0</span>

foodx = <span class="hljs-built_in">round</span>(<span class="hljs-built_in">random</span>.randrange(<span class="hljs-number">0</span>, dis_width - snake_block) / <span class="hljs-number">10.0</span>) * <span class="hljs-number">10.0</span>
foody = <span class="hljs-built_in">round</span>(<span class="hljs-built_in">random</span>.randrange(<span class="hljs-number">0</span>, dis_width - snake_block) / <span class="hljs-number">10.0</span>) * <span class="hljs-number">10.0</span>

<span class="hljs-keyword">while</span> <span class="hljs-keyword">not</span> game_over:

    <span class="hljs-keyword">while</span> game_close == True:
        dis.fill(white)
        message(<span class="hljs-string">"You Lost! Press Q-Quit or C-Play Again"</span>, red)
        pygame.<span class="hljs-built_in">display</span>.update()

        <span class="hljs-keyword">for</span> event <span class="hljs-keyword">in</span> pygame.event.<span class="hljs-built_in">get</span>():
            <span class="hljs-keyword">if</span> event.type == pygame.KEYDOWN:
                <span class="hljs-keyword">if</span> event.<span class="hljs-built_in">key</span> == pygame.K_q:
                    game_over = True
                    game_close = False
                <span class="hljs-keyword">if</span> event.<span class="hljs-built_in">key</span> == pygame.K_c:
                    gameLoop()

    <span class="hljs-keyword">for</span> event <span class="hljs-keyword">in</span> pygame.event.<span class="hljs-built_in">get</span>():
        <span class="hljs-keyword">if</span> event.type == pygame.QUIT:
            game_over = True
        <span class="hljs-keyword">if</span> event.type == pygame.KEYDOWN:
            <span class="hljs-keyword">if</span> event.<span class="hljs-built_in">key</span> == pygame.K_LEFT:
                x1_change = -snake_block
                y1_change = <span class="hljs-number">0</span>
            elif event.<span class="hljs-built_in">key</span> == pygame.K_RIGHT:
                x1_change = snake_block
                y1_change = <span class="hljs-number">0</span>
            elif event.<span class="hljs-built_in">key</span> == pygame.K_UP:
                y1_change = -snake_block
                x1_change = <span class="hljs-number">0</span>
            elif event.<span class="hljs-built_in">key</span> == pygame.K_DOWN:
                y1_change = snake_block
                x1_change = <span class="hljs-number">0</span>

    <span class="hljs-keyword">if</span> x1 &gt;= dis_width <span class="hljs-keyword">or</span> x1 &lt; <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> y1 &gt;= dis_height <span class="hljs-keyword">or</span> y1 &lt; <span class="hljs-number">0</span>:
        game_close = True

    x1 += x1_change
    y1 += y1_change
    dis.fill(white)
    pygame.<span class="hljs-built_in">draw</span>.rect(dis, blue, [foodx, foody, snake_block, snake_block])
    pygame.<span class="hljs-built_in">draw</span>.rect(dis, black, [x1, y1, snake_block, snake_block])
    pygame.<span class="hljs-built_in">display</span>.update()

    <span class="hljs-keyword">if</span> x1 == foodx <span class="hljs-keyword">and</span> y1 == foody:
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Yummy!!"</span>)
    clock.tick(snake_speed)

pygame.<span class="hljs-built_in">quit</span>()
<span class="hljs-built_in">quit</span>()

gameLoop()</pre></div><p id="9c55"><b>OUTPUT:</b></p><figure id="2852"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*IGFQ0foZiUWw161UMETSOg.png"><figcaption></figcaption></figure><p id="eb46"><b>Terminal:</b></p><figure id="6bfa"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*ug_5dc5fSkoERReFFfMo9Q.png"><figcaption></figcaption></figure><h1 id="c2d0">Increasing the Length of the Snake:</h1><p id="ce4c">The following code will increase the size of our sake when it eats the food. Also, if the snake collides with his own body, the game is over and you ill see a message as “You Lost! Press Q-Quit or C-Play Again”. The length of the snake is basically contained in a list and the initial size that is specified in the following code is one block.</p><div id="a38b"><pre><span class="hljs-attribute">import</span> pygame <span class="hljs-attribute">import</span> time <span class="hljs-attribute">import</span> random

<span class="hljs-attribute">pygame</span>.init()

<span class="hljs-attribute">white</span> = (<span class="hljs-number">255</span>, <span class="hljs-number">255</span>, <span class="hljs-number">255</span>) <span class="hljs-attribute">yellow</span> = (<span class="hljs-number">255</span>, <span class="hljs-number">255</span>, <span class="hljs-number">102</span>) <span class="hljs-attribute">black</span> = (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>) <span class="hljs-attribute">red</span> = (<span class="hljs-number">213</span>, <span class="hljs-number">50</span>, <span class="hljs-number">80</span>) <span class="hljs-attribute">green</span> = (<span class="hljs-number">0</span>, <span class="hljs-number">255</span>, <span class="hljs-number">0</span>) <span class="hljs-attribute">blue</span> = (<span class="hljs-number">50</span>, <span class="hljs-number">153</span>, <span class="hljs-number">213</span>)

<span class="hljs-attribute">dis_width</span> = <span class="hljs-number">600</span> <span class="hljs-attribute">dis_height</span> = <span class="hljs-number">400</span>

<span class="hljs-attribute">dis</span> = pygame.display.set_mode((dis_width, dis_height)) <span class="hljs-attribute">pygame</span>.display.set_caption('Snake Game by Edureka')

<span class="hljs-attribute">clock</span> = pygame.time.Clock()

<span class="hljs-attribute">snake_block</span> = <span class="hljs-number">10</span> <span class="hljs-attribute">snake_speed</span> = <span class="hljs-number">15</span>

<span class="hljs-attribute">font_style</span> = pygame.font.SysFont(<span class="hljs-string">"bahnschrift"</span>, <span class="hljs-number">25</span>) <span class="hljs-attribute">score_font</span> = pygame.font.SysFont(<span class="hljs-string">"comicsansms"</span>, <span class="hljs-number">35</span>)

<span class="hljs-attribute">def</span> our_snake(snake_block, snake_list): <span class="hljs-attribute">for</span> x in snake_list: <span class="hljs-attribute">pygame</span>.draw.rect(dis, black,<span class="hljs-meta"> [x[0], x[1], snake_block, snake_block])

def message(msg, color): mesg = font_style.render(msg, True, color) dis.blit(mesg, [dis_width / 6, dis_height / 3])

def gameLoop(): game_over = False game_close = False

x1 = dis_width / 2
y1 = dis_height / 2

x1_change = 0
y1_change = 0

snake_List = []</span>
<span class="hljs-attribute">Length_of_snake</span> = <span class="hljs-number">1</span>

<span class="hljs-attribute">foodx</span> = round(random.randrange(<span class="hljs-number">0</span>, dis_width - snake_block) / <span class="hljs-number">10</span>.<span class="hljs-number">0</span>) * <span class="hljs-number">10</span>.<span class="hljs-number">0</span>
<span class="hljs-attribute">foody</span> = round(random.randrange(<span class="hljs-number">0</span>, dis_height - snake_block) / <span class="hljs-number">10</span>.<span class="hljs-number">0</span>) * <span class="hljs-number">10</span>.<span class="hljs-number">0</span>

<span class="hljs-attribute">while</span> not game_over:

    <span class="hljs-attribute">while</span> game_close == True:
        <span class="hljs-attribute">dis</span>.fill(blue)
        <span class="hljs-attribute">message</span>(<span class="hljs-string">"You Lost! Press C-Play Again or Q-Quit"</span>, red)

        <span class="hljs-attribute">pygame</span>.display.update()

        <span class="hljs-attribute">for</span> event in pygame.event.get():
            <span class="hljs-attribute">if</span> event.type == pygame.KEYDOWN:
                <span class="hljs-attribute">if</span> event.key == pygame.K_q:
                    <span class="hljs-attribute">game_over</span> = True
                    <span class="hljs-attribute">game_close</span> = False
                <span class="hljs-attribute">if</span> event.key == pygame.K_c:
                    <span class="hljs-attribute">gameLoop</span>()

    <span class="hljs-attribute">for</span> event in pygame.event.get():
        <span class="hljs-attribute">if</span> event.type == pygame.QUIT:
            <span class="hljs-attribute">game_over</span> = True
        <span class="hljs-attribute">if</span> event.type == pygame.KEYDOWN:
            <span class="hljs-attribute">if</span> event.key == pygame.K_LEFT:
                <span class="hljs-attribute">x1_change</span> = -snake_block
                <span class="hljs-attribute">y1_change</span> = <span class="hljs-number">0</span>
            <span class="hljs-attribute">elif</span> event.key == pygame.K_RIGHT:
                <span class="hljs-attribute">x1_change</span> = snake_block
                <span class="hljs-attribute">y1_change</span> = <span class="hljs-number">0</span>
            <span class="hljs-attribute">elif</span> event.key == pygame.K_UP:
                <span class="hljs-attribute">y1_change</span> = -snake_block
                <span class="hljs-attribute">x1_change</span> = <span class="hljs-number">0</span>
            <span class="hljs-attribute">elif</span> event.key == pygame.K_DOWN:
                <span class="hljs-attribute">y1_change</span> = snake_block
                <span class="hljs-attribute">x1_change</span> = <span class="hljs-number">0</span>

    <span class="hljs-attribute">if</span> x1 &gt;= dis_width or x1 &lt; <span class="hljs-number">0</span> or y1 &gt;= dis_height or y1 &lt; <span class="hljs-number">0</span>:
        <span class="hljs-attribute">game_close</span> = True
    <span class="hljs-attribute">x1</span> += x1_change
    <span class="hljs-attribute">y1</span> += y1_change
    <span class="hljs-attribute">dis</span>.fill(blue)
    <span class="hljs-attribute">pygame</span>.draw.rect(dis, green,<span class="hljs-meta"> [foodx, foody, snake_block, snake_block])
    snake_Head = []</span>
    <span class="hljs-attribute">snake_Head</span>.append(x1)
    <span class="hljs-attribute">snake_Head</span>.append(y1)
    <span class="hljs-attribute">snake_List</span>.append(snake_Head)
    <span class="hljs-attribute">if</span> len(snake_List) &gt; Length_of_snake:
        <span class="hljs-attribute">del</span> snake_List[<span class="hljs-number">0</span>]

    <span class="hljs-attribute">for</span> x in snake_List[:-<span class="hljs-number">1</span>]:
        <span class="hljs-attribute">if</span> x == snake_Head:
            <span class="hljs-attribute">game_close</span> = True

    <span class="hljs-attribute">our_snake</span>(snake_block, snake_List)


    <span class="hljs-attribute">pygame</span>.display.update()

    <span class="hljs-attribute">if</span> x1 == foodx and y1 == foody:
        <span class="hljs-attribute">foodx</span> = round(random.randrange(<span class="hljs-number">0</span>, dis_width - snake_block) / <span class="hljs-number">10</span>.<span class="hljs-number">0</span>) * <span class="hljs-number">10</span>.<span class="hljs-number">0</span>
        <span class="hljs-attribute">foody</spa

Options

n> = round(random.randrange(<span class="hljs-number">0</span>, dis_height - snake_block) / <span class="hljs-number">10</span>.<span class="hljs-number">0</span>) * <span class="hljs-number">10</span>.<span class="hljs-number">0</span> <span class="hljs-attribute">Length_of_snake</span> += <span class="hljs-number">1</span>

    <span class="hljs-attribute">clock</span>.tick(snake_speed)

<span class="hljs-attribute">pygame</span>.quit()
<span class="hljs-attribute">quit</span>()

<span class="hljs-attribute">gameLoop</span>()</pre></div><p id="7218"><b>OUTPUT:</b></p><figure id="e509"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*IJjBcAlbpyIrW1JRxpo2Dg.png"><figcaption></figcaption></figure><h1 id="6ceb">Displaying the Score:</h1><p id="6dce">Last but definitely not the least, you will need to display the score of the player. To do this, I have created a new function as “Your_score”. This function will display the length of the snake subtracted by 1 because that is the initial size of the snake.</p><div id="7b88"><pre><span class="hljs-attribute">import</span> pygame <span class="hljs-attribute">import</span> time <span class="hljs-attribute">import</span> random

<span class="hljs-attribute">pygame</span>.init()

<span class="hljs-attribute">white</span> = (<span class="hljs-number">255</span>, <span class="hljs-number">255</span>, <span class="hljs-number">255</span>) <span class="hljs-attribute">yellow</span> = (<span class="hljs-number">255</span>, <span class="hljs-number">255</span>, <span class="hljs-number">102</span>) <span class="hljs-attribute">black</span> = (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>) <span class="hljs-attribute">red</span> = (<span class="hljs-number">213</span>, <span class="hljs-number">50</span>, <span class="hljs-number">80</span>) <span class="hljs-attribute">green</span> = (<span class="hljs-number">0</span>, <span class="hljs-number">255</span>, <span class="hljs-number">0</span>) <span class="hljs-attribute">blue</span> = (<span class="hljs-number">50</span>, <span class="hljs-number">153</span>, <span class="hljs-number">213</span>)

<span class="hljs-attribute">dis_width</span> = <span class="hljs-number">600</span> <span class="hljs-attribute">dis_height</span> = <span class="hljs-number">400</span>

<span class="hljs-attribute">dis</span> = pygame.display.set_mode((dis_width, dis_height)) <span class="hljs-attribute">pygame</span>.display.set_caption('Snake Game by Edureka')

<span class="hljs-attribute">clock</span> = pygame.time.Clock()

<span class="hljs-attribute">snake_block</span> = <span class="hljs-number">10</span> <span class="hljs-attribute">snake_speed</span> = <span class="hljs-number">15</span>

<span class="hljs-attribute">font_style</span> = pygame.font.SysFont(<span class="hljs-string">"bahnschrift"</span>, <span class="hljs-number">25</span>) <span class="hljs-attribute">score_font</span> = pygame.font.SysFont(<span class="hljs-string">"comicsansms"</span>, <span class="hljs-number">35</span>)

<span class="hljs-attribute">def</span> Your_score(score): <span class="hljs-attribute">value</span> = score_font.render(<span class="hljs-string">"Your Score: "</span> + str(score), True, yellow) <span class="hljs-attribute">dis</span>.blit(value,<span class="hljs-meta"> [0, 0])

def our_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])

def message(msg, color): mesg = font_style.render(msg, True, color) dis.blit(mesg, [dis_width / 6, dis_height / 3])

def gameLoop(): game_over = False game_close = False

x1 = dis_width / 2
y1 = dis_height / 2

x1_change = 0
y1_change = 0

snake_List = []</span>
<span class="hljs-attribute">Length_of_snake</span> = <span class="hljs-number">1</span>

<span class="hljs-attribute">foodx</span> = round(random.randrange(<span class="hljs-number">0</span>, dis_width - snake_block) / <span class="hljs-number">10</span>.<span class="hljs-number">0</span>) * <span class="hljs-number">10</span>.<span class="hljs-number">0</span>
<span class="hljs-attribute">foody</span> = round(random.randrange(<span class="hljs-number">0</span>, dis_height - snake_block) / <span class="hljs-number">10</span>.<span class="hljs-number">0</span>) * <span class="hljs-number">10</span>.<span class="hljs-number">0</span>

<span class="hljs-attribute">while</span> not game_over:

    <span class="hljs-attribute">while</span> game_close == True:
        <span class="hljs-attribute">dis</span>.fill(blue)
        <span class="hljs-attribute">message</span>(<span class="hljs-string">"You Lost! Press C-Play Again or Q-Quit"</span>, red)
        <span class="hljs-attribute">Your_score</span>(Length_of_snake - <span class="hljs-number">1</span>)
        <span class="hljs-attribute">pygame</span>.display.update()

        <span class="hljs-attribute">for</span> event in pygame.event.get():
            <span class="hljs-attribute">if</span> event.type == pygame.KEYDOWN:
                <span class="hljs-attribute">if</span> event.key == pygame.K_q:
                    <span class="hljs-attribute">game_over</span> = True
                    <span class="hljs-attribute">game_close</span> = False
                <span class="hljs-attribute">if</span> event.key == pygame.K_c:
                    <span class="hljs-attribute">gameLoop</span>()

    <span class="hljs-attribute">for</span> event in pygame.event.get():
        <span class="hljs-attribute">if</span> event.type == pygame.QUIT:
            <span class="hljs-attribute">game_over</span> = True
        <span class="hljs-attribute">if</span> event.type == pygame.KEYDOWN:
            <span class="hljs-attribute">if</span> event.key == pygame.K_LEFT:
                <span class="hljs-attribute">x1_change</span> = -snake_block
                <span class="hljs-attribute">y1_change</span> = <span class="hljs-number">0</span>
            <span class="hljs-attribute">elif</span> event.key == pygame.K_RIGHT:
                <span class="hljs-attribute">x1_change</span> = snake_block
                <span class="hljs-attribute">y1_change</span> = <span class="hljs-number">0</span>
            <span class="hljs-attribute">elif</span> event.key == pygame.K_UP:
                <span class="hljs-attribute">y1_change</span> = -snake_block
                <span class="hljs-attribute">x1_change</span> = <span class="hljs-number">0</span>
            <span class="hljs-attribute">elif</span> event.key == pygame.K_DOWN:
                <span class="hljs-attribute">y1_change</span> = snake_block
                <span class="hljs-attribute">x1_change</span> = <span class="hljs-number">0</span>

    <span class="hljs-attribute">if</span> x1 &gt;= dis_width or x1 &lt; <span class="hljs-number">0</span> or y1 &gt;= dis_height or y1 &lt; <span class="hljs-number">0</span>:
        <span class="hljs-attribute">game_close</span> = True
    <span class="hljs-attribute">x1</span> += x1_change
    <span class="hljs-attribute">y1</span> += y1_change
    <span class="hljs-attribute">dis</span>.fill(blue)
    <span class="hljs-attribute">pygame</span>.draw.rect(dis, green,<span class="hljs-meta"> [foodx, foody, snake_block, snake_block])
    snake_Head = []</span>
    <span class="hljs-attribute">snake_Head</span>.append(x1)
    <span class="hljs-attribute">snake_Head</span>.append(y1)
    <span class="hljs-attribute">snake_List</span>.append(snake_Head)
    <span class="hljs-attribute">if</span> len(snake_List) &gt; Length_of_snake:
        <span class="hljs-attribute">del</span> snake_List[<span class="hljs-number">0</span>]

    <span class="hljs-attribute">for</span> x in snake_List[:-<span class="hljs-number">1</span>]:
        <span class="hljs-attribute">if</span> x == snake_Head:
            <span class="hljs-attribute">game_close</span> = True

    <span class="hljs-attribute">our_snake</span>(snake_block, snake_List)
    <span class="hljs-attribute">Your_score</span>(Length_of_snake - <span class="hljs-number">1</span>)

    <span class="hljs-attribute">pygame</span>.display.update()

    <span class="hljs-attribute">if</span> x1 == foodx and y1 == foody:
        <span class="hljs-attribute">foodx</span> = round(random.randrange(<span class="hljs-number">0</span>, dis_width - snake_block) / <span class="hljs-number">10</span>.<span class="hljs-number">0</span>) * <span class="hljs-number">10</span>.<span class="hljs-number">0</span>
        <span class="hljs-attribute">foody</span> = round(random.randrange(<span class="hljs-number">0</span>, dis_height - snake_block) / <span class="hljs-number">10</span>.<span class="hljs-number">0</span>) * <span class="hljs-number">10</span>.<span class="hljs-number">0</span>
        <span class="hljs-attribute">Length_of_snake</span> += <span class="hljs-number">1</span>

    <span class="hljs-attribute">clock</span>.tick(snake_speed)

<span class="hljs-attribute">pygame</span>.quit()
<span class="hljs-attribute">quit</span>()

<span class="hljs-attribute">gameLoop</span>()</pre></div><p id="7950"><b>OUTPUT:</b></p><figure id="2389"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*J9ib7z9LYI-BM1dgrfZEow.png"><figcaption></figcaption></figure><p id="4978">With this, we have reached the end of this article on Snake Game in Python. I hope you are clear with all that has been shared with you in this article. <b><i>Make sure you practice as much as possible and revert your experience.</i></b></p><p id="3ba5">If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=django-interview-questions">Edureka’s official site.</a></p><p id="c46c">Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.</p><blockquote id="fdf0"><p>1. <a href="https://readmedium.com/machine-learning-classifier-c02fbd8400c9">Machine Learning Classifier in Python</a></p></blockquote><blockquote id="9411"><p>2. <a href="https://readmedium.com/python-scikit-learn-cheat-sheet-9786382be9f5">Python Scikit-Learn Cheat Sheet</a></p></blockquote><blockquote id="c6c2"><p>3. <a href="https://readmedium.com/python-libraries-for-data-science-and-machine-learning-1c502744f277">Machine Learning Tools</a></p></blockquote><blockquote id="d683"><p>4. <a href="https://readmedium.com/python-libraries-for-data-science-and-machine-learning-1c502744f277">Python Libraries For Data Science And Machine Learning</a></p></blockquote><blockquote id="fbc6"><p>5. <a href="https://readmedium.com/how-to-make-a-chatbot-in-python-b68fd390b219">Chatbot In Python</a></p></blockquote><blockquote id="eaa2"><p>6. <a href="https://readmedium.com/collections-in-python-d0bc0ed8d938">Python Collections</a></p></blockquote><blockquote id="5ea9"><p>7. <a href="https://readmedium.com/python-modules-abb0145a5963">Python Modules</a></p></blockquote><blockquote id="9d13"><p>8. <a href="https://readmedium.com/python-developer-skills-371583a69be1">Python developer Skills</a></p></blockquote><blockquote id="ed86"><p>9. <a href="https://readmedium.com/oops-interview-questions-621fc922cdf4">OOPs Interview Questions and Answers</a></p></blockquote><blockquote id="76dd"><p>10. <a href="https://readmedium.com/python-developer-resume-ded7799b4389">Resume For A Python Developer</a></p></blockquote><blockquote id="8d2d"><p>11. <a href="https://readmedium.com/exploratory-data-analysis-in-python-3ee69362a46e">Exploratory Data Analysis In Python</a></p></blockquote><blockquote id="30ee"><p>12. <a href="https://readmedium.com/python-turtle-module-361816449390">Snake Game With Python’s Turtle Module</a></p></blockquote><blockquote id="1eb9"><p>13. <a href="https://readmedium.com/python-developer-salary-ba2eff6a502e">Python Developer Salary</a></p></blockquote><blockquote id="5dbd"><p>14.<a href="https://readmedium.com/principal-component-analysis-69d7a4babc96"> Principal Component Analysis</a></p></blockquote><blockquote id="27ab"><p>15. <a href="https://readmedium.com/python-vs-cpp-c3ffbea01eec">Python vs C++</a></p></blockquote><blockquote id="3da7"><p>16. <a href="https://readmedium.com/scrapy-tutorial-5584517658fb">Scrapy Tutorial</a></p></blockquote><blockquote id="d5b4"><p>17. <a href="https://readmedium.com/scipy-tutorial-38723361ba4b">Python SciPy</a></p></blockquote><blockquote id="31ef"><p>18. <a href="https://readmedium.com/least-square-regression-40b59cca8ea7">Least Squares Regression Method</a></p></blockquote><blockquote id="eceb"><p>19. <a href="https://readmedium.com/jupyter-notebook-cheat-sheet-88f60d1aca7">Jupyter Notebook Cheat Sheet</a></p></blockquote><blockquote id="1d48"><p>20. <a href="https://readmedium.com/python-basics-f371d7fc0054">Python Basics</a></p></blockquote><blockquote id="80f1"><p>21. <a href="https://readmedium.com/python-pattern-programs-75e1e764a42f">Python Pattern Programs</a></p></blockquote><blockquote id="0d6f"><p>22. <a href="https://readmedium.com/generators-in-python-258f21e3d3ff">Generators in Python</a></p></blockquote><blockquote id="7a89"><p>23. <a href="https://readmedium.com/python-decorator-tutorial-bf7b21278564">Python Decorator</a></p></blockquote><blockquote id="fdeb"><p>24.<a href="https://readmedium.com/spyder-ide-2a91caac4e46"> Python Spyder IDE</a></p></blockquote><blockquote id="8d77"><p>25. <a href="https://readmedium.com/kivy-tutorial-9a0f02fe53f5">Mobile Applications Using Kivy In Python</a></p></blockquote><blockquote id="886a"><p>26. <a href="https://readmedium.com/best-books-for-python-11137561beb7">Top 10 Best Books To Learn & Practice Python</a></p></blockquote><blockquote id="2b79"><p>27. <a href="https://readmedium.com/robot-framework-tutorial-f8a75ab23cfd">Robot Framework With Python</a></p></blockquote><blockquote id="9957"><p>28. <a href="https://readmedium.com/socket-programming-python-bbac2d423bf9">What is Socket Programming in Python</a></p></blockquote><blockquote id="d426"><p>29. <a href="https://readmedium.com/django-interview-questions-a4df7bfeb7e8">Django Interview Questions and Answers</a></p></blockquote><blockquote id="4390"><p>30. <a href="https://readmedium.com/python-applications-18b780d64f3b">Top 10 Python Applications</a></p></blockquote><blockquote id="9dbc"><p>31. <a href="https://readmedium.com/hash-tables-and-hashmaps-in-python-3bd7fc1b00b4">Hash Tables and Hashmaps in Python</a></p></blockquote><blockquote id="c2a4"><p>32. <a href="https://readmedium.com/whats-new-python-3-8-7d52cda747b">Python 3.8</a></p></blockquote><blockquote id="244c"><p>33. <a href="https://readmedium.com/support-vector-machine-in-python-539dca55c26a">Support Vector Machine</a></p></blockquote><blockquote id="dfc4"><p>34. <a href="https://readmedium.com/python-tutorial-be1b3d015745">Python Tutorial</a></p></blockquote><p id="e047"><i>Originally published at <a href="https://www.edureka.co/blog/snake-game-with-pygame/">https://www.edureka.co</a> on October 22, 2019.</i></p></article></body>

How To implement Snake Game in Python using PyGame?

Snake Game in Python — Edureka

Yes, I know you all have played the Snake Game and definitely, you never wanted to lose. As kids, we all loved looking for cheats in order to never see the “Game Over” message but as techies, I know you would want to make this ‘Snake’ dance to your beats. This is what I will be showing you all in this article on Snake Game in Python. Before moving on, let’s have a quick look at all the sub-bits that build the Snake Game in Python:

  1. Installing Pygame
  2. Create the Screen
  3. Create the Snake
  4. Moving the Snake
  5. Game Over when Snake hits the boundaries
  6. Adding the Food
  7. Increasing the Length of the Snake
  8. Displaying the Score

Installing Pygame:

The first thing you will need to do in order to create games using Pygame is to install it on your systems. To do that, you can simply use the following command:

pip install pygame

Once that is done, just import Pygame and start off with your game development. Before moving on, take a look at the Pygame functions that have been used in this Snake Game along with their descriptions.

Create the Screen:

To create the screen using Pygame, you will need to make use of the display.set_mode() function. Also, you will have to make use of the init() and the quit() methods to initialize and uninitialize everything at the start and the end of the code. The update() method is used to update any changes made to the screen. There is another method i.e flip() that works similarly to the update() function. The difference is that the update() method updates only the changes that are made (however, if no parameters are passed, updates the complete screen) but the flip() method redoes the complete screen again.

CODE:

import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
pygame.display.update()
pygame.quit()
quit()

OUTPUT:

But when you run this code, the screen will appear, but it will immediately close as well. To fix that, you should make use of a game loop using the while loop before I actually quit the game as follows:

import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
pygame.display.update()
pygame.display.set_caption('Snake game by Edureka')
game_over=False
while not game_over:
    for event in pygame.event.get():
        print(event)   #prints out all the actions that take place on the screen
 
pygame.quit()
quit()

When you run this code, you will see that the screen that you saw earlier does not quit and also, it returns all the actions that take place over it. I have done that using the event.get() function. Also, I have named the screen as “Snake Game by Edureka” using the display.set_caption() function.

OUTPUT:

Now, you have a screen to play your Snake Game, but when you try to click on the close button, the screen does not close. This is because you have not specified that your screen should exit when you hit that close button. To do that, Pygame provides an event called “QUIT” and it should be used as follows:

import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
pygame.display.update()
pygame.display.set_caption('Snake game by Edureka')
game_over=False
while not game_over:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            game_over=True
 
pygame.quit()
quit()

So now your screen is all set. The next part is to draw our snake on the screen which is covered in the following topic.

Create the Snake:

To create the snake, I will first initialize a few color variables in order to color the snake, food, screen, etc. The color scheme used in Pygame is RGB i.e “Red Green Blue”. In case you set all these to 0’s, the color will be black and all 255’s will be white. So our snake will actually be a rectangle. To draw rectangles in Pygame, you can make use of a function called draw.rect() which will help yo draw the rectangle with the desired color and size.

import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
 
pygame.display.set_caption('Snake game by Edureka')
 
blue=(0,0,255)
red=(255,0,0)
 
game_over=False
while not game_over:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            game_over=True
    pygame.draw.rect(dis,blue,[200,150,10,10])
    pygame.display.update()
pygame.quit()
quit()

OUTPUT:

As you can see, the snakehead is created as a blue rectangle. The next step is to get your snake moving.

Moving the Snake:

To move the snake, you will need to use the key events present in the KEYDOWN class of Pygame. The events that are used over here are, K_UP, K_DOWN, K_LEFT, and K_RIGHT to make the snake move up, down, left and right respectively. Also, the display screen is changed from the default black to white using the fill() method.

I have created new variables x1_change and y1_change in order to hold the updating values of the x and y coordinates.

import pygame
 
pygame.init()
 
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
 
dis = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Snake Game by Edureka')
 
game_over = False
 
x1 = 300
y1 = 300
 
x1_change = 0       
y1_change = 0
 
clock = pygame.time.Clock()
 
while not game_over:
    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 = -10
                y1_change = 0
            elif event.key == pygame.K_RIGHT:
                x1_change = 10
                y1_change = 0
            elif event.key == pygame.K_UP:
                y1_change = -10
                x1_change = 0
            elif event.key == pygame.K_DOWN:
                y1_change = 10
                x1_change = 0
 
    x1 += x1_change
    y1 += y1_change
    dis.fill(white)
    pygame.draw.rect(dis, black, [x1, y1, 10, 10])
 
    pygame.display.update()
 
    clock.tick(30)
 
pygame.quit()
quit()

OUTPUT:

Game Over when Snake hits the boundaries:

In this snake game, if the player hits the boundaries of the screen, then he loses. To specify that, I have made use of an ‘if’ statement that defines the limits for the x and y coordinates of the snake to be less than or equal to that of the screen. Also, make a not over here that I have removed the hardcodes and used variables instead so that it becomes easy in case you want to make any changes to the game later on.

import pygame
import time
pygame.init()
 
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
 
dis_width = 800
dis_height  = 600
dis = pygame.display.set_mode((dis_width, dis_width))
pygame.display.set_caption('Snake Game by Edureka')
 
game_over = False
 
x1 = dis_width/2
y1 = dis_height/2
 
snake_block=10
 
x1_change = 0
y1_change = 0
 
clock = pygame.time.Clock()
snake_speed=30
 
font_style = pygame.font.SysFont(None, 50)
 
def message(msg,color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width/2, dis_height/2])
 
while not game_over:
    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
 
    if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
        game_over = True
 
    x1 += x1_change
    y1 += y1_change
    dis.fill(white)
    pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])
 
    pygame.display.update()
 
    clock.tick(snake_speed)
 
message("You lost",red)
pygame.display.update()
time.sleep(2)
 
pygame.quit()
quit()

OUTPUT:

Adding the Food:

Here, I will be adding some food for the snake and when the snake crosses over that food, I will have a message saying “Yummy!!”. Also, I will be making a small change wherein I will include the options to quit the game or to play again when the player loses.

import pygame
import time
import random
 
pygame.init()
 
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
 
dis_width = 800
dis_height = 600
 
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Edureka')
 
clock = pygame.time.Clock()
 
snake_block = 10
snake_speed = 30
 
font_style = pygame.font.SysFont(None, 30)
 
 
def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width/3, dis_height/3])
 
 
def gameLoop():  # creating a function
    game_over = False
    game_close = False
 
    x1 = dis_width / 2
    y1 = dis_height / 2
 
    x1_change = 0
    y1_change = 0
 
    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
 
    while not game_over:
 
        while game_close == True:
            dis.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
 
        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
 
        x1 += x1_change
        y1 += y1_change
        dis.fill(white)
        pygame.draw.rect(dis, blue, [foodx, foody, snake_block, snake_block])
        pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])
        pygame.display.update()
 
        if x1 == foodx and y1 == foody:
            print("Yummy!!")
        clock.tick(snake_speed)
 
    pygame.quit()
    quit()
 
 
gameLoop()

OUTPUT:

Terminal:

Increasing the Length of the Snake:

The following code will increase the size of our sake when it eats the food. Also, if the snake collides with his own body, the game is over and you ill see a message as “You Lost! Press Q-Quit or C-Play Again”. The length of the snake is basically contained in a list and the initial size that is specified in the following code is one block.

import pygame
import time
import random
 
pygame.init()
 
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
 
dis_width = 600
dis_height = 400
 
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Edureka')
 
clock = pygame.time.Clock()
 
snake_block = 10
snake_speed = 15
 
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
 
def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
 
 
def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])
 
 
def gameLoop():
    game_over = False
    game_close = False
 
    x1 = dis_width / 2
    y1 = dis_height / 2
 
    x1_change = 0
    y1_change = 0
 
    snake_List = []
    Length_of_snake = 1
 
    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
 
    while not game_over:
 
        while game_close == True:
            dis.fill(blue)
            message("You Lost! Press C-Play Again or Q-Quit", 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
 
        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]
 
        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True
 
        our_snake(snake_block, snake_List)
 
 
        pygame.display.update()
 
        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1
 
        clock.tick(snake_speed)
 
    pygame.quit()
    quit()
 
 
gameLoop()

OUTPUT:

Displaying the Score:

Last but definitely not the least, you will need to display the score of the player. To do this, I have created a new function as “Your_score”. This function will display the length of the snake subtracted by 1 because that is the initial size of the snake.

import pygame
import time
import random
 
pygame.init()
 
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
 
dis_width = 600
dis_height = 400
 
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Edureka')
 
clock = pygame.time.Clock()
 
snake_block = 10
snake_speed = 15
 
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
 
 
def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, yellow)
    dis.blit(value, [0, 0])
 
 
 
def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
 
 
def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])
 
 
def gameLoop():
    game_over = False
    game_close = False
 
    x1 = dis_width / 2
    y1 = dis_height / 2
 
    x1_change = 0
    y1_change = 0
 
    snake_List = []
    Length_of_snake = 1
 
    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
 
    while not game_over:
 
        while game_close == True:
            dis.fill(blue)
            message("You Lost! Press C-Play Again or Q-Quit", red)
            Your_score(Length_of_snake - 1)
            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
 
        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]
 
        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True
 
        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)
 
        pygame.display.update()
 
        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1
 
        clock.tick(snake_speed)
 
    pygame.quit()
    quit()
 
 
gameLoop()

OUTPUT:

With this, we have reached the end of this article on Snake Game in Python. I hope you are clear with all that has been shared with you in this article. Make sure you practice as much as possible and revert your experience.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.

1. Machine Learning Classifier in Python

2. Python Scikit-Learn Cheat Sheet

3. Machine Learning Tools

4. Python Libraries For Data Science And Machine Learning

5. Chatbot In Python

6. Python Collections

7. Python Modules

8. Python developer Skills

9. OOPs Interview Questions and Answers

10. Resume For A Python Developer

11. Exploratory Data Analysis In Python

12. Snake Game With Python’s Turtle Module

13. Python Developer Salary

14. Principal Component Analysis

15. Python vs C++

16. Scrapy Tutorial

17. Python SciPy

18. Least Squares Regression Method

19. Jupyter Notebook Cheat Sheet

20. Python Basics

21. Python Pattern Programs

22. Generators in Python

23. Python Decorator

24. Python Spyder IDE

25. Mobile Applications Using Kivy In Python

26. Top 10 Best Books To Learn & Practice Python

27. Robot Framework With Python

28. What is Socket Programming in Python

29. Django Interview Questions and Answers

30. Top 10 Python Applications

31. Hash Tables and Hashmaps in Python

32. Python 3.8

33. Support Vector Machine

34. Python Tutorial

Originally published at https://www.edureka.co on October 22, 2019.

Python
Pygame
Snake Games
Python Libraries
Python3
Recommended from ReadMedium