Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add an enemy to your Python game

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to add an enemy to your Python game, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!

Create enemy goblins

Yes, whether you realize it or not, you already know how to achieve the enemy. This process is very similar to creating a player leprechaun:

Create a class for enemy generation

Create a update method to enable the enemy to detect collisions

Create a move method that allows enemies to wander around

Start with the class. Conceptually, it is roughly the same as your Player class. You set up a picture or group of pictures, and then set the initial position of the leprechaun.

Before moving on to the next step, make sure you have an image of your enemy, even if it's just a temporary one. Put the images in the images directory of your game project (the same directory where you put your player images).

If all the living creatures had animation, the game would look much better. Animating enemy goblins is the same way as animating player goblins. But now, to keep it simple, we use a leprechaun without animation.

At the top of the objects section of your code, create a class called Enemy with the following code:

Class Enemy (pygame.sprite.Sprite):''generate an enemy' 'def _ _ init__ (self,x,y,img): pygame.sprite.Sprite.__init__ (self) self.image = pygame.image.load (os.path.join (' images') Img)) self.image.convert_alpha () self.image.set_colorkey (ALPHA) self.rect = self.image.get_rect () self.rect.x = x self.rect.y = y

If you want to get your enemies moving, use the same way you animate your players.

Generate an enemy.

You can generate more than one enemy by telling the class which image the goblin should use and where it should appear in the world. This means that you can use the same enemy humans to generate any number of enemy goblins anywhere in the game world. All you have to do is call the class and tell it which image to use and the X and Y coordinates of the point you expect to generate.

Again, this is similar in principle to generating a player elf. Add the following code to the setup section of your script:

Enemy = Enemy (20png') # generate enemy enemy_list = pygame.sprite.Group () # create enemy group enemy_list.add (enemy) # add the enemy to the enemy group

In the sample code, the X coordinate is 20 and the Y coordinate is 200. You may need to adjust these numbers according to the size of your enemy goblins, but try to generate them within a range so that your player goblins can touch it. Yeti.png is an image used for enemies.

Next, draw all the enemies of the enemy group on the screen. Now, you have only one enemy, and if you want more, you can add it later. Once you add an enemy to an enemy group, it will be drawn on the screen in the main loop. The middle line is the new line you need to add:

Player_list.draw (world) enemy_list.draw (world) # Refresh enemy pygame.display.flip ()

Start your game and your enemies will appear at the X and Y coordinates of your choice in the game world.

Pass one

Your game is still in its infancy, but you may want to add another level to it. It's important to plan for the future of your program, because as you learn more programming skills, your program will grow. Even if you still don't have a complete level, you should program on the assumption that there will be many levels.

Think about what the "level" is. How do you know you are at a specific level in the game?

You can think of a level as a collection of items. Just like the platform you just created, a level contains a specific arrangement of platforms, enemy placement, trophies, and so on. You can create a class that can be used to create levels near your players. Finally, when you create more than one level, you can use this class to generate the next level when your player reaches a specific goal.

Move the code you wrote to generate enemies and their groups to a new function that will be called each time a new level is generated. You need to make some changes so that every time you create a new level, you can create some enemies.

Class Level (): def bad (lvl,eloc): if lvl = = 1: enemy = Enemy (eloc [0], eloc [1] 'yeti.png') # generate enemy enemy_list = pygame.sprite.Group () # generate enemy group enemy_list.add (enemy) # add enemy to enemy group if lvl = = 2: print ("Level" + str (lvl)) return enemy_list

The return statement ensures that when you call the Level.bad method, you will get an enemy_list variable that contains all the enemies you define.

Because you are now creating enemies as part of each level, your setup part also needs to make some changes. Instead of creating an enemy, you have to define where the enemy is generated and which level the enemy belongs to.

Eloc = [] eloc = [2007.20] enemy_list = Level.bad (1, eloc)

Run the game again to make sure your level is generated correctly. As usual, you should see your players and the enemies you have added in this chapter.

Strike a blow at the enemy

An enemy is not an enemy if it has no effect on the player. When players collide with enemies, they usually cause damage to the player.

Because you may want to track the player's health, collision detection occurs in the Player class, not the Enemy class. Of course, you can also track the enemy's health if you want. The logic between them is roughly similar to the code, and now we only need to track the player's health.

In order to track the player's health, you must determine a variable for it. The * line in the code example is a context hint, so add the second line to your Player class:

Self.frame = 0 self.health = 10

In the update method of your Player class, add the following code block:

Hit_list = pygame.sprite.spritecollide (self, enemy_list, False) for enemy in hit_list: self.health-= 1 print (self.health)

This code uses Pygame's sprite.spritecollide method to set up a collision detector called enemy_hit. The collision detector sends a signal whenever the collision zone of its parent leprechaun (the player leprechaun that generates the detector) touches the collision zone of any leprechaun in the enemy_list. When this signal is received, the for loop is triggered and a bit of player health is deducted.

Once this code appears in the update method of your Player class and the update method is called in your main loop, Pygame will detect a collision in each clock tick.

Move the enemy

Still enemies can also be useful if you like, such as spikes and traps that can cause damage to your players. But if the enemy can wander around, then the game will be more challenging.

Unlike player goblins, enemy goblins are not controlled by players, so they must move automatically.

Eventually, your game world will roll. So, how do you make the enemies in the game world move back and forth when the game world scrolls?

For example, you tell your enemy leprechaun to move 10 steps to the right and 10 steps to the left. But enemy goblins don't count, so you need to create a variable to track how many steps your enemy has moved, and move your enemy left or right based on the value of the count variable.

First, create a count variable in your Enemy class. Add a single line of code from the following code example:

Self.rect = self.image.get_rect () self.rect.x = x self.rect.y = y self.counter = 0 # count variable

Then, create a move method in your Enemy class. Use an if-else loop to create a so-called dead loop:

If the count is between 0 and 100, move to the right

If the count is between 100 and 200, move to the left

If the count is greater than 200, the count is reset to 0.

The endless cycle has no end, because the loop judgment condition is always true, so it will cycle forever. In this case, the counter is always between 0 and 100 or 100 to 200, so the enemy will always move from left to right and then from right to left.

The exact distance you use the enemy to move in each direction depends on the size of your screen or, more specifically, on the size of the platform your enemy is moving. Start with a smaller value and gradually increase the value according to the habit. First, try the following:

Def move (self):''enemy move' 'distance = 80 speed = 8 if self.counter > = 0 and self.counter = distance and self.counter

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report