Tutorial #3
Subscribe to Tech with Tim
Cube Class - Draw Method
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.
class cube(object): ... def draw(self, surface, eyes=False): dis = self.w // self.rows # Width/Height of each cube i = self.pos[0] # Current row j = self.pos[1] # Current Column pygame.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 it if eyes: # Draws the eyes centre = dis//2 radius = 3 circleMiddle = (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.
def redrawWindow(surface): global rows, width, s # NEW surface.fill((0,0,0)) s.draw(surface) # NEW drawGrid(width,rows, surface) pygame.display.update()
Moving Our Snake
Now that we've coded most of our classes we can do some more work in the game loop.
To allow our snake to move we must call s.move().
def main(): global width, rows, s width = 500 rows = 20 win = pygame.display.set_mode((width, width)) s = snake((255,0,0), (10,10)) flag = True clock = pygame.time.Clock() while flag: pygame.time.delay(50) clock.tick(10) s.move() # NEW redrawWindow(win)
Adding Cubes
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.
def randomSnack(rows, item): positions = item.body # Get all the posisitons of cubes in our snake while True: # Keep generating random positions until we get a valid one x = random.randrange(rows) y = random.randrange(rows) if len(list(filter(lambda z:z.pos == (x,y), positions))) > 0: # This wll check if the position we generated is occupied by the snake continue else: break return (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