Now we will draw our cubes inside of the draw() method. This involves a bit of math as we have 20 positions in our grid and a screen with dimensions of 500x500. We need to determine where to draw each cube so that it appears within the proper space on the grid.
classcube(object):...defdraw(self,surface,eyes=False):dis=self.w//self.rows# Width/Height of each cubei=self.pos# Current rowj=self.pos# Current Columnpygame.draw.rect(surface,self.color,(i*dis+1,j*dis+1,dis-2,dis-2))# By multiplying the row and column value of our cube by the width and height of each cube we can determine where to draw itifeyes:# Draws the eyescentre=dis//2radius=3circleMiddle=(i*dis+centre-radius,j*dis+8)circleMiddle2=(i*dis+dis-radius*2,j*dis+8)pygame.draw.circle(surface,(0,0,0),circleMiddle,radius)pygame.draw.circle(surface,(0,0,0),circleMiddle2,radius)
Now to actually see anything on the screen we must add something to the redrawWindow function.
Now that we can move our snake around the screen we need something for it to eat or collect. Every time we collide with one of these objects we will add a new cube to the end of our snake. We are going to call this item a snack.
The first step is to generate a position for our "snack". We will do this inside the randomSnack() function.
defrandomSnack(rows,item):positions=item.body# Get all the posisitons of cubes in our snakewhileTrue:# Keep generating random positions until we get a valid onex=random.randrange(rows)y=random.randrange(rows)iflen(list(filter(lambdaz:z.pos==(x,y),positions)))>0:# This wll check if the position we generated is occupied by the snakecontinueelse:breakreturn(x,y)
Now that we have a function for creating a random snack we should use it! Add the following line into the main() function before the while loop.
snack=cube(randomSnack(rows,s), color=(0,255,0))# This goes in the main function