How to use Python to create a steerable role players

In this first article in this series, I explained how to use Python to create a simple text-based dice game. In the second part, I show you how to build a game from scratch, that is, start by creating a game environment. But every game needs a player, and each player needs a steerable role, which is we are going to be in this part of the third series of the need to do.

In Pygame, the player controls the icon or avatar is called fairy sprite. If you do not have any image can be used for players fairy, or you can use Krita Inkscape to create some of your own image. If you lack confidence in their artistic, you can also search for some ready-made images OpenClipArt.org or OpenGameArt.org. If you have not follow the article said separate images to create a folder, then you need to create it in your Python project directory. You will want to use in the game pictures are put images folder.

In order to make your game real thrill, you should be a dynamic picture of fairies as your hero. This means that you need to draw more material, and they are to be different. The most common is to walk animation cycle through a series of images to make your fairy look like walking. Walking cycling fastest rough version requires four images.

How to how to use Python to create a steerable role players to use Python to create a steerable role players

Note: The sample code in this article is compatible with both static and dynamic players fairy.

Your players goblin named hero.png. If you are creating a dynamic monster, you need to add a number after their name, from hero1.png start.

Create a Python class

In Python, when you create one you want to display objects on the screen, you need to create a class.

In your Python  script to a position near the top, add the following code to create a player. In the following code example, the first three lines already in Python you're dealing with  a script in which:

import pygame
import sys
import os # 以下是新代码

class Player(pygame.sprite.Sprite):
    '''
    生成一个玩家
    '''
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.images = []
    img = pygame.image.load(os.path.join('images','hero.png')).convert()
    self.images.append(img)
    self.image = self.images[0]
    self.rect  = self.image.get_rect()

If you can control role has a walk cycle, corresponding to the images in the folder to save the image as a separate file hero1.png to hero4.png.

Use a loop to tell Python through each file.

'''
对象
'''

class Player(pygame.sprite.Sprite):
    '''
    生成一个玩家
    '''
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.images = []
        for i in range(1,5):
            img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
            self.images.append(img)
            self.image = self.images[0]
            self.rect  = self.image.get_rect()

The players into the game world

Has now created a Player class, you need to use it to generate a goblin player in your game world. If you do not call the Player class, then it will never work, (game world) there would be no players. You can run your game to immediately verify. An article on the game will see the end of the run like that, and get a clear result: an empty game world.

To a goblin player game brought to your world, you must call the Player class to generate a monster, and add it to the Pygame fairy group. In the sample code below, the first three lines of code that already exist, you need to add code thereafter:

world       = pygame.display.set_mode([worldx,worldy])
backdrop    = pygame.image.load(os.path.join('images','stage.png')).convert()
backdropbox = screen.get_rect()

# 以下是新代码

player = Player()   # 生成玩家
player.rect.x = 0   # 移动 x 坐标
player.rect.y = 0   # 移动 y 坐标
player_list = pygame.sprite.Group()
player_list.add(player)

Try to start your game to see what happens. High-energy warning: it does not work as you expect, when you start your project, the player does not appear goblins. In fact it generates, but there was only a millisecond. How do you fix a appears only for a millisecond things? You may recall the previous article, you need to add something to the main loop. In order to make the player's presence for more than a millisecond, you need to tell Python in each cycle are drawn once.

The bottom of your statement cycle changes as follows:

    world.blit(backdrop, backdropbox)
    player_list.draw(screen) # 绘制玩家
    pygame.display.flip()
    clock.tick(fps)

Now start your game, your players appeared!

Alpha channel settings

Depending on how you create your player goblins around it might be a color. What you see is a space to be occupied by the alpha channel. It could have been invisible "color", but do not know Python to make it invisible. So you see, it is a space in the area around the border around the goblin (or the modern game in terms of a "hit area hit box").

How to how to use Python to create a steerable role players to use Python to create a steerable role players

You can tell what color the Python invisible by setting an alpha channel and RGB values. If you do not know the image of the RGB value of the alpha channel, or Krita Inkscape you can open it, and using a unique color, such as # 00ff00 (almost "green green screen") to fill the empty space around the image . Note the hexadecimal value corresponding to the color (here # 00ff00, green, green screen) and used as an alpha channel for your Python scripts.

Alpha channel correlation need to generate code that you add the following two lines in the monster. Similar to the first line of code already exists in your script, you only need to add two more lines:

            img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
            img.convert_alpha()     # 优化 alpha
            img.set_colorkey(ALPHA) # 设置 alpha

Unless you tell it otherwise, Python does not know what color as the alpha channel. In the provision of the relevant area of ​​your code, to add some color definition. The following variable definitions added to any location on your settings related areas:

ALPHA = (0, 255, 0)

In the sample code above, we 0,255,0 be used, it is the same as the representative RGB values ​​in the # 00ff00 value represented in hexadecimal. You can be an excellent image applications such as GIMP, Krita or Inkscape, to get all these color values. Alternatively, you can use a good system-level color selector, such as KColorChooser, to detect color.

How to how to use Python to create a steerable role players to use Python to create a steerable role players

If your image application to your fairy background rendered into other values, you can adjust the value of ALPHA-demand variable. No matter how much you set the alpha, and finally it will be "invisible." RGB color values ​​are very strict, so if you need the alpha to 000, but you want your image to 000 for the black line, you only need to set the color of the image center line 111. Thus, (black line image) sufficiently close to black, but in addition the computer no one can see the difference.

Run your game to see the results.

In the fourth article in this series, I will show you how to make your fairy move. How exciting ah!


via: https://opensource.com/article/17/12/game-python-add-a-player

Author: Seth Kenlon  topics: lujun9972  Translator: cycoe  proofread: wxy

This article from the  LCTT  original compiler, Linux China  is proud

Original from: https://linux.cn/article-10858-1.html

Guess you like

Origin blog.csdn.net/Linuxprobe18/article/details/90401230