I'm recreating snake in Python, I've set the base up but i'm at a road block for how to refresh/update the screen

Viewed 36
from tkinter import *
root =  Tk()
root.geometry('400x400')
root.title('Snake')
#root['background'] = ''
canvas = Canvas(root,width = 400,height = 400,bg = '#FF0000')
canvas.pack()

Heading ###class used to setup snake with methods.

class Snake:
    def __init__(self):
        self.width = 10
        self.height = 10
        self.snake_length = [1]
    def draw_cell(self,pos_x,pos_y):
        # pos_x, pos_y will be divided by 20 so we times by 20
        canvas.create_rectangle(pos_x*20,pos_y*20,pos_x*20+20,pos_y*20+20)
    def draw_snake(self):
        for i in range(0,len(self.snake_length)):
            self.draw_cell(10,10)
    def movement(self):
        




def grid():
    for i in range(0,20):
        for j in range(0,20):
            canvas.create_rectangle(i*20,j*20,i*20+20,j*20+20,fill = '#ff6347'

##starting up everything also checking things

grid()
a = Snake()
a.draw_snake()
root.mainloop()

Im not very good at python, so any extra help with silly mistakes would be helpful :)

1 Answers

The function/method you are looking for would redraw the grid and then draw your snake. Since you already created the functions/methods to do this, the actual implementation of this should be easy as that:

def update():
    grid()
    a.draw_snake()

If you want to control the refresh rate (which I would recommend since otherwise, your frame will update as often as your update function can be called) you can use the after() method from the tkinter module. You place it just before your mainloop call. In this example, the variable fps would represent the desired frames per second.

root.after(1000/fps, update)

If you are further interested in the after method(), you will find a pretty good explanation here.

Related