原文: https://pythonspot.com/snake-ai-in-pygame/

在本文中,我们将向您展示如何创建基本的游戏 AI(人工智能)。 本文将介绍游戏蛇的 AI。

在此游戏(蛇)中,计算机和您都在玩蛇,而计算机蛇会尝试抓住您。 简而言之:对手 AI 会根据您在棋盘上的位置尝试确定并前往目的地。

添加计算机玩家:

我们使用名为Computer的新类扩展了代码,它将成为我们的计算机玩家。 这包含绘制和移动计算机蛇的例程。

  1. class Computer:
  2. x = [0]
  3. y = [0]
  4. step = 44
  5. direction = 0
  6. length = 3
  7. updateCountMax = 2
  8. updateCount = 0
  9. def __init__(self, length):
  10. self.length = length
  11. for i in range(0,2000):
  12. self.x.append(-100)
  13. self.y.append(-100)
  14. # initial positions, no collision.
  15. self.x[0] = 1*44
  16. self.y[0] = 4*44
  17. def update(self):
  18. self.updateCount = self.updateCount + 1
  19. if self.updateCount > self.updateCountMax:
  20. # update previous positions
  21. for i in range(self.length-1,0,-1):
  22. self.x[i] = self.x[i-1]
  23. self.y[i] = self.y[i-1]
  24. # update position of head of snake
  25. if self.direction == 0:
  26. self.x[0] = self.x[0] + self.step
  27. if self.direction == 1:
  28. self.x[0] = self.x[0] - self.step
  29. if self.direction == 2:
  30. self.y[0] = self.y[0] - self.step
  31. if self.direction == 3:
  32. self.y[0] = self.y[0] + self.step
  33. self.updateCount = 0
  34. def moveRight(self):
  35. self.direction = 0
  36. def moveLeft(self):
  37. self.direction = 1
  38. def moveUp(self):
  39. self.direction = 2
  40. def moveDown(self):
  41. self.direction = 3
  42. def draw(self, surface, image):
  43. for i in range(0,self.length):
  44. surface.blit(image,(self.x[i],self.y[i]))

然后,我们调用计算机的更新和绘制方法。

  1. def on_loop(self):
  2. self.player.update()
  3. self.computer.update()
  4. ....
  5. def on_render(self):
  6. self._display_surf.fill((0,0,0))
  7. self.player.draw(self._display_surf, self._image_surf)
  8. self.apple.draw(self._display_surf, self._apple_surf)
  9. self.computer.draw(self._display_surf, self._image_surf)
  10. pygame.display.flip()

这将使计算机蛇移动并在屏幕上绘制。 它具有与人类玩家相同的属性。

为计算机玩家添加智能

因为这是一个简单的游戏,所以我们无需在游戏内部创建完整的思维机。 我们只需要计算机玩家展示一些基本情报即可。 游戏中的智能通常非常有限,因为在大多数情况下,不需要复杂性或根本没有时间实现聪明的算法。

我们将添加的算法将仅到达目的地。 它将忽略任何障碍(人类玩家)。

  1. def target(self,dx,dy):
  2. if self.x[0] > dx:
  3. self.moveLeft()
  4. if self.x[0] < dx:
  5. self.moveRight()
  6. if self.x[0] == dx:
  7. if self.y[0] < dy:
  8. self.moveDown()
  9. if self.y[0] > dy:
  10. self.moveUp()

完整代码

