Snake

Tags: pgzero, game

https://simplegametutorials.github.io/pygamezero/

snake.py
  1import pgzero, pgzrun
  2import random
  3
  4
  5# SETTINGS {{{
  6def move_food():# {{{
  7    global food_position
  8    possible_food_positions = []
  9
 10    for food_x in range(grid_x_count):
 11        for food_y in range(grid_y_count):
 12            possible = True
 13
 14            for segment in snake_segments:
 15                if food_x == segment['x'] and food_y == segment['y']:
 16                    possible == False
 17
 18                if possible:
 19                    possible_food_positions.append({'x': food_x, 'y': food_y})
 20
 21    food_position = random.choice(possible_food_positions)
 22
 23    
 24
 25
 26    # }}}
 27def reset():# {{{
 28    global timer
 29    global direction_queue
 30    global snake_segments
 31    global snake_alive
 32
 33    snake_alive =  True
 34
 35    timer = 0
 36
 37    snake_segments = [
 38            {'x': 2, 'y':1},
 39            {'x': 1, 'y':1},
 40            {'x': 0, 'y':1},
 41            ]
 42
 43    direction_queue = ['right']
 44    move_food()
 45    # }}}
 46
 47grid_x_count = 24
 48grid_y_count = 16
 49cell_size = 15
 50
 51WIDTH = grid_x_count * cell_size
 52HEIGHT = grid_y_count * cell_size
 53reset()
 54# }}}
 55# DRAW {{{
 56def draw():
 57
 58    def draw_cell(x, y, color): # {{{
 59        screen.draw.filled_rect(
 60                Rect (
 61                    x * cell_size,
 62                    y * cell_size,
 63                    cell_size -1,
 64                    cell_size -1,
 65                    ),
 66                color=color
 67                ) # }}}
 68
 69    screen.fill((0, 0, 0))
 70    screen.draw.filled_rect(
 71            Rect (0, 0, grid_x_count * cell_size, grid_y_count * cell_size),
 72            color=(70, 70, 70)
 73            )
 74
 75    draw_cell(food_position['x'], food_position['y'], color=(255, 76, 76))
 76    color=(165, 255, 81)
 77    if not snake_alive: color=(140, 140, 140)
 78    for segment in snake_segments: draw_cell(segment['x'], segment['y'], color)
 79    draw_cell(snake_segments[0]['x'], snake_segments[0]['y'], color=(165, 255, 220))
 80
 81    for index, direction in enumerate(direction_queue):
 82        screen.draw.text(
 83                '%d: %s' % (index, direction), 
 84                (cell_size, WIDTH - (cell_size + cell_size * index))
 85                )
 86# }}}
 87# UPDATE {{{
 88def update(dt):
 89    global timer
 90    global food_position
 91    global snake_alive
 92
 93    timer += dt
 94
 95    if snake_alive:
 96        if timer >= 0.15: 
 97            timer = 0
 98            # print("tick")
 99            if len (direction_queue) > 1: direction_queue.pop(0)
100
101            next_x_position = snake_segments[0]['x']
102            next_y_position = snake_segments[0]['y']
103
104            direction = direction_queue[0]
105            if direction == 'right': 
106                next_x_position += 1
107                if next_x_position >= grid_x_count:
108                    next_x_position = 0
109
110            elif direction == 'left': 
111                next_x_position -= 1
112                if next_x_position < 0:
113                    next_x_position = grid_x_count
114
115            elif direction == 'down': 
116                next_y_position += 1
117                if next_y_position >= grid_y_count:
118                    next_y_position = 0
119
120            elif direction == 'up': 
121                next_y_position -= 1
122                if next_y_position < 0:
123                    next_y_position = grid_y_count -1
124
125
126            can_move = True
127
128            for segment in snake_segments[:-1]:
129                if next_x_position == segment['x'] and next_y_position == segment['y']:
130                    can_move = False
131
132            if can_move:
133                snake_segments.insert(0, {'x': next_x_position, 'y': next_y_position})
134
135
136                test = snake_segments[0]['x'] == food_position['x'] and snake_segments[0]['y'] ==  food_position['y']
137                if test:
138                    move_food()
139                else:
140                    snake_segments.pop()
141            else:
142                snake_alive = False
143    elif timer >= 2:
144        reset()
145
146# }}}
147# EVENT HOOKS {{{
148def on_key_down(key): # {{{
149    global direction
150    last_direction = direction_queue[-1]
151
152    if key == keys.A and not (last_direction in ('right', 'left')):
153        direction_queue.append('left')
154    elif key == keys.D and not (last_direction in ('right', 'left')):
155        direction_queue.append('right')
156    elif key == keys.W and not (last_direction in ('up', 'down')):
157        direction_queue.append('up')
158    elif key == keys.S and not (last_direction in ('up', 'down')):
159        direction_queue.append('down')
160    # }}}
161# }}}
162
163pgzrun.go()