python snake game code

Solutions on MaxInterview for python snake game code by the best coders in the world

showing results for - "python snake game code"
Elisa
22 Jan 2018
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()