I am creating Snake game in pygame using Sprite logic
how do i chain the movement of the snake? another question on this has been answered here but i cant apply it to my code: see here
the minimal example above works. try it first and you will see my issue :) the snake grows on collision with the red food… but its movement does not chain
thank you
JavaScript
x
98
98
1
import pygame
2
from random import randint
3
from sys import exit
4
5
pygame.init()
6
game_active = True #start the game on the Welcome Screen
7
clock = pygame.time.Clock() #an object to track time, for fps
8
9
10
def display_surface():
11
"""function to create the main window"""
12
disp_surface = pygame.display.set_mode(size = (610, 700)) #creates a main display window
13
pygame.display.set_caption("Snake")
14
return disp_surface
15
disp_surface = display_surface() #MUST return this immediately so it can be pushed to pygame.display.update()
16
17
class snake(pygame.sprite.Sprite):
18
def __init__(self, x_pos = 300, y_pos = 300):
19
#Access the super class of Sprite
20
super().__init__()
21
image1 = pygame.image.load("square1.png").convert_alpha()
22
self.x_pos = x_pos
23
self.y_pos = y_pos
24
25
self.image = image1
26
self.rect = self.image.get_rect(x = x_pos, y = y_pos)
27
28
def update(self, left, right, up, down):
29
"""defines the movement of the snake using arrow keys"""
30
if left:
31
self.rect.left -= 1
32
if right:
33
self.rect.right += 1
34
if up:
35
self.rect.top -= 1
36
if down:
37
self.rect.bottom += 1
38
39
snakegroup = pygame.sprite.Group()
40
original_snake = snake()
41
snakegroup.add(original_snake)
42
43
class food(pygame.sprite.Sprite):
44
"""class to control food action"""
45
def __init__(self):
46
super().__init__() #access the Sprite super class methods
47
food1 = pygame.image.load("food1.png").convert_alpha()
48
x_pos = randint(50,600)
49
y_pos = randint(50,650)
50
self.image = food1
51
self.rect = self.image.get_rect(x = x_pos,y = y_pos)
52
53
foods = pygame.sprite.GroupSingle()
54
foods.add(food())
55
56
multiplier_x_pos = 1
57
while True:
58
"""EVENT LOOP CODE"""
59
for eachevent in pygame.event.get():
60
if eachevent.type == pygame.QUIT:
61
pygame.quit()
62
exit()
63
64
game_active = True
65
if pygame.sprite.spritecollideany(foods.sprite, snakegroup):
66
foods.empty()
67
foods.add(food())
68
foods.draw(disp_surface)
69
70
snakegroup.add(snake(original_snake.rect.x-(25*multiplier_x_pos),original_snake.rect.y))
71
multiplier_x_pos += 1
72
snakegroup.update(left, right, up, down)
73
74
75
keys = pygame.key.get_pressed()
76
events = pygame.event.get()
77
78
left = keys[pygame.K_LEFT]
79
right = keys[pygame.K_RIGHT]
80
up = keys[pygame.K_UP]
81
down = keys[pygame.K_DOWN]
82
83
snakegroup.update(left,right,up,down)
84
85
"""PYGAME EVENT CODE"""
86
if game_active:
87
disp_surface = display_surface()
88
89
snakegroup.draw(disp_surface)
90
foods.draw(disp_surface)
91
92
else:
93
disp_surface.fill((64,64,64))
94
95
pygame.display.update() #update all the surfaces on each frame
96
clock.tick(120) #fps
97
98
Advertisement
Answer
See the answer referenced in your question How do I chain the movement of a snake’s body?.
You need to use the 2nd solution and adjust the function that creates the snake body. The new function needs to update the positions of the Snakes body Sprites:
JavaScript
1
21
21
1
def update_body(track, distance):
2
body = snakegroup.sprites()
3
no_parts = len(body)
4
body[0].update(*track[0])
5
track_i = 1
6
next_i = 1
7
for i in range(1, no_parts):
8
while track_i < len(track):
9
pos = track[track_i]
10
track_i += 1
11
dx, dy = body[i-1].x_pos-pos[0], body[i-1].y_pos-pos[1]
12
if math.sqrt(dx*dx + dy*dy) >= distance:
13
body[i].update(*pos)
14
next_i = i+1
15
break
16
while next_i < no_parts:
17
body[next_i].update(*track[-1])
18
next_i += 1
19
del track[track_i:]
20
return body
21
Example based on your (revised) code:
JavaScript
1
103
103
1
import pygame
2
import math
3
from random import randint
4
from sys import exit
5
6
pygame.init()
7
clock = pygame.time.Clock()
8
disp_surface = pygame.display.set_mode(size = (610, 700))
9
10
class Snake(pygame.sprite.Sprite):
11
def __init__(self, x_pos = 300, y_pos = 300):
12
#Access the super class of Sprite
13
super().__init__()
14
#self.image = pygame.image.load("square1.png").convert_alpha()
15
self.image = pygame.Surface((20, 20), pygame.SRCALPHA)
16
pygame.draw.circle(self.image, (0, 255, 0), (10, 10), 10)
17
self.x_pos = x_pos
18
self.y_pos = y_pos
19
self.rect = self.image.get_rect(x = x_pos, y = y_pos)
20
def update(self, x_pos, y_pos):
21
self.x_pos = x_pos
22
self.y_pos = y_pos
23
self.rect = self.image.get_rect(center = (x_pos, y_pos))
24
25
class Food(pygame.sprite.Sprite):
26
"""class to control food action"""
27
def __init__(self):
28
super().__init__() #access the Sprite super class methods
29
#self.image = pygame.image.load("food1.png").convert_alpha()
30
self.image = pygame.Surface((20, 20), pygame.SRCALPHA)
31
pygame.draw.circle(self.image, (255, 0, 0), (10, 10), 10)
32
x_pos = randint(50,600)
33
y_pos = randint(50,650)
34
self.rect = self.image.get_rect(x = x_pos,y = y_pos)
35
def update(self, pos):
36
x_pos = randint(50,600)
37
y_pos = randint(50,650)
38
self.rect = self.image.get_rect(x = x_pos,y = y_pos)
39
40
41
def update_body(track, distance):
42
body = snakegroup.sprites()
43
no_parts = len(body)
44
body[0].update(*track[0])
45
track_i = 1
46
next_i = 1
47
for i in range(1, no_parts):
48
while track_i < len(track):
49
pos = track[track_i]
50
track_i += 1
51
dx, dy = body[i-1].x_pos-pos[0], body[i-1].y_pos-pos[1]
52
if math.sqrt(dx*dx + dy*dy) >= distance:
53
body[i].update(*pos)
54
next_i = i+1
55
break
56
while next_i < no_parts:
57
body[next_i].update(*track[-1])
58
next_i += 1
59
del track[track_i:]
60
return body
61
62
snakegroup = pygame.sprite.Group()
63
original_snake = Snake()
64
snakegroup.add(original_snake)
65
track = [(original_snake.x_pos, original_snake.y_pos)]
66
67
foods = pygame.sprite.GroupSingle()
68
foods.add(Food())
69
70
direction = (0, 0)
71
speed = 1
72
run = True
73
while run:
74
for eachevent in pygame.event.get():
75
if eachevent.type == pygame.QUIT:
76
run = False
77
if eachevent.type == pygame.KEYDOWN:
78
if eachevent.key == pygame.K_LEFT and direction[0] != 1:
79
direction = (-1, 0)
80
if eachevent.key == pygame.K_RIGHT and direction[0] != -1:
81
direction = (1, 0)
82
if eachevent.key == pygame.K_UP and direction[1] != 1:
83
direction = (0, -1)
84
if eachevent.key == pygame.K_DOWN and direction[1] != -1:
85
direction = (0, 1)
86
87
track.insert(0, track[0][:])
88
track[0] = (track[0][0] + direction[0] * speed) % disp_surface.get_width(), (track[0][1] + direction[1] * speed) % disp_surface.get_height()
89
update_body(track, 20)
90
91
if pygame.sprite.spritecollideany(foods.sprite, snakegroup):
92
foods.empty()
93
foods.add(Food())
94
last_part = snakegroup.sprites()[-1]
95
snakegroup.add(Snake(last_part.x_pos, last_part.y_pos))
96
speed = min(10, speed + 1)
97
98
disp_surface.fill((64,64,64))
99
snakegroup.draw(disp_surface)
100
foods.draw(disp_surface)
101
pygame.display.update()
102
clock.tick(120)
103