{"id":133321,"date":"2023-04-24T15:52:42","date_gmt":"2023-04-24T15:52:42","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=1315485"},"modified":"2023-04-24T15:52:42","modified_gmt":"2023-04-24T15:52:42","slug":"python-snake-made-easy","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2023\/04\/24\/python-snake-made-easy\/","title":{"rendered":"Python Snake Made Easy"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1315485&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;title&quot;:&quot;Python Snake Made Easy&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/p><\/div>\n<p>This code creates a simple Snake game using the Pygame library in Python. <\/p>\n<p>The game starts with a small snake moving around the screen, controlled by arrow keys, eating randomly placed food items. Each time the snake eats food, it grows longer, and the game gets faster. <\/p>\n<p>The game ends if the snake collides with itself or the screen borders, and the player&#8217;s goal is to keep the snake growing as long as possible.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import pygame\nimport sys\nimport random # Initialize pygame\npygame.init() # Set screen dimensions\nWIDTH = 640\nHEIGHT = 480\nCELL_SIZE = 20 # Colors\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0) # Create the game screen\nscreen = pygame.display.set_mode((WIDTH, HEIGHT)) # Set the game clock\nclock = pygame.time.Clock() def random_food_position(): return (random.randint(0, (WIDTH-CELL_SIZE)\/\/CELL_SIZE) * CELL_SIZE, random.randint(0, (HEIGHT-CELL_SIZE)\/\/CELL_SIZE) * CELL_SIZE) def draw_snake(snake_positions): for pos in snake_positions: pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], CELL_SIZE, CELL_SIZE)) def draw_food(food_position): pygame.draw.rect(screen, RED, pygame.Rect(food_position[0], food_position[1], CELL_SIZE, CELL_SIZE)) def main(): snake_positions = [(100, 100), (80, 100), (60, 100)] snake_direction = (20, 0) food_position = random_food_position() game_speed = 10 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and snake_direction != (0, 20): snake_direction = (0, -20) elif event.key == pygame.K_DOWN and snake_direction != (0, -20): snake_direction = (0, 20) elif event.key == pygame.K_LEFT and snake_direction != (20, 0): snake_direction = (-20, 0) elif event.key == pygame.K_RIGHT and snake_direction != (-20, 0): snake_direction = (20, 0) new_head = (snake_positions[0][0] + snake_direction[0], snake_positions[0][1] + snake_direction[1]) if new_head in snake_positions or new_head[0] &lt; 0 or new_head[0] >= WIDTH or new_head[1] &lt; 0 or new_head[1] >= HEIGHT: break snake_positions.insert(0, new_head) if new_head == food_position: food_position = random_food_position() game_speed += 1 else: snake_positions.pop() screen.fill(WHITE) draw_snake(snake_positions) draw_food(food_position) pygame.display.update() clock.tick(game_speed) if __name__ == \"__main__\": main()\n<\/pre>\n<p>This simple implementation of the classic Snake game uses the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-install-pygame-on-pycharm\/\" data-type=\"post\" data-id=\"35078\" target=\"_blank\">Pygame library<\/a> in Python &#8212; here&#8217;s how I quickly lost in the game:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"634\" height=\"506\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/04\/snake_py.gif\" alt=\"\" class=\"wp-image-1315513\"\/><\/figure>\n<\/div>\n<p>Here&#8217;s a brief explanation of each part of the code:<\/p>\n<ol>\n<li>Import libraries:\n<ul>\n<li><code>pygame<\/code> for creating the game window and handling events, <\/li>\n<li><code>sys<\/code> for system-specific parameters and functions, and <\/li>\n<li><code>random<\/code> for generating random numbers.<\/li>\n<\/ul>\n<\/li>\n<li>Initialize <code>pygame<\/code> with <code>pygame.init()<\/code>.<\/li>\n<li>Set screen dimensions and cell size. The <code>WIDTH<\/code>, <code>HEIGHT<\/code>, and <code>CELL_SIZE<\/code> constants define the game window size and the size of each cell (both snake segments and food).<\/li>\n<li>Define color constants <code>WHITE<\/code>, <code>GREEN<\/code>, and <code>RED<\/code> as RGB tuples.<\/li>\n<li>Create the game screen with <code>pygame.display.set_mode((WIDTH, HEIGHT))<\/code>.<\/li>\n<li>Set the game clock with <code>pygame.time.Clock()<\/code> to control the game&#8217;s frame rate.<\/li>\n<li>Define the <code>random_food_position()<\/code> function to generate a random food position on the grid, ensuring it&#8217;s aligned with the <code>CELL_SIZE<\/code>.<\/li>\n<li>Define <code>draw_snake(snake_positions)<\/code> function to draw the snake&#8217;s body segments at their respective positions using green rectangles.<\/li>\n<li>Define <code>draw_food(food_position)<\/code> function to draw the food as a red rectangle at its position.<\/li>\n<li>Define the <code>main()<\/code> function, which contains the main game loop and logic.\n<ul>\n<li>Initialize the snake&#8217;s starting position, direction, food position, and game speed.<\/li>\n<li>The <code>while True<\/code> loop is the main game loop that runs indefinitely until the snake collides with itself or the screen borders.<\/li>\n<li>Handle events like closing the game window or changing the snake&#8217;s direction using arrow keys.<\/li>\n<li>Update the snake&#8217;s position based on its current direction.<\/li>\n<li>Check for collisions with itself or the screen borders, breaking the loop if a collision occurs.<\/li>\n<li>If the snake&#8217;s head is at the food position, generate a new food position and increase the game speed. Otherwise, remove the last snake segment.<\/li>\n<li>Update the game display by filling the screen with a white background, drawing the snake and food, and updating the display.<\/li>\n<li>Control the game speed using <code>clock.tick(game_speed)<\/code>.<\/li>\n<\/ul>\n<\/li>\n<li>Run the <code>main()<\/code> function when the script is executed by checking if <code>__name__ == \"__main__\"<\/code>.<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) This code creates a simple Snake game using the Pygame library in Python. The game starts with a small snake moving around the screen, controlled by arrow keys, eating randomly placed food items. Each time the snake eats food, it grows longer, and the game gets faster. The game ends if [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,857],"tags":[73,468,528],"class_list":["post-133321","post","type-post","status-publish","format-standard","hentry","category-games","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/133321","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=133321"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/133321\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=133321"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=133321"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=133321"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}