#example snake snake = [[1, 2], [1, 3], [2, 3]]
def draw():
canvas.delete('all')
for segment in snake:
y = segment[0] * 10
x = segment[1] * 10
canvas.create_rectangle(x, y, x + 10, y + 10, fill="red")
canvas.update()
I have created a simple snake game in python using tkinter but the movement slows down rapidly when the snake array contains 30+ rectangles, so i was wondering is there a better way to do the drawing of the objects so it works faster instead of constantly calling this draw function?
Another possible issue is the inefficiency of the move functions:
def move_right(event):
global left, right, up, down
if right != True:
left, right, up, down = False, True, False, False
while right == True:
if snake[0][1] >= snake[1][1]:
for x in range(len(snake) - 1, 0, -1):
snake[x] = snake[x - 1]
snake[0] = [snake[0][0], snake[0][1] + 1]
draw()
time.sleep(0.05)
This my first actual game so don't kill me :(.
You don't have to delete all rectangles from canvas. You have to remove only last rectangle and add new head rectangle.
To add new x,y in snake list you don't have to move all elements - you need only
snake.insert(0, [new_x, new_y])
You can use
root.after
instead ofwhile
loop andsleep
Example - without checking collisions