04-02 Move Snake to Class

01

Move the contents of snake in a Snake class

block = pygame.image.load('images/block.jpg').convert()
block_x = 100
block_y = 100

put the drawBlock() function into a method, draw() inside of Snake

def drawBlock():
    surface.fill((255,255,255))
    surface.blit(block,(block_x,block_y))
    pygame.display.flip()
                

**The code will not run yet AND the Snake needs to be passed in the surface

remember to change block, block_x and y with self.block, self.x and self.y

class Snake:
    def __init__(self):
        self.block = pygame.image.load('images/block.jpg').convert()
        self.x = 100
        self.y = 100

    def draw(self):
        self.surface.fill((255,255,255))
        self.surface.blit(self.block,(self.x,self.y))
        pygame.display.flip()

02

Pass in the surface as an argument into the Snake class and call it parent_surface

**The code will still not run, We Need to add a snake class in the Game class, where we can pass the surface into

class Snake:
    def __init__(self,parent_surface):
        self.parent_surface = parent_surface
        self.block = pygame.image.load('images/block.jpg').convert()
        self.x = 100
        self.y = 100

    def drawBlock(self):
        self.parent_surface.fill((255,255,255))
        self.parent_surface.blit(self.block,(self.x,self.y))
        pygame.display.flip()

03

Create an instance of the Snake class in the Game class. This is also where we pass in the surface into the Snake class

class Game:
    def __init__(self):
        pygame.init()
        self.surface = pygame.display.set_mode((500,400))
        self.surface.fill((255,255,255))
        self.snake = Snake(self.surface)
        self.snake.draw()
    def run(self):
        pass

**The code will still not run, Below are the Snake and Game classes so far, go to the next lesson to finish

class Snake:
    def __init__(self,parent_surface):
        self.parent_surface = parent_surface
        self.block = pygame.image.load('images/block.jpg').convert()
        self.block_x = 100
        self.block_y = 100

    def drawBlock(self):
        self.surface.fill((255,255,255))
        self.surface.blit(block,(block_x,block_y))
        pygame.display.flip()

class Game:
    def __init__(self):
        pygame.init()
        self.surface = pygame.display.set_mode((500,400))
        self.surface.fill((255,255,255))
        self.snake = Snake(self.surface)
    def run(self):

        pass