❏ 站外平台:

在你的 Python 游戏中模拟引力

作者: Seth Kenlon 译者: LCTT 

| 2020-01-13 22:39      

学习如何使用 Python 的 Pygame 模块编程电脑游戏,并开始操作引力。

真实的世界充满了运动和生活。物理学使得真实的生活如此忙碌和动态。物理学是物质在空间中运动的方式。既然一个电脑游戏世界没有物质,它也就没有物理学规律,使用游戏程序员不得不模拟物理学。

从大多数电脑游戏来说,这里基本上仅有两个方面的物理学是重要的:引力和碰撞。

当你添加一个敌人到你的游戏中时,你实现了一些碰撞检测,但是这篇文章要添加更多的东西,因为引力需要碰撞检测。想想为什么引力可能涉及碰撞。如果你不能想到任何原因,不要担心 —— 它会随着你开发示例代码工作而且显然。

在真实世界中的引力是有质量的物体来相互吸引的倾向性。物体(质量)越大,它施加越大的引力作用。在电脑游戏物理学中,你不必创建质量足够大的物体来证明引力的正确;你可以在电脑游戏世界本身中仅编程一个物体落向假设的最大的对象的倾向。

添加一个引力函数

记住你的玩家已经有了一个决定动作的属性。使用这个属性来将玩家精灵拉向屏幕底部。

在 Pygame 中,较高的数字更接近屏幕的底部边缘。

在真实的世界中,引力影响一切。然而,在平台游戏中,引力是有选择性的 —— 如果你添加引力到你的整个游戏世界,你的所有平台都将掉到地上。反之,你可以仅添加引力到你的玩家和敌人精灵中。

首先,在你的 Player 类中添加一个 gravity 函数:

  1.     def gravity(self):
  2.         self.movey += 3.2 # 玩家掉落的多快

这是一个简单的函数。首先,不管你的玩家是否想运动,你设置你的玩家垂直运动。也就是说,你已经编程你的玩家总是在下降。这基本上就是引力。

为使引力函数生效,你必须在你的主循环中调用它。这样,当每一个处理循环时,Python 都应用下落运动到你的玩家。

在这代码中,添加第一行到你的循环中:

  1.     player.gravity() # 检查引力
  2.     player.update()

启动你的游戏来看看会发生什么。要注意,因为它发生的很快:你是玩家从天空上下落,马上掉出了你的游戏屏幕。

你的引力模拟是工作的,但是,也许太好了。

作为一次试验,尝试更改你玩家下落的速度。

给引力添加一个地板

你的游戏没有办法发现你的角色掉落出世界的问题。在一些游戏中,如果一个玩家掉落出世界,该精灵被删除,并在某个新的位置重生。在另一些游戏中,玩家会丢失分数或一条生命。当一个玩家掉落出世界时,不管你想发生什么,你必须能够侦测出玩家何时消失在屏幕外。

在 Python 中,要检查一个条件,你可以使用一个 if 语句。

你必需查看你玩家是否正在掉落,以及你的玩家掉落的程度。如果你的玩家掉落到屏幕的底部,那么你可以做一些事情。简化一下,设置玩家精灵的位置为底部边缘上方 20 像素。

使你的 gravity 函数看起来像这样:

  1.     def gravity(self):
  2.         self.movey += 3.2 # 玩家掉落的多快
  3.        
  4.         if self.rect.y > worldy and self.movey >= 0:
  5.             self.movey = 0
  6.             self.rect.y = worldy-ty

然后,启动你的游戏。你的精灵仍然下落,但是它停在屏幕的底部。不过,你也许不能看到你在地面层之上的精灵。一个简单的解决方法是,在精灵碰撞游戏世界的底部后,通过添加另一个 -ty 到它的新 Y 位置,从而使你的精灵弹跳到更高处:

  1.     def gravity(self):
  2.         self.movey += 3.2 # 玩家掉落的多快
  3.        
  4.         if self.rect.y > worldy and self.movey >= 0:
  5.             self.movey = 0
  6.             self.rect.y = worldy-ty-ty

现在你的玩家在屏幕底部弹跳,恰好在你地面精灵上面。

你的玩家真正需要的是反抗引力的方法。引力问题是,你不能反抗它,除非你有一些东西来推开引力作用。因此,在接下来的文章中,你将添加地面和平台碰撞以及跳跃能力。在这期间,尝试应用引力到敌人精灵。

