Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

před 1 rokem
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import pygame
  2. STEP = 44
  3. class Food():
  4. def __init__(self, x, y, surface):
  5. self.x = x * STEP
  6. self.y = y * STEP
  7. self.surface = surface
  8. self.image = pygame.image.load("food.png").convert()
  9. def draw(self):
  10. self.surface.blit(self.image, (self.x, self.y))
  11. class Snake():
  12. def __init__(self, x, y, surface):
  13. self.x = [x*STEP]
  14. self.y = [y*STEP] # 用两个列表来存储贪吃蛇每个节点的位置
  15. self.length = 1 # 贪吃蛇的长度
  16. self.direction = 0 # 0表示向右, 1表示向下, 2表示向左, 3表示向上
  17. self.image = pygame.image.load("snake.png").convert() # 加载蛇
  18. self.surface = surface
  19. self.step = 44 # 运动步长
  20. self.updateCount = 0 # 更新次数
  21. # 虽然有这么多节点,但是有length来控制界面上画出多少蛇的节点
  22. for i in range(1, 100):
  23. self.x.append(-100)
  24. self.y.append(-100)
  25. def draw(self):
  26. for i in range(self.length):
  27. self.surface.blit(self.image, (self.x[i],self.y[i]))
  28. def moveRight(self):
  29. self.direction = 0
  30. def moveLeft(self):
  31. self.direction = 2
  32. def moveUp(self):
  33. self.direction = 3
  34. def moveDown(self):
  35. self.direction = 1
  36. def update(self):
  37. self.updateCount += 1
  38. if self.updateCount > 2:
  39. for i in range(self.length-1, 0, -1):
  40. self.x[i] = self.x[i-1]
  41. self.y[i] = self.y[i-1]
  42. if self.direction == 0:
  43. self.x[0] = self.x[0] + self.step # 向右
  44. if self.direction == 1:
  45. self.y[0] = self.y[0] + self.step # 向下
  46. if self.direction == 2:
  47. self.x[0] = self.x[0] - self.step # 向左
  48. if self.direction == 3:
  49. self.y[0] = self.y[0] - self.step # 向上
  50. self.updateCount = 0