import random from pygame.locals import * import pygame import time from test.游戏.Food import Food, Snake, STEP class SnakeGame(): def __init__(self): self.width = 800 self.height = 600 self._running = False def init(self): pygame.init() #初始化所有导入的pygame模块 # 初始化一个准备显示的窗口或屏幕 self._display_surf = pygame.display.set_mode((self.width,self.height), pygame.HWSURFACE) self.food = Food(5, 5, self._display_surf) self.snake = Snake(1, 1, self._display_surf) self._running = True def run(self): self.init() while self._running: pygame.event.pump() # 内部处理pygame事件处理程序 self.listen_keybord() # 监听键盘上下左右键 self.loop() self.render() time.sleep(0.05) def listen_keybord(self): keys = pygame.key.get_pressed() if (keys[K_RIGHT]): self.snake.moveRight() if (keys[K_LEFT]): self.snake.moveLeft() if (keys[K_UP]): self.snake.moveUp() if (keys[K_DOWN]): self.snake.moveDown() if (keys[K_ESCAPE]): self._running = False def render(self): self._display_surf.fill((0, 0, 0)) # 游戏界面填充为黑色 self.food.draw() # 画出食物 self.snake.draw() # 画出蛇 pygame.display.flip() # 刷新屏幕 def loop(self): self.snake.update() self.eat() self.faild_check() def faild_check(self): # 检查是否吃到了自己 for i in range(2,self.snake.length): if self.isCollision(self.snake.x[0], self.snake.y[0], self.snake.x[i], self.snake.y[i],40): print('吃到自己了') exit(0) if self.snake.x[0] < 0 or self.snake.x[0] > self.width \ or self.snake.y[0] < 0 or self.snake.y[0] > self.height: print('出边界了') exit(0) 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 @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 if __name__ == '__main__': snake = SnakeGame() snake.run()