Pygame Snake Velocity Too High When The Fps Above 15
Solution 1:
The return value of self.clock.tick()
is the time which has passed since the last call.
Use the return value to control the speed. Define the distance, of movement of the snake per second (e.g. self.velocity = 400
means 400 pixel per second). Get the time between to frames (delta_t
) and scale the movement of the snake by the elapsed time (delta_t / 1000
):
classGame:
def__init__(self):
# [...]# distance per second
self.velocity = 400# [...]defgame(self):
# [...]while self.running:
delta_t = self.clock.tick(30)
# [...]ifnot self.paused:
step = delta_t / 1000# / 1000 because unit of velocity is seconds
self.snake_x += self.snake_x_change * step
self.snake_y += self.snake_y_change * step
else:
self.game_over()
pygame.display.flip()
With this setup it is ease to control the speed of the snake. For instance, the speed can be increased (e.g. self.velocity += 50
), when the snake grows.
Of course you have to round the position of the snake (self.snake_x
, self.snake_y
) to a multiple of the grid size (multiple of 25) when you draw the snake and when you do the collision test. Use round
to do so:
x, y = round(self.snake_x / 25) * 25, round(self.snake_y / 25) * 25
Ensure that the positions which are stored in snake_list
are a multiple of 25. Just append a new head to the list, if the head of the snake has reached a new field:
iflen(self.snake_list) <= 0or snake_head != self.snake_list[-1]:
self.snake_list.append(snake_head)
Apply that to the methods build_snake
draw
and check_apple_eaten
:
classGame:
# [...]defbuild_snake(self):
snake_head = list()
x, y = round(self.snake_x / 25) * 25, round(self.snake_y / 25) * 25
snake_head.append(x)
snake_head.append(y)
iflen(self.snake_list) <= 0or snake_head != self.snake_list[-1]:
self.snake_list.append(snake_head)
iflen(self.snake_list) > self.snake_length:
del self.snake_list[0]
for snake in self.snake_list[:-1]:
if snake == snake_head:
self.snake_reset()
self.draw("snake")
defcheck_apple_eaten(self):
x, y = round(self.snake_x / 25) * 25, round(self.snake_y / 25) * 25if x == self.apple_x and y == self.apple_y:
self.set_position("apple")
self.snake_length += 1
self.score += 1defsnake_borders_check(self):
x, y = round(self.snake_x / 25) * 25, round(self.snake_y / 25) * 25if x < 0or x > self.SCREEN_WIDTH - 25:
self.snake_reset()
if y < 0or y > self.SCREEN_HEIGHT - 25:
self.snake_reset()
Post a Comment for "Pygame Snake Velocity Too High When The Fps Above 15"