self.direction = "right": Refers to the initial direction of [Greedy Snake] when it was born
self.body = [[100, 100], [80, 100]]: Initial small grid coordinates (with the upper left corner as the origin)
self.head = list(self.body[0])# The position of the snake head, the coordinates of the snake head
Function [ draw_me], use * pygame.draw.rect(sc, green, (b[0], b[1], 20, 20))*, this has been mentioned in the third lesson: click me to review the third lesson
Function [ move_head], movement function, the left and right movement is related to the X axis, so the * in the code takes the head head[0], and the up and down movement is related to the Y axis, so thehead[1] * in the code takes the head
Function [ add_body]: increase the small square of the body, this is the function called after eating food
Function [ cut_tail]: This is the small square to delete the tail
Function [ move_snake], this function calls [ add_body, cut_tail], one is added to the head, one is subtracted from the tail, one is added to the head, one is subtracted from the tail, one is added to the head, one is subtracted from the tail..., this is moving
3. Next, we create a [snake] class
# 食物类的设计classFood():def__init__(self):
self.color=white
#知识进阶-双倍奖励#self.color=random.choice([white,pink])
x = random.randrange(0,640,20)
y = random.randrange(0,480,20)
self.postion =[x,y]defdraw_me(self):
pygame.draw.rect(sc, self.color,(self.postion[0], self.postion[1],20,20))defreset(self):
x = random.randrange(0,640,20)
y = random.randrange(0,480,20)
self.postion =[x,y]#知识进阶-双倍奖励#self.color=random.choice([white,pink])
code comment
self.color=white, the initial color of the food is white
x = random.randrange(0, 640,20), y = random.randrange(0, 480,20), this means that the food cannot exceed the size of the game interface, the X axis is 0 to 640 with a step size of 20, and the Y axis is 0 to 480 with a step size of 20,都是随机的
Knowledge advancement - double rewards self.color=random.choice([white,pink]), colors can be randomly selected