跳至正文
View Categories

< 1 min read

贪吃蛇6 #

  1. 碰撞检测
  2. 食物“吞食”设置
  3. 窗口更新

碰撞检测 #

本小节主要介绍了贪吃蛇类与食物类的碰撞检测方法

class SnakeGame():
    @staticmethod
    def isCollision(x1, y1, x2, y2, bsize):
    if x1 >= x2 and x1 <= x2 + bsize:
        if y1 >= y2 and y1 <= y2 + bsize:
            return True
    return False

食物“吞食”设置 #

本小节主要介绍贪吃蛇类与食物类碰撞后,下一个食物随机出现,贪吃蛇长度+1的方法。在class SnakeGame()类中添加eat()函数

    def eat(self):
        if self.isCollision(self.food.x, self.food.y, self.snake.x[0], self.snake.y[0], 40):
            self.food.x = random.randint(2, 9)*STEP #食物随机出现
            self.food.y = random.randint(2, 9)*STEP
            self.snake.length += 1      # 蛇的长度加1

窗口更新 #

本小节主要介绍了碰撞、吞食的窗口更新。在class SnakeGame()类中增加“eat”更新,并通过run()函数中调用self.loop()进行窗口更新

    #def loop(self):
        #self.snake.update()
        self.eat()#增加eat更新

小结 #

本节主要介绍了贪吃蛇游戏中贪吃蛇与食物的碰撞检测与“吞食”及相应窗口更新