import pygame

STEP = 44


class Food():
    def __init__(self, x, y, surface):
        self.x = x * STEP
        self.y = y * STEP
        self.surface = surface
        self.image = pygame.image.load("food.png").convert()

    def draw(self):
        self.surface.blit(self.image, (self.x, self.y))

class Snake():
    def __init__(self, x, y, surface):
        self.x = [x*STEP]
        self.y = [y*STEP]      # 用两个列表来存储贪吃蛇每个节点的位置
        self.length = 1        # 贪吃蛇的长度
        self.direction = 0     # 0表示向右, 1表示向下, 2表示向左, 3表示向上
        self.image = pygame.image.load("snake.png").convert()       # 加载蛇
        self.surface = surface
        self.step = 44         # 运动步长
        self.updateCount = 0     # 更新次数

        # 虽然有这么多节点,但是有length来控制界面上画出多少蛇的节点
        for i in range(1, 100):
            self.x.append(-100)
            self.y.append(-100)

    def draw(self):
        for i in range(self.length):
            self.surface.blit(self.image, (self.x[i],self.y[i]))

    def moveRight(self):
        self.direction = 0

    def moveLeft(self):
        self.direction = 2

    def moveUp(self):
        self.direction = 3

    def moveDown(self):
        self.direction = 1

    def update(self):
        self.updateCount += 1
        if self.updateCount > 2:
            for i in range(self.length-1, 0, -1):
                self.x[i] = self.x[i-1]
                self.y[i] = self.y[i-1]
            if self.direction == 0:
                self.x[0] = self.x[0] + self.step    # 向右
            if self.direction == 1:
                self.y[0] = self.y[0] + self.step    # 向下
            if self.direction == 2:
                self.x[0] = self.x[0] - self.step    # 向左
            if self.direction == 3:
                self.y[0] = self.y[0] - self.step    # 向上
            self.updateCount = 0
