You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.6KB

  1. import random
  2. from pygame.locals import *
  3. import pygame
  4. import time
  5. from test.游戏.Food import Food, Snake, STEP
  6. class SnakeGame():
  7. def __init__(self):
  8. self.width = 800
  9. self.height = 600
  10. self._running = False
  11. def init(self):
  12. pygame.init() #初始化所有导入的pygame模块
  13. # 初始化一个准备显示的窗口或屏幕
  14. self._display_surf = pygame.display.set_mode((self.width,self.height), pygame.HWSURFACE)
  15. self.food = Food(5, 5, self._display_surf)
  16. self.snake = Snake(1, 1, self._display_surf)
  17. self._running = True
  18. def run(self):
  19. self.init()
  20. while self._running:
  21. pygame.event.pump() # 内部处理pygame事件处理程序
  22. self.listen_keybord() # 监听键盘上下左右键
  23. self.loop()
  24. self.render()
  25. time.sleep(0.05)
  26. def listen_keybord(self):
  27. keys = pygame.key.get_pressed()
  28. if (keys[K_RIGHT]):
  29. self.snake.moveRight()
  30. if (keys[K_LEFT]):
  31. self.snake.moveLeft()
  32. if (keys[K_UP]):
  33. self.snake.moveUp()
  34. if (keys[K_DOWN]):
  35. self.snake.moveDown()
  36. if (keys[K_ESCAPE]):
  37. self._running = False
  38. def render(self):
  39. self._display_surf.fill((0, 0, 0)) # 游戏界面填充为黑色
  40. self.food.draw() # 画出食物
  41. self.snake.draw() # 画出蛇
  42. pygame.display.flip() # 刷新屏幕
  43. def loop(self):
  44. self.snake.update()
  45. self.eat()
  46. self.faild_check()
  47. def faild_check(self):
  48. # 检查是否吃到了自己
  49. for i in range(2,self.snake.length):
  50. if self.isCollision(self.snake.x[0], self.snake.y[0], self.snake.x[i], self.snake.y[i],40):
  51. print('吃到自己了')
  52. exit(0)
  53. if self.snake.x[0] < 0 or self.snake.x[0] > self.width \
  54. or self.snake.y[0] < 0 or self.snake.y[0] > self.height:
  55. print('出边界了')
  56. exit(0)
  57. def eat(self):
  58. if self.isCollision(self.food.x, self.food.y, self.snake.x[0], self.snake.y[0], 40):
  59. self.food.x = random.randint(2, 9)*STEP
  60. self.food.y = random.randint(2, 9)*STEP
  61. self.snake.length += 1 # 蛇的长度加1
  62. @staticmethod
  63. def isCollision(x1, y1, x2, y2, bsize):
  64. if x1 >= x2 and x1 <= x2 + bsize:
  65. if y1 >= y2 and y1 <= y2 + bsize:
  66. return True
  67. return False
  68. if __name__ == '__main__':
  69. snake = SnakeGame()
  70. snake.run()