Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»Snake Game using PyGame in Python
    python

    Snake Game using PyGame in Python

    April 7, 2023No Comments15 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Python implementation of the Snake Game using PyGame

    In the following walkthrough, we will learn how to create a Snake Game by using the PyGame package in the programming language Python.

    Nevertheless, before we get started, let’s first have a quick review of what the Snake Game is.

    is.

    The arcade version of the video game known as

    A Brief Overview of the Snake Game

    Snake was first introduced in the late 1970s. In 1998, it became the standard game that was pre-loaded onto Nokia mobile phones. The primary purpose of the game is for the player to take control of a long, slender creature that resembles a snake and moves about on a bounded plane while attempting to gather the most amount of fruits possible without colliding with the wall or oneself. The head of the snake may be controlled by the player in any one of four directions (up, down, left, or right), and the body of the snake will move in that direction. The complexity of the game will increase each time the snake consumes a new item of food since its tail will continue to grow longer.

    The process of learning how to make a video game is both intriguing and enjoyable. When first getting started with Python or the PyGame module, making a Snake game might be a tough task. Any newbie programmer should take on the task of creating a game based on the Snake franchise since it is one of the simpler projects available.

    Now, let us have a little discussion on the Python game known as PyGame.

    library

    Understanding the PyGame library

    The PyGame library is a collection of Python modules that may be used to create video games. It is compatible with several platforms. The majority of what makes up PyGame are computer graphics and sound libraries that are intended to be used in conjunction with the programming language Python. This library was developed by Pete Shinners in an official capacity as a replacement for PySDL. It is appropriate to design client-side programs that have the possibility of being packaged in a standalone

    executable.

    How to install the PyGame library?

    On a command prompt or terminal, use the following command to install the PyGame library with the PIP installer. You may do this by following the instructions below. Syntax:



    1. # installing the PyGame library




    2. $ pip install pygame

    When the installation has been finished, we will be able to determine whether or not the pygame library was installed correctly by generating a new Python program file and importing the pygame module. This will allow us to do so.

    The portion of code that illustrates the aforementioned concept may be found below. File: verify.py



    1. import


      pygame

    Now that we have finished editing the file, let’s save it and then execute the following command on the command prompt or terminal. Syntax:



    1. $ python verify.py

    If the software does not report any importing errors once the library has been installed, then the installation was successful. In the event that an error is thrown, you should attempt to reload the library and think about looking at their official

    documentation.

    Prerequisites of the Project

    Let’s take a quick look at the project’s requirements now that we have successfully installed the necessary library. The following is a list of the modules that were necessary for the

    project:


    1. PyGame:

      This module will allow us to develop the game.

    2. Random:

      This module will allow us to generate random numbers, print a random value for a list or string, and more.

    3. Time:

      This module will allow us to work with time.

    Developing the Snake Game using PyGame

    After we have completed all of the requirements for the project, we will move on to the next step, which is the creation of the game. The process of developing the Python version of the Snake Game has been broken down into the progressive manner by our team. The following are the actions that need to be taken: Step 1: In the very first step, we will import the necessary modules. Step 2: After that, we will specify the required variables for the application Step 3: After that, we will initialize the pygame for the application Step 4: After that, we will initialize the sizes and locations of the game objects. In the fifth step, we will proceed to identify the essential functionalities that must be included in order for the game to be playable. In the sixth and last step, we will establish the application’s primary functionality, also known as the game loop.

    Today we shall comprehend the measures that were previously taken in

    detail.

    Importing the required modules

    First things first, we will begin the process of developing the game by loading the essential modules. At this step, we will also import the time and random modules in addition to the pygame module.

    Let us take into consideration the following piece of code that demonstrates the same thing. File: snake.py

    Explanation: W01A1@@3 Explanation:

    In order to build the game, we have imported the pygame module, which can be seen in the preceding bit of code. After that, the time module was imported so that we could control the time. In the end, we were successful in importing the random module so that we could produce the objects in the

    game.

    Defining the necessary variables for the game

    We are going to begin by defining some of the game’s required variables right now. The pace of the snake, the screen’s width and height, and the colors that will be used in the program are all examples of these variables.

    Let’s have a look at the following bit of code that illustrates the same thing, shall we? File: snake.py

    Explanation:



    1. # defining the game variables




    2. speed_of_snake =

      15






    3. # defining the size of the window




    4. SCREEN_WIDTH =

      700




    5. SCREEN_HEIGHT =

      460






    6. # defining  the colors




    7. midnight_blue = pygame.Color(

      25


      ,


      25


      ,


      112


      )


    8. mint_cream = pygame.Color(

      245


      ,


      255


      ,


      250


      )


    9. crimson_red = pygame.Color(

      220


      ,


      20


      ,


      60


      )


    10. lawn_green = pygame.Color(

      124


      ,


      252


      ,


      0


      )


    11. orange_red = pygame.Color(

      255


      ,


      69


      ,


      0


      )

    Related:

    The variable that stores the speed of the snake has been defined in the line of code that was just shown to you. After that, we have established the width as well as the height of the window. Using the use of the Color() class provided by pygame, we have at long last specified a few colors, including white, black, red, green, and blue.

    module.

    Initializing the pygame for the application

    Now that pygame has been loaded, we will initialize it by using the init() method, and we will use the pygame.display module to construct the main window that will show how the game is being played. In addition to this, we will use the pygame.time module in order to determine the game’s frame rates.

    Let’s have a look at the following bit of code to better see how the functionality is really implemented. File: snake.py

    Explanation:



    1. # initializing the pygame window using the pygame.init() function




    2. pygame.init()



    3. # using the set_mode() function of the pygame.display module to set the size of the screen




    4. display_screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))



    5. # setting the title of the application using the set_caption() function




    6. pygame.display.set_caption(

      ‘SNAKE – JAVATPOINT’


      )




    7. # creating an object of the Clock() class of the pygame.time module




    8. game_clock = pygame.time.Clock()

    Related:

    The pygame window has been initialized by using the init() method, which can be seen in the above bit of code. After that, we adjusted the dimensions of the screen by using the set mode() method that is included in the pygame.display module. After that, in order to set the application’s title, we made use of the set caption() method that is included in the pygame.display module. At long last, an instance of the Clock() class inside the pygame.time module has been constructed by us in order to establish the refresh rate for the

    game.

    Initializing the sizes and positions of the game objects

    Adding the items to the game, as well as configuring their sizes and locations, is the next step. The fruit and the snake are both included in these things. To begin, we are going to determine the initial location of the snake as well as its size. In addition to this, we will move the fruits to the desired location and ensure that their spawn flag is set to True. In addition to this, we will determine the default position of the snake’s head.

    Let’s have a look at the following bit of code that illustrates the same thing, shall we? File: snake.py

    Explanation of



    1. # defining the default position of the snake




    2. position_of_snake = [

      100


      ,


      50


      ]




    3. # defining the first four blocks of snake body




    4. body_of_snake = [

    5. [

      100


      ,


      50


      ],


    6. [

      90


      ,


      50


      ],


    7. [

      80


      ,


      50


      ],


    8. [

      70


      ,


      50


      ]


    9. ]



    10. # position of the fruit




    11. position_of_fruit = [

    12. random.randrange(

      1


      , (SCREEN_WIDTH//


      10


      )) *


      10


      ,


    13. random.randrange(

      1


      , (SCREEN_HEIGHT//


      10


      )) *


      10




    14. ]

    15. spawning_of_fruit =

      True






    16. # setting the default direction of the snake towards RIGHT




    17. initial_direction =

      ‘RIGHT’




    18. snake_direction = initial_direction

    Format:

    The default location of the snake has been specified in the piece of code that was just shown to you. After defining these first four sections of the snake’s body, we are now finished. After that, the location of the fruit has been specified, and the spawning of fruit variable has had its value changed to True. Also, we have configured the starting course of the snake to go in the right direction.

    .

    Defining the necessary functions of the game

    It is time for us to specify some needed functions at this point, seeing as how we have already gone through the basic needs of the game. A function will be defined to show the player’s score, and another function will be defined to end the game. The actual operation of these functions in the system will now be shown to us.

    detail.

    Function to display the score of the player

    The very first function that we will write will provide us the ability to show the player’s current score.

    Let’s have a look at the following bit of code that illustrates the same thing, shall we? File: snake.py

    Explanation:



    1. # initial score




    2. player_score =

      0






    3. # defining the functions





    4. # function to display the score





    5. def


      display_score(selection, font_color, font_style, font_size):




    6. # creating the font object




    7. score_font_style = pygame.font.SysFont(font_style, font_size)



    8. # creating the display surface object




    9. score_surface = score_font_style.render(

      ‘Your Score : ‘


      + str(player_score),


      True


      , font_color)




    10. # creating a rectangular object for the text placement




    11. score_rectangle = score_surface.get_rect()



    12. # displaying the text




    13. display_screen.blit(score_surface, score_rectangle)

    Related:

    With the line of code that you just read, we have constructed a variable that will store the number 0 when it is first assigned to the score. Next, we went ahead and built a function called display score(), which takes in many arguments including the text that was chosen as well as its color, style, and size. Under the context of this function, a font object was produced by us. After that, we have made use of the render() method to produce a backdrop surface, which will undergo modifications anytime the score is revised. After that, we fashioned a rectangle object for use in the positioning of the text. At long last, we have successfully shown the score on the main screen by using the blit() technique.

    screen.

    Function to over the game

    When the snake collides with a wall or with itself, the second function that we construct will take over, showing the final score and quitting the program.

    Let’s have a look at the following bit of code that illustrates the same thing, shall we? File: snake.py

    Explanation of



    1. # function to over the game





    2. def


      game_over():




    3. # creating the font object




    4. game_over_font_style = pygame.font.SysFont(

      ‘times new roman’


      ,


      50


      )




    5. # creating the display surface object




    6. game_over_surface = game_over_font_style.render(


    7. ‘Your Score is : ‘


      + str(player_score),


      True


      , crimson_red


    8. )



    9. # creating a rectangular object for the text placement




    10. game_over_rectangle = game_over_surface.get_rect()



    11. # setting the position of the text




    12. game_over_rectangle.midtop = (SCREEN_WIDTH/

      2


      , SCREEN_HEIGHT/


      4


      )




    13. # displaying the text on the screen




    14. display_screen.blit(game_over_surface, game_over_rectangle)



    15. # using the flip() function to update the small portion of the screen




    16. pygame.display.flip()



    17. # suspending the execution of the current thread for 2 seconds




    18. time.sleep(

      2


      )




    19. # calling the quit() function




    20. pygame.quit()



    21. # quiting the application




    22. quit()

    Format:

    The line of code that you just looked at contains the definition of a method that we called game over(). Within the context of this function, we have developed a font object in order to show the scores. In addition to that, we have developed text surfaces in order to represent the scores. After that, we made sure that the text was centered in the playable area by using the blit() technique, and we displayed the final scores on the screen that was previously utilized. After that, we made advantage of the flip() method to bring the score up to date by modifying the surface. At long last, we used the sleep() method of the time module to pause the execution of the currently active threat for two seconds, and then we used the quit() function to terminate the process.

    application.

    Creating the Game Loop to run the application

    Now that we have completed all of the prerequisites for developing the game, it is time for us to write the primary function, also known as the game loop, in order to put the program into action. Because of this loop, everything that we have generated will be rendered, and both functions will be implemented properly.

    Let us analyze the following bit of code, which demonstrates how the game loop should be implemented. File: snake.py

    Explanation for W01A1@@9:

    After that, in the preceding bit of code, we have changed the value of the game run flag to True and are now running the game with the help of the while loop. In this loop, we have iterated over the list of events and checked to see whether the player asked to exit the program. If they did, we have continued the process as before and changed the flag value to False. We have also determined whether or not the key is responsible for the movement of the snake, and we have established the unique condition that stipulates the snake should not be permitted to go in the opposite direction immediately. After that, we searched for the collision that occurred between the snake and the fruit, and when we found it, we added one to the score, which caused a fresh fruit to appear. After that, we checked to see whether the snake had collided with a wall, and if it had, we invoked the game over() method. In addition to that, we tested to see whether the snake was able to strike itself before calling the game over() method once again. After that, the display score() method was used so that the scores could be shown to the audience. After that, we refreshed the game screen by using the update() method, and we synchronized the game’s refresh rate with the snake’s movement pace. At long last, we have successfully exited the while loop and used the quit() method.

    We are pleased to announce that the code for the Snake game has been successfully developed. We are now able to save the file, and in order to execute the program, we will need to type the following command into a command shell or terminal. Syntax:



    1. $ python snake.py

    But before we get to the section where we discuss the outcome, let’s take a quick look at the whole project code for the “Snake game using PyGame

    “.

    The Complete Project Code

    The whole piece of code for the “Snake game using PyGame in Python” project is going to be shown to us today. File: snake.py



    1. # importing the necessary modules





    2. import


      pygame


      # importing the pygame module





    3. import


      time


      # importing the time module





    4. import


      random


      # importing the random module






    5. # defining the speed of the snake




    6. speed_of_snake =

      15






    7. # defining the size of the window




    8. SCREEN_WIDTH =

      700




    9. SCREEN_HEIGHT =

      460






    10. # defining  the colors




    11. midnight_blue = pygame.Color(

      25


      ,


      25


      ,


      112


      )


    12. mint_cream = pygame.Color(

      245


      ,


      255


      ,


      250


      )


    13. crimson_red = pygame.Color(

      220


      ,


      20


      ,


      60


      )


    14. lawn_green = pygame.Color(

      124


      ,


      252


      ,


      0


      )


    15. orange_red = pygame.Color(

      255


      ,


      69


      ,


      0


      )




    16. # initializing the pygame window using the pygame.init() function




    17. pygame.init()



    18. # using the set_mode() function of the pygame.display module to set the size of the screen




    19. display_screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))



    20. # setting the title of the application using the set_caption() function




    21. pygame.display.set_caption(

      ‘SNAKE – JAVATPOINT’


      )




    22. # creating an object of the Clock() class of the pygame.time module




    23. game_clock = pygame.time.Clock()



    24. # defining the default position of the snake




    25. position_of_snake = [

      100


      ,


      50


      ]




    26. # defining the first four blocks of snake body




    27. body_of_snake = [

    28. [

      100


      ,


      50


      ],


    29. [

      90


      ,


      50


      ],


    30. [

      80


      ,


      50


      ],


    31. [

      70


      ,


      50


      ]


    32. ]



    33. # position of the fruit




    34. position_of_fruit = [

    35. random.randrange(

      1


      , (SCREEN_WIDTH//


      10


      )) *


      10


      ,


    36. random.randrange(

      1


      , (SCREEN_HEIGHT//


      10


      )) *


      10




    37. ]

    38. spawning_of_fruit =

      True






    39. # setting the default direction of the snake towards RIGHT




    40. initial_direction =

      ‘RIGHT’




    41. snake_direction = initial_direction



    42. # initial score




    43. player_score =

      0






    44. # defining the functions





    45. # function to display the score





    46. def


      display_score(selection, font_color, font_style, font_size):




    47. # creating the font object




    48. score_font_style = pygame.font.SysFont(font_style, font_size)



    49. # creating the display surface object




    50. score_surface = score_font_style.render(

      ‘Your Score : ‘


      + str(player_score),


      True


      , font_color)




    51. # creating a rectangular object for the text placement




    52. score_rectangle = score_surface.get_rect()



    53. # displaying the text




    54. display_screen.blit(score_surface, score_rectangle)



    55. # function to over the game





    56. def


      game_over():




    57. # creating the font object




    58. game_over_font_style = pygame.font.SysFont(

      ‘times new roman’


      ,


      50


      )




    59. # creating the display surface object




    60. game_over_surface = game_over_font_style.render(


    61. ‘Your Score is : ‘


      + str(player_score),


      True


      , crimson_red


    62. )



    63. # creating a rectangular object for the text placement




    64. game_over_rectangle = game_over_surface.get_rect()



    65. # setting the position of the text




    66. game_over_rectangle.midtop = (SCREEN_WIDTH/

      2


      , SCREEN_HEIGHT/


      4


      )




    67. # displaying the text on the screen




    68. display_screen.blit(game_over_surface, game_over_rectangle)



    69. # using the flip() function to update the small portion of the screen




    70. pygame.display.flip()



    71. # suspending the execution of the current thread for 2 seconds




    72. time.sleep(

      2


      )




    73. # calling the quit() function




    74. pygame.quit()



    75. # quiting the application




    76. quit()



    77. # setting the run flag value to True




    78. game_run =

      True






    79. # the game loop





    80. # using the while loop





    81. while


      game_run:



    82. # iterating through the events in the pygame.event module





    83. for


      event


      in


      pygame.event.get():



    84. # setting the variable value to False if the event’s type is equivalent to pygame’s QUIT constant





    85. if


      event.type == pygame.QUIT:



    86. # setting the flag value to False




    87. game_run =

      False






    88. # setting the variable value either to UP, DOWN, LEFT, or RIGHT





    89. # if the event’s type is equivalent to pygame’s KEYDOWN constant,





    90. # and any of the stated keys is pressed





    91. if


      event.type == pygame.KEYDOWN:



    92. if


      event.key == pygame.K_UP:


    93. snake_direction =

      ‘UP’





    94. if


      event.key == pygame.K_DOWN:


    95. snake_direction =

      ‘DOWN’





    96. if


      event.key == pygame.K_LEFT:


    97. snake_direction =

      ‘LEFT’





    98. if


      event.key == pygame.K_RIGHT:


    99. snake_direction =

      ‘RIGHT’






    100. # neglecting the action taken if the key of opposite direction is pressed





    101. if


      snake_direction ==


      ‘UP’




      and


      initial_direction !=


      ‘DOWN’


      :


    102. initial_direction =

      ‘UP’





    103. if


      snake_direction ==


      ‘DOWN’




      and


      initial_direction !=


      ‘UP’


      :


    104. initial_direction =

      ‘DOWN’





    105. if


      snake_direction ==


      ‘LEFT’




      and


      initial_direction !=


      ‘RIGHT’


      :


    106. initial_direction =

      ‘LEFT’





    107. if


      snake_direction ==


      ‘RIGHT’




      and


      initial_direction !=


      ‘LEFT’


      :


    108. initial_direction =

      ‘RIGHT’






    109. # updating the position of the snake for every direction





    110. if


      initial_direction ==


      ‘UP’


      :


    111. position_of_snake[

      1


      ] -=


      10





    112. if


      initial_direction ==


      ‘DOWN’


      :


    113. position_of_snake[

      1


      ] +=


      10





    114. if


      initial_direction ==


      ‘LEFT’


      :


    115. position_of_snake[

      0


      ] -=


      10





    116. if


      initial_direction ==


      ‘RIGHT’


      :


    117. position_of_snake[

      0


      ] +=


      10






    118. # updating the body of the snake




    119. body_of_snake.insert(

      0


      , list(position_of_snake))



    120. if


      position_of_snake[


      0


      ] == position_of_fruit[


      0


      ]


      and


      position_of_snake[


      1


      ] == position_of_fruit[


      1


      ]:



    121. # incrementing the player’s score by 1




    122. player_score +=

      1




    123. spawning_of_fruit =

      False





    124. else


      :


    125. body_of_snake.pop()



    126. # randomly spawning the fruit





    127. if




      not


      spawning_of_fruit:


    128. position_of_fruit = [

    129. random.randrange(

      1


      , (SCREEN_WIDTH//


      10


      )) *


      10


      ,


    130. random.randrange(

      1


      , (SCREEN_HEIGHT//


      10


      )) *


      10




    131. ]

    132. spawning_of_fruit =

      True






    133. # filling the color on the screen




    134. display_screen.fill(mint_cream)



    135. # drawing the game objects on the screen





    136. for


      position


      in


      body_of_snake:


    137. pygame.draw.rect(display_screen, lawn_green, pygame.Rect(position[

      0


      ], position[


      1


      ],


      10


      ,


      10


      ))


    138. pygame.draw.rect(display_screen, orange_red, pygame.Rect(position_of_fruit[

      0


      ], position_of_fruit[


      1


      ],


      10


      ,


      10


      ))




    139. # conditions for the game to over





    140. if


      position_of_snake[


      0


      ] <


      0




      or


      position_of_snake[


      0


      ] > SCREEN_WIDTH –


      10


      :


    141. game_over()


    142. if


      position_of_snake[


      1


      ] <


      0




      or


      position_of_snake[


      1


      ] > SCREEN_HEIGHT –


      10


      :


    143. game_over()



    144. # touching the snake body





    145. for


      block


      in


      body_of_snake[


      1


      :]:



    146. if


      position_of_snake[


      0


      ] == block[


      0


      ]


      and


      position_of_snake[


      1


      ] == block[


      1


      ]:


    147. game_over



    148. # displaying the score continuously




    149. display_score(

      1


      , midnight_blue,


      ‘times new roman’


      ,


      20


      )




    150. # refreshing the game screen




    151. pygame.display.update()



    152. # refresh rate




    153. game_clock.tick(speed_of_snake)



    154. # calling the quit() function to quit the application




    155. pygame.quit()

    Output:

    Picture 1 shows the final product of the Snake Game developed using PyGame.

    Snake Game using PyGame in Python Picture 2: The Mechanisms Behind the Snake Game

    Snake Game using PyGame in Python Picture 3: The End of the Game

    Snake Game using PyGame in Python

    Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language Snake Game using PyGame in Python
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleDeque in Python
    Next Article An Effective Sales Page with Bootstrap 3

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.