我们得到以下完整代码:

  1. from pygame.locals import *
  2. from random import randint
  3. import pygame
  4. import time
  5. class Apple:
  6. x = 0
  7. y = 0
  8. step = 44
  9. def __init__(self,x,y):
  10. self.x = x * self.step
  11. self.y = y * self.step
  12. def draw(self, surface, image):
  13. surface.blit(image,(self.x, self.y))
  14. class Player:
  15. x = [0]
  16. y = [0]
  17. step = 44
  18. direction = 0
  19. length = 3
  20. updateCountMax = 2
  21. updateCount = 0
  22. def __init__(self, length):
  23. self.length = length
  24. for i in range(0,2000):
  25. self.x.append(-100)
  26. self.y.append(-100)
  27. # initial positions, no collision.
  28. self.x[0] = 1*44
  29. self.x[0] = 2*44
  30. def update(self):
  31. self.updateCount = self.updateCount + 1
  32. if self.updateCount > self.updateCountMax:
  33. # update previous positions
  34. for i in range(self.length-1,0,-1):
  35. self.x[i] = self.x[i-1]
  36. self.y[i] = self.y[i-1]
  37. # update position of head of snake
  38. if self.direction == 0:
  39. self.x[0] = self.x[0] + self.step
  40. if self.direction == 1:
  41. self.x[0] = self.x[0] - self.step
  42. if self.direction == 2:
  43. self.y[0] = self.y[0] - self.step
  44. if self.direction == 3:
  45. self.y[0] = self.y[0] + self.step
  46. self.updateCount = 0
  47. def moveRight(self):
  48. self.direction = 0
  49. def moveLeft(self):
  50. self.direction = 1
  51. def moveUp(self):
  52. self.direction = 2
  53. def moveDown(self):
  54. self.direction = 3
  55. def draw(self, surface, image):
  56. for i in range(0,self.length):
  57. surface.blit(image,(self.x[i],self.y[i]))
  58. class Computer:
  59. x = [0]
  60. y = [0]
  61. step = 44
  62. direction = 0
  63. length = 3
  64. updateCountMax = 2
  65. updateCount = 0
  66. def __init__(self, length):
  67. self.length = length
  68. for i in range(0,2000):
  69. self.x.append(-100)
  70. self.y.append(-100)
  71. # initial positions, no collision.
  72. self.x[0] = 1*44
  73. self.y[0] = 4*44
  74. def update(self):
  75. self.updateCount = self.updateCount + 1
  76. if self.updateCount > self.updateCountMax:
  77. # update previous positions
  78. for i in range(self.length-1,0,-1):
  79. self.x[i] = self.x[i-1]
  80. self.y[i] = self.y[i-1]
  81. # update position of head of snake
  82. if self.direction == 0:
  83. self.x[0] = self.x[0] + self.step
  84. if self.direction == 1:
  85. self.x[0] = self.x[0] - self.step
  86. if self.direction == 2:
  87. self.y[0] = self.y[0] - self.step
  88. if self.direction == 3:
  89. self.y[0] = self.y[0] + self.step
  90. self.updateCount = 0
  91. def moveRight(self):
  92. self.direction = 0
  93. def moveLeft(self):
  94. self.direction = 1
  95. def moveUp(self):
  96. self.direction = 2
  97. def moveDown(self):
  98. self.direction = 3
  99. def target(self,dx,dy):
  100. if self.x[0] > dx:
  101. self.moveLeft()
  102. if self.x[0] < dx:
  103. self.moveRight()
  104. if self.x[0] == dx:
  105. if self.y[0] < dy:
  106. self.moveDown()
  107. if self.y[0] > dy:
  108. self.moveUp()
  109. def draw(self, surface, image):
  110. for i in range(0,self.length):
  111. surface.blit(image,(self.x[i],self.y[i]))
  112. class Game:
  113. def isCollision(self,x1,y1,x2,y2,bsize):
  114. if x1 >= x2 and x1 <= x2 + bsize:
  115. if y1 >= y2 and y1 <= y2 + bsize:
  116. return True
  117. return False
  118. class App:
  119. windowWidth = 800
  120. windowHeight = 600
  121. player = 0
  122. apple = 0
  123. def __init__(self):
  124. self._running = True
  125. self._display_surf = None
  126. self._image_surf = None
  127. self._apple_surf = None
  128. self.game = Game()
  129. self.player = Player(5)
  130. self.apple = Apple(8,5)
  131. self.computer = Computer(5)
  132. def on_init(self):
  133. pygame.init()
  134. self._display_surf = pygame.display.set_mode((self.windowWidth,self.windowHeight), pygame.HWSURFACE)
  135. pygame.display.set_caption('Pygame pythonspot.com example')
  136. self._running = True
  137. self._image_surf = pygame.image.load("pygame.png").convert()
  138. self._apple_surf = pygame.image.load("apple.png").convert()
  139. def on_event(self, event):
  140. if event.type == QUIT:
  141. self._running = False
  142. def on_loop(self):
  143. self.computer.target(self.apple.x, self.apple.y)
  144. self.player.update()
  145. self.computer.update()
  146. # does snake eat apple?
  147. for i in range(0,self.player.length):
  148. if self.game.isCollision(self.apple.x,self.apple.y,self.player.x[i], self.player.y[i],44):
  149. self.apple.x = randint(2,9) * 44
  150. self.apple.y = randint(2,9) * 44
  151. self.player.length = self.player.length + 1
  152. # does computer eat apple?
  153. for i in range(0,self.player.length):
  154. if self.game.isCollision(self.apple.x,self.apple.y,self.computer.x[i], self.computer.y[i],44):
  155. self.apple.x = randint(2,9) * 44
  156. self.apple.y = randint(2,9) * 44
  157. #self.computer.length = self.computer.length + 1
  158. # does snake collide with itself?
  159. for i in range(2,self.player.length):
  160. if self.game.isCollision(self.player.x[0],self.player.y[0],self.player.x[i], self.player.y[i],40):
  161. print "You lose! Collision: "
  162. print "x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")"
  163. print "x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")"
  164. exit(0)
  165. pass
  166. def on_render(self):
  167. self._display_surf.fill((0,0,0))
  168. self.player.draw(self._display_surf, self._image_surf)
  169. self.apple.draw(self._display_surf, self._apple_surf)
  170. self.computer.draw(self._display_surf, self._image_surf)
  171. pygame.display.flip()
  172. def on_cleanup(self):
  173. pygame.quit()
  174. def on_execute(self):
  175. if self.on_init() == False:
  176. self._running = False
  177. while( self._running ):
  178. pygame.event.pump()
  179. keys = pygame.key.get_pressed()
  180. if (keys[K_RIGHT]):
  181. self.player.moveRight()
  182. if (keys[K_LEFT]):
  183. self.player.moveLeft()
  184. if (keys[K_UP]):
  185. self.player.moveUp()
  186. if (keys[K_DOWN]):
  187. self.player.moveDown()
  188. if (keys[K_ESCAPE]):
  189. self._running = False
  190. self.on_loop()
  191. self.on_render()
  192. time.sleep (50.0 / 1000.0);
  193. self.on_cleanup()
  194. if __name__ == "__main__" :
  195. theApp = App()
  196. theApp.on_execute()

Pygame 中的贪食蛇 AI - 图1

python 贪食蛇

结论

您学习了如何使用非常简单的 AI 算法创建基本的计算机玩家。

下一步:学习基本的侧滑器逻辑