how to make snake game using python

Solutions on MaxInterview for how to make snake game using python by the best coders in the world

showing results for - "how to make snake game using python"
Eloi
28 Aug 2017
1#this code has asumed that you have intsalled pygame,time,random>
2import pygame
3import time
4import random
5 
6pygame.init()
7 
8white = (255, 255, 255)
9yellow = (255, 255, 102)
10black = (0, 0, 0)
11red = (213, 50, 80)
12green = (0, 255, 0)
13blue = (50, 153, 213)
14 
15dis_width = 600
16dis_height = 400
17 
18dis = pygame.display.set_mode((dis_width, dis_height))
19pygame.display.set_caption('Snake Game by Edureka')
20 
21clock = pygame.time.Clock()
22 
23snake_block = 10
24snake_speed = 15
25 
26font_style = pygame.font.SysFont("bahnschrift", 25)
27score_font = pygame.font.SysFont("comicsansms", 35)
28 
29 
30def Your_score(score):
31    value = score_font.render("Your Score: " + str(score), True, yellow)
32    dis.blit(value, [0, 0])
33 
34 
35 
36def our_snake(snake_block, snake_list):
37    for x in snake_list:
38        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
39 
40 
41def message(msg, color):
42    mesg = font_style.render(msg, True, color)
43    dis.blit(mesg, [dis_width / 6, dis_height / 3])
44 
45 
46def gameLoop():
47    game_over = False
48    game_close = False
49 
50    x1 = dis_width / 2
51    y1 = dis_height / 2
52 
53    x1_change = 0
54    y1_change = 0
55 
56    snake_List = []
57    Length_of_snake = 1
58 
59    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
60    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
61 
62    while not game_over:
63 
64        while game_close == True:
65            dis.fill(blue)
66            message("You Lost! Press C-Play Again or Q-Quit", red)
67            Your_score(Length_of_snake - 1)
68            pygame.display.update()
69 
70            for event in pygame.event.get():
71                if event.type == pygame.KEYDOWN:
72                    if event.key == pygame.K_q:
73                        game_over = True
74                        game_close = False
75                    if event.key == pygame.K_c:
76                        gameLoop()
77 
78        for event in pygame.event.get():
79            if event.type == pygame.QUIT:
80                game_over = True
81            if event.type == pygame.KEYDOWN:
82                if event.key == pygame.K_LEFT:
83                    x1_change = -snake_block
84                    y1_change = 0
85                elif event.key == pygame.K_RIGHT:
86                    x1_change = snake_block
87                    y1_change = 0
88                elif event.key == pygame.K_UP:
89                    y1_change = -snake_block
90                    x1_change = 0
91                elif event.key == pygame.K_DOWN:
92                    y1_change = snake_block
93                    x1_change = 0
94 
95        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
96            game_close = True
97        x1 += x1_change
98        y1 += y1_change
99        dis.fill(blue)
100        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
101        snake_Head = []
102        snake_Head.append(x1)
103        snake_Head.append(y1)
104        snake_List.append(snake_Head)
105        if len(snake_List) > Length_of_snake:
106            del snake_List[0]
107 
108        for x in snake_List[:-1]:
109            if x == snake_Head:
110                game_close = True
111 
112        our_snake(snake_block, snake_List)
113        Your_score(Length_of_snake - 1)
114 
115        pygame.display.update()
116 
117        if x1 == foodx and y1 == foody:
118            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
119            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
120            Length_of_snake += 1
121 
122        clock.tick(snake_speed)
123 
124    pygame.quit()
125    quit()
126 
127 
128gameLoop()
Elif
17 Nov 2019
1import turtle
2import random
3
4WIDTH = 500
5HEIGHT = 500
6FOOD_SIZE = 10
7DELAY = 100  # milliseconds
8
9offsets = {
10    "up": (0, 20),
11    "down": (0, -20),
12    "left": (-20, 0),
13    "right": (20, 0)
14}
15
16def reset():
17    global snake, snake_direction, food_pos, pen
18    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
19    snake_direction = "up"
20    food_pos = get_random_food_pos()
21    food.goto(food_pos)
22    # screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
23    move_snake()
24
25def move_snake():
26    global snake_direction
27
28    #  Next position for head of snake.
29    new_head = snake[-1].copy()
30    new_head[0] = snake[-1][0] + offsets[snake_direction][0]
31    new_head[1] = snake[-1][1] + offsets[snake_direction][1]
32
33    # Check self-collision
34    if new_head in snake[:-1]:  # Or collision with walls?
35        reset()
36    else:
37        # No self-collision so we can continue moving the snake.
38        snake.append(new_head)
39
40        # Check food collision
41        if not food_collision():
42            snake.pop(0)  # Keep the snake the same length unless fed.
43
44        #  Allow screen wrapping
45        if snake[-1][0] > WIDTH / 2:
46            snake[-1][0] -= WIDTH
47        elif snake[-1][0] < - WIDTH / 2:
48            snake[-1][0] += WIDTH
49        elif snake[-1][1] > HEIGHT / 2:
50            snake[-1][1] -= HEIGHT
51        elif snake[-1][1] < -HEIGHT / 2:
52            snake[-1][1] += HEIGHT
53
54        # Clear previous snake stamps
55        pen.clearstamps()
56
57        # Draw snake
58        for segment in snake:
59            pen.goto(segment[0], segment[1])
60            pen.stamp()
61
62        # Refresh screen
63        screen.update()
64
65        # Rinse and repeat
66        turtle.ontimer(move_snake, DELAY)
67
68def food_collision():
69    global food_pos
70    if get_distance(snake[-1], food_pos) < 20:
71        food_pos = get_random_food_pos()
72        food.goto(food_pos)
73        return True
74    return False
75
76def get_random_food_pos():
77    x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
78    y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
79    return (x, y)
80
81def get_distance(pos1, pos2):
82    x1, y1 = pos1
83    x2, y2 = pos2
84    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
85    return distance
86
87def go_up():
88    global snake_direction
89    if snake_direction != "down":
90        snake_direction = "up"
91
92def go_right():
93    global snake_direction
94    if snake_direction != "left":
95        snake_direction = "right"
96
97def go_down():
98    global snake_direction
99    if snake_direction != "up":
100        snake_direction = "down"
101
102def go_left():
103    global snake_direction
104    if snake_direction != "right":
105        snake_direction = "left"
106
107# Screen
108screen = turtle.Screen()
109screen.setup(WIDTH, HEIGHT)
110screen.title("Snake master play and have fanda")
111screen.bgcolor("yellow")
112screen.setup(500, 500)
113screen.tracer(0)
114
115# Pen
116pen = turtle.Turtle("square")
117pen.penup()
118
119# Food
120food = turtle.Turtle()
121food.shape("square")
122food.color("red")
123food.shapesize(FOOD_SIZE / 20)  # Default size of turtle "square" shape is 20.
124food.penup()
125
126# Event handlers
127screen.listen()
128screen.onkey(go_up, "Up")
129screen.onkey(go_right, "Right")
130screen.onkey(go_down, "Down")
131screen.onkey(go_left, "Left")
132
133# Let's go
134reset()
135turtle.done()
queries leading to this page
snake code for pythonsnake game with basic pythonhow to make snake in pythonsnake game in pythonprogram to make a snake game in pythonsnake code pyhtonsnake game using python descriptionhow to make snake game using pythonbest snake game pythonhow to make a snake game in tynker pythonpytho snake game codecode snake pythonsnake gamein pythonpython program of snake gamesnake game code in pythonpython snake gamefull code to implement snake game in pythonsnake python gamepython snake game tutorialsnake game in python codesnake game pythonsnake game code pythonsnake pygame code pythonpython to create snake gamesnake code pythonsnake game on python codesnake code python pygamemake snake game in pythonsource code for snake game in pythonpython snake game codesnake game python pygame codepython snake game libpython code for snake gamepython code for snakepython program for snake gamehow to make a snake game using python only using pythonsnake game 2b coding in pythoncoding snake in pythonsimple snake python codepython code for simple snake gamepython snake game source codesnake game python codecreate snake game with pythonpython snake game downloadsnake code game pythonimplement snake game in pythonmultiplayer snake game pythonpython game code snakesnake game python source codeprograming snake pythonpython snake game 5chow to create a snake game in pythonsnake game by pythonsnake game with pythonsnake game in python description pygame python snake game codesnake game in python 3snake game python game tutorialsnake game python gamepycode python for snakesnake game with python easycode for snake game in pythonhow to write the snake game in pythonpython code scripts for snake gamesnake game pythonhow to create a snake game with pythonpython code for a snake gamesnake game tutorial python pygamehow to create snake game in pythongame snake python codesnake python codehow to make a snake game in pythonsnake game project in pythonsnake game using pythonsnake simple game pythonhow code snake pythoncan you make snake in python 3simple snake game pythonmake a snake game in pythonsnake game python pythonhow to make snake game in pythonsnake game with python 3how to code snake game in pythonsnake game basic pythonprogram snake in pythonhow to code snake in pythonpython snake codepython snake game terminalpython how to mmake a snake gamepython code snake gamehpw to make a snake game with pythonhow to make snake game using python