到目前为止,这里是全部的代码:

  1. #!/usr/bin/env python3
  2. # draw a world
  3. # add a player and player control
  4. # add player movement
  5. # add enemy and basic collision
  6. # add platform
  7. # add gravity
  8. # GNU All-Permissive License
  9. # Copying and distribution of this file, with or without modification,
  10. # are permitted in any medium without royalty provided the copyright
  11. # notice and this notice are preserved. This file is offered as-is,
  12. # without any warranty.
  13. import pygame
  14. import sys
  15. import os
  16. '''
  17. Objects
  18. '''
  19. class Platform(pygame.sprite.Sprite):
  20. # x location, y location, img width, img height, img file
  21. def __init__(self,xloc,yloc,imgw,imgh,img):
  22. pygame.sprite.Sprite.__init__(self)
  23. self.image = pygame.image.load(os.path.join('images',img)).convert()
  24. self.image.convert_alpha()
  25. self.rect = self.image.get_rect()
  26. self.rect.y = yloc
  27. self.rect.x = xloc
  28. class Player(pygame.sprite.Sprite):
  29. '''
  30. Spawn a player
  31. '''
  32. def __init__(self):
  33. pygame.sprite.Sprite.__init__(self)
  34. self.movex = 0
  35. self.movey = 0
  36. self.frame = 0
  37. self.health = 10
  38. self.score = 1
  39. self.images = []
  40. for i in range(1,9):
  41. img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
  42. img.convert_alpha()
  43. img.set_colorkey(ALPHA)
  44. self.images.append(img)
  45. self.image = self.images[0]
  46. self.rect = self.image.get_rect()
  47. def gravity(self):
  48. self.movey += 3.2 # how fast player falls
  49. if self.rect.y > worldy and self.movey >= 0:
  50. self.movey = 0
  51. self.rect.y = worldy-ty-ty
  52. def control(self,x,y):
  53. '''
  54. control player movement
  55. '''
  56. self.movex += x
  57. self.movey += y
  58. def update(self):
  59. '''
  60. Update sprite position
  61. '''
  62. self.rect.x = self.rect.x + self.movex
  63. self.rect.y = self.rect.y + self.movey
  64. # moving left
  65. if self.movex < 0:
  66. self.frame += 1
  67. if self.frame > ani*3:
  68. self.frame = 0
  69. self.image = self.images[self.frame//ani]
  70. # moving right
  71. if self.movex > 0:
  72. self.frame += 1
  73. if self.frame > ani*3:
  74. self.frame = 0
  75. self.image = self.images[(self.frame//ani)+4]
  76. # collisions
  77. enemy_hit_list = pygame.sprite.spritecollide(self, enemy_list, False)
  78. for enemy in enemy_hit_list:
  79. self.health -= 1
  80. print(self.health)
  81. ground_hit_list = pygame.sprite.spritecollide(self, ground_list, False)
  82. for g in ground_hit_list:
  83. self.health -= 1
  84. print(self.health)
  85. class Enemy(pygame.sprite.Sprite):
  86. '''
  87. Spawn an enemy
  88. '''
  89. def __init__(self,x,y,img):
  90. pygame.sprite.Sprite.__init__(self)
  91. self.image = pygame.image.load(os.path.join('images',img))
  92. #self.image.convert_alpha()
  93. #self.image.set_colorkey(ALPHA)
  94. self.rect = self.image.get_rect()
  95. self.rect.x = x
  96. self.rect.y = y
  97. self.counter = 0
  98. def move(self):
  99. '''
  100. enemy movement
  101. '''
  102. distance = 80
  103. speed = 8
  104. if self.counter >= 0 and self.counter <= distance:
  105. self.rect.x += speed
  106. elif self.counter >= distance and self.counter <= distance*2:
  107. self.rect.x -= speed
  108. else:
  109. self.counter = 0
  110. self.counter += 1
  111. class Level():
  112. def bad(lvl,eloc):
  113. if lvl == 1:
  114. enemy = Enemy(eloc[0],eloc[1],'yeti.png') # spawn enemy
  115. enemy_list = pygame.sprite.Group() # create enemy group
  116. enemy_list.add(enemy) # add enemy to group
  117. if lvl == 2:
  118. print("Level " + str(lvl) )
  119. return enemy_list
  120. def loot(lvl,lloc):
  121. print(lvl)
  122. def ground(lvl,gloc,tx,ty):
  123. ground_list = pygame.sprite.Group()
  124. i=0
  125. if lvl == 1:
  126. while i < len(gloc):
  127. ground = Platform(gloc[i],worldy-ty,tx,ty,'ground.png')
  128. ground_list.add(ground)
  129. i=i+1
  130. if lvl == 2:
  131. print("Level " + str(lvl) )
  132. return ground_list
  133. def platform(lvl,tx,ty):
  134. plat_list = pygame.sprite.Group()
  135. ploc = []
  136. i=0
  137. if lvl == 1:
  138. ploc.append((0,worldy-ty-128,3))
  139. ploc.append((300,worldy-ty-256,3))
  140. ploc.append((500,worldy-ty-128,4))
  141. while i < len(ploc):
  142. j=0
  143. while j <= ploc[i][2]:
  144. plat = Platform((ploc[i][0]+(j*tx)),ploc[i][1],tx,ty,'ground.png')
  145. plat_list.add(plat)
  146. j=j+1
  147. print('run' + str(i) + str(ploc[i]))
  148. i=i+1
  149. if lvl == 2:
  150. print("Level " + str(lvl) )
  151. return plat_list
  152. '''
  153. Setup
  154. '''
  155. worldx = 960
  156. worldy = 720
  157. fps = 40 # frame rate
  158. ani = 4 # animation cycles
  159. clock = pygame.time.Clock()
  160. pygame.init()
  161. main = True
  162. BLUE = (25,25,200)
  163. BLACK = (23,23,23 )
  164. WHITE = (254,254,254)
  165. ALPHA = (0,255,0)
  166. world = pygame.display.set_mode([worldx,worldy])
  167. backdrop = pygame.image.load(os.path.join('images','stage.png')).convert()
  168. backdropbox = world.get_rect()
  169. player = Player() # spawn player
  170. player.rect.x = 0
  171. player.rect.y = 0
  172. player_list = pygame.sprite.Group()
  173. player_list.add(player)
  174. steps = 10 # how fast to move
  175. eloc = []
  176. eloc = [200,20]
  177. gloc = []
  178. #gloc = [0,630,64,630,128,630,192,630,256,630,320,630,384,630]
  179. tx = 64 #tile size
  180. ty = 64 #tile size
  181. i=0
  182. while i <= (worldx/tx)+tx:
  183. gloc.append(i*tx)
  184. i=i+1
  185. enemy_list = Level.bad( 1, eloc )
  186. ground_list = Level.ground( 1,gloc,tx,ty )
  187. plat_list = Level.platform( 1,tx,ty )
  188. '''
  189. Main loop
  190. '''
  191. while main == True:
  192. for event in pygame.event.get():
  193. if event.type == pygame.QUIT:
  194. pygame.quit(); sys.exit()
  195. main = False
  196. if event.type == pygame.KEYDOWN:
  197. if event.key == pygame.K_LEFT or event.key == ord('a'):
  198. print("LEFT")
  199. player.control(-steps,0)
  200. if event.key == pygame.K_RIGHT or event.key == ord('d'):
  201. print("RIGHT")
  202. player.control(steps,0)
  203. if event.key == pygame.K_UP or event.key == ord('w'):
  204. print('jump')
  205. if event.type == pygame.KEYUP:
  206. if event.key == pygame.K_LEFT or event.key == ord('a'):
  207. player.control(steps,0)
  208. if event.key == pygame.K_RIGHT or event.key == ord('d'):
  209. player.control(-steps,0)
  210. if event.key == pygame.K_UP or event.key == ord('w'):
  211. print('jump')
  212. if event.key == ord('q'):
  213. pygame.quit()
  214. sys.exit()
  215. main = False
  216. world.blit(backdrop, backdropbox)
  217. player.gravity() # check gravity
  218. player.update()
  219. player_list.draw(world)
  220. enemy_list.draw(world)
  221. ground_list.draw(world)
  222. plat_list.draw(world)
  223. for e in enemy_list:
  224. e.move()
  225. pygame.display.flip()
  226. clock.tick(fps)

这是仍在进行中的关于使用 Pygame 模块来在 Python 3 在创建电脑游戏的第七部分。先前的文章是:


via: https://opensource.com/article/19/11/simulate-gravity-python

作者:Seth Kenlon 选题:lujun9972 译者:robsean 校对:wxy

本文由 LCTT 原创编译,Linux中国 荣誉推出



最新评论

从 2025.1.15 起,不再提供评论功能
LCTT 译者
🌟🌟🌟🌟🌟
共计翻译: 122.0 篇 | 共计贡献: 1773
贡献时间:2018-12-03 -> 2023-10-10
访问我的 LCTT 主页 | 在 GitHub 上关注我


返回顶部

分享到微信

打开微信,点击顶部的“╋”,
使用“扫一扫”将网页分享至微信。