In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use Python to add jump function to the game". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how to use Python to add jumping function to the game"!
Set the jump state variable
You need to add two new variables to your Player class:
One is to track whether your character is jumping, which can be determined by whether your player genie is standing on solid ground.
One is to bring the player back to the ground.
Add the following two variables to your Player class. In the following code, the part before the comment is used to prompt the context, so only the last two lines need to be added:
Self.movex = 0 self.movey = 0 self.frame = 0 self.health = 10 # here is the gravity related variable self.collide_delta = 0 self.jump_delta = 6
The first variable, collide_delta, is set to 0 because the player wizard is not in a jumping state under normal conditions. Another variable, jump_delta, is set to 6 to prevent elves from bouncing (actually jumping) the first time they enter the game world. When you have completed the example in this article, try setting the variable to 0 and see what happens.
A collision in a jump
If you are jumping on a trampoline, your jump must be very beautiful. But what happens if you jump to a wall? Never try! No matter how impressive your take-off is, when you hit something bigger and harder than you, you will stop immediately. (LCTT translation note: principle refers to the law of conservation of momentum)
To simulate this in your video game, you need to set the self.collide_delta variable to 0 when your player's wizard collides with something like the ground. If your self.collide_delta is not zero but something else, then your player will jump and will not be able to jump when your player collides with a wall or ground.
In the update method of your Player class, modify the block of code related to the ground collision as follows:
Ground_hit_list = pygame.sprite.spritecollide (self, ground_list, False) for g in ground_hit_list: self.movey = 0 self.rect.y = worldy-ty-ty self.collide_delta = 0 # stop jumping if self.rect.y > g.rect.y: self.health-= 1 print (self.health)
This code block checks the collision between the ground elf and the player wizard. When a collision occurs, it sets the coordinates of the player's Y direction to the height of the game window minus the height of one tile and then the height of another tile. This ensures that the player genie is standing on the ground, not embedded in the ground. It also sets self.collide_delta to 0 so that the program knows that the player is not jumping. In addition, it sets self.movey to 0 so that the program can know that the player is not currently being pulled by gravity (which is the strange thing about the game physics engine, and once the player lands, there is no need to continue to pull the player to the ground).
Here the if statement is used to detect whether the player has fallen below the ground, and if so, deduct a little health as a penalty. This assumes that you want to lose health when your player falls off the map. This setting is not required, it is just a convention for platform games. More likely, you want this event to trigger other events, or something that makes your real-world players addicted to letting elves fall off the screen. A simple way to recover is to reset self.rect.y to 0 when the player wizard falls off the map, so that it will regenerate above the map and land on solid ground.
Hit the ground
The simulated gravity makes your player's Y coordinate increase continuously. (LCTT note: it is 0 here, but the lower Y coordinate should be larger in Pygame). To jump, complete the following code to get your player elves off the ground and into the air.
In the update method of your Player class, add the following code to temporarily delay the effect of gravity:
If self.collide_delta
< 6 and self.jump_delta < 6: self.jump_delta = 6*2 self.movey -= 33 # 跳跃的高度 self.collide_delta += 6 self.jump_delta += 6 根据此代码所示,跳跃使玩家精灵向空中移动了 33 个像素。此处是负 33 是因为在 Pygame 中,越小的数代表距离屏幕顶端越近。 不过此事件视条件而定,只有当 self.collide_delta 小于 6(缺省值定义在你 Player 类的 init 方法中)并且 self.jump_delta 也于 6 的时候才会发生。此条件能够保证直到玩家碰到一个平台,才能触发另一次跳跃。换言之,它能够阻止空中二段跳。 在某些特殊条件下,你可能不想阻止空中二段跳,或者说你允许玩家进行空中二段跳。举个栗子,如果玩家获得了某个战利品,那么在他被敌人攻击到之前,都能够拥有空中二段跳的能力。 当你完成本篇文章中的示例,尝试将 self.collide_delta 和 self.jump_delta 设置为 0,从而获得百分之百的几率触发空中二段跳。 在平台上着陆 目前你已经定义了在玩家精灵摔落地面时的抵抗重力条件,但此时你的游戏代码仍保持平台与地面置于不同的列表中(就像本文中做的很多其他选择一样,这个设定并不是必需的,你可以尝试将地面作为另一种平台)。为了允许玩家精灵站在平台之上,你必须像检测地面碰撞一样,检测玩家精灵与平台精灵之间的碰撞。将如下代码放于你的 update 方法中: plat_hit_list = pygame.sprite.spritecollide(self, plat_list, False) for p in plat_hit_list: self.collide_delta = 0 # 跳跃结束 self.movey = 0 但此处还有一点需要考虑:平台悬在空中,也就意味着玩家可以通过从上面或者从下面接触平台来与之互动。 确定平台如何与玩家互动取决于你,阻止玩家从下方到达平台也并不稀奇。将如下代码加到上方的代码块中,使得平台表现得像天花板或者说是藤架。只有在玩家精灵跳得比平台上沿更高时才能跳到平台上,但会阻止玩家从平台下方跳上来: if self.rect.y >P.rect.y: self.rect.y = p.rect.y+ty else: self.rect.y = p.rect.y-ty
Here the first clause of the if statement code block prevents the player wizard from jumping directly under the platform onto the platform. If it detects that the player wizard's coordinates are larger than the platform (in Pygame, larger coordinates mean lower on the screen), set the player wizard's new Y coordinates to the Y coordinates of the current platform plus the height of a tile. The actual effect is to ensure that the player spirit is at the height of a tile from the platform to prevent it from passing through the platform from below.
The else clause does the opposite. When the program runs here, if the Y coordinate of the player wizard is no larger than that of the platform, it means that the player wizard is falling from the air (whether it is because the player has just been generated from here, or the player has performed a jump). In this case, the Y coordinate of the player wizard is set to the Y coordinate of the platform minus the height of a tile (remember, in Pygame, the smaller Y coordinate represents higher on the screen). This ensures that the player is on the platform unless he jumps or steps down from the platform.
You can also try other ways to deal with the interaction between players and the platform. Take Chestnut, maybe the player wizard is set to be in the "front" of the platform, and he can jump across the platform and stand on it without obstacles. Or you can design a platform that slows down but doesn't completely stop the player from jumping. You can even mix and match different platforms into different lists.
Trigger a jump
So far, your code has simulated all the necessary jump conditions, but still lacks a jump trigger. The self.jump_delta initial value of your player wizard is set to 6, and the update jump code will be triggered only if it is smaller than 6.
Set a new setting method for the jump variable, create a jump method in your Player class, and set self.jump_delta to a value less than 6. Temporarily slow down the effect of gravity by causing the player's wizard to move 33 pixels into the air.
Def jump (self,platform_list): self.jump_delta = 0
Believe it or not, that's what the jump approach is all about. The rest is in the update method, which you implemented earlier.
There is one last thing to do for the jump in your game to take effect. If you can't remember what it is, run the game and see how the jump works.
The problem is that you don't call the jump method in your main loop. You have previously created a keystroke placeholder for this method, and now all the jump keys do is print the jump to the terminal.
Call the jump method
In your main loop, change the effect of the up arrow from printing a debug statement to calling the jump method.
Note here that like the update method, the jump method also needs to detect collisions, so you need to tell it which plat_list to use.
If event.key = = pygame.K_UP or event.key = = ord ('w'): player.jump (plat_list)
If you prefer to use the spacebar as the jump key, use pygame.K_SPACE instead of pygame.K_UP as the key. Alternatively, you can use both methods (using separate if statements) to give players one more choice.
Now try your game! In the next article, you will make your game roll up.
Pygame platform games
Here is all the code so far:
#! / usr/bin/env python3# draw a world# add a player and player control# add player movement# add enemy and basic collision# add platform# add gravity# add jumping # GNU All-Permissive License# Copying and distribution of this file, with or without modification,# are permitted in any medium without royalty provided the copyright# notice and this notice are preserved. This file is offered as-is,# without any warranty. Import pygameimport sysimport os''Objects''' class Platform (pygame.sprite.Sprite): # x coordinates, y coordinates, image width, image height Image file def _ _ init__ (self,xloc,yloc,imgw,imgh,img): pygame.sprite.Sprite.__init__ (self) self.image = pygame.image.load (os.path.join ('images') Img) .convert () self.image.convert_alpha () self.rect = self.image.get_rect () self.rect.y = yloc self.rect.x = xloc class Player (pygame.sprite.Sprite):''generate a player' 'def _ _ init__ (self): pygame.sprite.Sprite.__init__ (self) Self.movex = 0 self.movey = 0 self.frame = 0 self.health = 10 self.collide_delta = 0 self.jump_delta = 6 self.score = 1 self.images = [] for i in range (1pm 9): img = pygame.image.load ('images' 'hero' + str (I) +' .png') convert () img.convert_alpha () img.set_colorkey (ALPHA) self.images.append (img) self.image = self.images [0] self.rect = self.image.get_rect () def jump (self Platform_list): self.jump_delta = 0 def gravity (self): self.movey + = 3.2 # how fast player falls if self.rect.y > worldy and self.movey > = 0: self.movey = 0 self.rect.y = worldy-ty def control (self,x Y):''control the player's movement' 'self.movex + = x self.movey + = y def update (self):' 'update the sprite position' self.rect.x = self.rect.x + self.movex self.rect.y = self.rect.y + self.movey # move if self.movex to the left
< 0: self.frame += 1 if self.frame >Ani*3: self.frame = 0 self.image = self.images [self.frame//ani] # move if self.movex > 0: self.frame + = 1 if self.frame > ani*3: self.frame = 0 self.image = self.images [(self.frame//ani) + 4] # collision enemy_hit_list = pygame.sprite.spritecollide (self Enemy_list, False) for enemy in enemy_hit_list: self.health-= 1 # print (self.health) plat_hit_list = pygame.sprite.spritecollide (self, plat_list) False) for pin plat_hit_list: self.collide_delta = 0 # stop jumping self.movey = 0 if self.rect.y > p.rect.y: self.rect.y = p.rect.y+ty else: self.rect.y = p.rect.y-ty ground_hit_list = pygame.sprite.spritecollide (self Ground_list, False) for g in ground_hit_list: self.movey = 0 self.rect.y = worldy-ty-ty self.collide_delta = 0 # stop jumping if self.rect.y > g.rect.y: self.health-= 1 print (self.health) if self.collide_delta
< 6 and self.jump_delta < 6: self.jump_delta = 6*2 self.movey -= 33 # how high to jump self.collide_delta += 6 self.jump_delta += 6 class Enemy(pygame.sprite.Sprite): ''' 生成一个敌人 ''' def __init__(self,x,y,img): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(os.path.join('images',img)) self.movey = 0 #self.image.convert_alpha() #self.image.set_colorkey(ALPHA) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.counter = 0 def move(self): ''' 敌人移动 ''' distance = 80 speed = 8 self.movey += 3.2 if self.counter >= 0 and self.counter = distance and self.counter = worldy-ty-ty: self.rect.y + = self.movey plat_hit_list = pygame.sprite.spritecollide (self, plat_list False) for p in plat_hit_list: self.movey = 0 if self.rect.y > p.rect.y: self.rect.y = p.rect.y+ty else: self.rect.y = p.rect.y-ty ground_hit_list = pygame.sprite.spritecollide (self, ground_list False) for g in ground_hit_list: self.rect.y = worldy-ty-ty class Level (): def bad (lvl,eloc): if lvl = = 1: enemy = Enemy (eloc [0], eloc [1] 'yeti.png') # generate enemy enemy_list = pygame.sprite.Group () # create enemy group enemy_list.add (enemy) # add enemy to enemy group if lvl = = 2: print ("Level" + str (lvl)) return enemy_list def loot (lvl Lloc): print (lvl) def ground (lvl,gloc,tx,ty): ground_list = pygame.sprite.Group () iTun0 if lvl = = 1: while I < len (gloc): ground = Platform (gloci [I], worldy-ty,tx,ty 'ground.png') ground_list.add (ground) i=i+1 if lvl = 2: print ("Level" + str (lvl)) return ground_list def platform (lvl,tx,ty): plat_list = pygame.sprite.Group () ploc = [] ifol0 if lvl = = 1: ploc.append ((0) Worldy-ty-128,3)) ploc.append ((300) ploc.append ((500) len (ploc): juni0 while j
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.