Python and Pygame universal module constructs a game frame (3)

Use Pygame move your game character

Pygame There are some functions you can add other types of controls, but if you enter Python code must have a keyboard that is what we will use.

You create a key to exit the game in the second article in this series, the principle and the same movement. But let your character moves more complicated.

Let's start from the simple part: set the controller key.

Sprite control the player setting key for

Open the game Python script in IDLE, Ninja-IDE or text editor.

As the game must continue to "listen" keyboard events, so you will need to write code to run continuously. Can you think of code during the game often you need to run where to put it?

If you answered "In the main loop," then you are right! Remember, unless the code in the loop, otherwise it will run only once - if it is hidden in a class or function will never be used, and it might not run.

To monitor the incoming key Python, add this code to the main loop. No code can make anything happen, so use printthe statement to indicate success. This is a common debugging techniques.


而主要== 真:
    对于事件的 pygame的。事件。get ():
        if event。type == pygame。退出:
            pygame。退出(); SYS。exit ()
            main = 如果是事件则为False。type == pygame。KEYDOWN:if event。key == pygame。K_LEFT 或事件。

            key == ord ('a' ):
                print ('left' )
            if event。key == pygame。K_RIGHT 或事件。key == ord ('d' ):
                print ('right' )
            if event。key == pygame。K_UP 或事件。key == ord ('w' ):
            print ('jump' )

        if event。type ==pygame的。KEYUP:
            if event。key == pygame。K_LEFT 或事件。key == ord ('a' ):
                print ('left stop' )
            if event。key == pygame。K_RIGHT 或事件。key == ord ('d' ):
                print ('right stop' )
            if event。key == ord ('q' ):
                pygame的。quit ()
                sys。exit ()
                main = False    

Some people prefer to use the keyboard characters W, A, S and D to control the player character, while others prefer to use the arrow keys. Be sure to include these two options.

** Note: ** Considering all users is critical during programming. If you write code only applies to you, then you probably only use the code in your application. More importantly, if you are looking for a money writing code to work, you should write the code for everyone. To provide users with choices such as arrow keys or WASD option to use, it is a sign of good programmers.

Use Python start the game, and pressing the right, looking at the output console window leftward and upward arrow or A, D and W keys.


$ python ./your-name_game。PY
  左
  左边停止
  右
  右停止
  跳跃

This confirms Pygame correctly detected button. Now is the time to do the hard work of the spirit moving.

The player moves coding function

To move the wizard, you must create a property is a moving spirit. When your spirit is not moving, this variable is set 0.

If you want to animate your sprite, or if you decide in the future to animate, you must also make walking track frame to maintain normal circulation.

Create a variable in the Player class. The first two lines for context (if you have been to follow, you have used them in code), so just add the last three lines:


    def __init__ (self ):
        pygame。精灵。雪碧。__init__ (自我)
        自我。movex = 0 #沿X 
        self 移动。movey = 0 #沿着Y 
        self 移动。frame = 0 #counts frames

After setting these variables, you can encode the spirit of sport.

Players need not always respond to the wizard control; sometimes it does not move. Therefore, the control wizard code is just a small part of all the things done by the player sprite. When you want to create an object in Python, independently of the rest of the code, the new code in a function. Python function starts with the keyword def, on behalf of the DEFINE .

Create a function in your Player class, add sprite position on the screen some of the pixel count . Do not worry about how many pixels you add; this will be decided at a later code.

    def控制(自我, x , y ):
        ''' 
        控制球员运动
        ''' 
        自我。movex + = x 
        self。movey + = y

To move the sprite in Pygame, you must tell the Python redrawn sprites in its new position - and the position of the new location.

Since Player elves are not always on the move, so the update function if the Player simply a class. In controladding this function after the function that you created earlier.

To make the sprite look like a walking (or flying or whatever your sprite should do), you need to change its position on the screen when you press the appropriate key. To make it move across the screen, you can set its position (by the attribute self.rect.xand self.rect.ythe specified property) redefined as the current position plus any number movexor moveylocation applications. (Set the number of pixels required to move later.)


    def update (self ):
        ''' 
        更新精灵位置
        ''' 
        self。RECT。x = 自我。RECT。x + 自我。的Movex        

Do the same thing for the Y position:


        自我。RECT。y = 自我。RECT。y + 自我。movey

For animation, every time the sprite animation frame moves forward, and use the corresponding animation frame image as players:

        #向左移动
        ,如果 自我。movex < 0:
            自我。帧 + = 1 
            如果 自己。frame > 3 * ani:
                self。frame = 0 
            self。image = self。图像[ 自我。帧 // ANI ] 

        #向右移动
        ,如果 自我。movex > 0:
            自我。帧 + = 1 
            如果 自我。frame > 3 * ani:
                self。frame = 0 
            self。image = self。图像[ (自我。帧 // ANI ) + 4 ]

By setting a tag tell the code to add to the number of pixels of the sprite location, and then use that variable when triggered Player wizard function.

First, create a variable in the Settings section. In this code, the first two lines for the context, and therefore simply add the third line to the script:


player_list = pygame。精灵。Group ()
player_list。add ( player )
steps = 10  #要移动的像素数

Now that you have the appropriate functions and variables, use your keys to trigger functions and variables sent to your elves.

By printusing the name of the player sprite (player), a function (.control) replace the primary loop statements, and desired number of players with each sprite step along the X-axis and Y-axis movement cycles to perform this operation.

        如果事件。type == pygame。KEYDOWN:
            if event。key == pygame。K_LEFT 或事件。key == ord ('a' ):
                玩家。控制( -steps ,0 )
            if event。key == pygame。K_RIGHT 或事件。key == ord ('d' ):
                玩家。控制(步骤,0 )
            如果事件。key == pygame。K_UP 或事件。key == ord ('w' ):
                print ('jump' )

        if event。type == pygame。KEYUP:
            if event。key == pygame。K_LEFT 或事件。key == ord ('a' ):
                玩家。控制(步骤,0 )
            如果事件。key == pygame。K_RIGHT 或事件。key == ord ('d' ):
                玩家。控制( -steps ,0 )
            if event。key == ord ('q' ):
                pygame。quit ()
                sys。exit ()
                main = False

Keep in mind, stepsit is a variable that represents the number of pixels sprite move when the key is pressed. If you add 10 pixels to the position of the player sprite when you press the right arrow or D, stop when you press this button, you must subtract 10 ( -steps) to restore momentum wizard to zero.

Try it now your game. Warning: It does not perform as expected.

Why not move your elves? Because the primary loop does not call the updatefunction.

Add code to the main loop to tell the location Python update the player sprite. Add comment line:


    播放器。update ()  #
    upcate player position player_list。画(世界)
    pygame。显示。翻转()
    时钟。tick ( fps )

Start the game again to see if your player sprite to move the screen in your bids. No vertical movement, because these functions will be controlled by gravity, but that's another lesson for another article.

In the meantime, if you have access to a joystick, try reading the Pygame joystick module documentation, see if you can get your sprites move. Or, see if you can make the mouse to interact with your spirit.

Most importantly, have fun!

All codes used in this tutorial

For your reference, this is all the code so far this series of articles used.


#!/ usr / bin / env python3 
#画一个世界
#添加玩家和玩家控制
#add player movement 

#GNU All-Permissive License 
#复制和分发此文件,无论有没有修改,
#都允许在任何媒体中使用#版税提供版权
#通知,此通知保留。此文件按原样提供,
#没有任何保证。

进口 pygame的
进口 SYS 
进口 OS 

“”“ 
对象
‘’” 

类的播放器(。pygame的精灵。精灵):
    ‘’“ 
    生成一个播放器
    ‘’”
    def __init__ (self ):
        pygame。精灵。雪碧。__init__ (自我)
        自我。movex = 0 
        self。movey = 0 
        self。frame = 0 
        self。图像 = [ ] 
        为我在 范围(1 ,5 ):
            IMG = pygame的。图像。负载(操作系统。路径。加入('images' ,'hero' + str ( i ) + '。png' ))。convert ()
            img。convert_alpha ()
            img。set_colorkey ( ALPHA )
            self。图像。追加( img )
            自我。image = self。图像[ 0 ] 
            自我。矩形  = 自我。图像。get_rect ()

    def控制(self , x , y ):
        ''' 
        控制玩家运动
        ''' 
        自我。movex + = x 
        self。movey + = y 

    def update (self ):
        ''' 
        更新精灵位置
        ''' 

        self。RECT。x = 自我。RECT。x + 自我。movex 
        self。RECT。y = 自我。RECT。y + 自我。movey 

        #向左移动
        ,如果 自我。movex < 0:
            自我。帧 + = 1 
            如果 自己。frame > 3 * ani:
                self。frame = 0 
            self。image = self。图像[ 自我。帧 // ANI ] 

        #向右移动
        ,如果 自我。movex > 0:
            自我。帧 + = 1 
            如果 自己。frame > 3 * ani:
                self。frame = 0 
            self。image = self。图像[ (自我。帧 // ANI ) + 4 ] 

'' ' 
设置
'''
worldx = 960
worldy = 720

fps = 40        #frame rate
ani = 4        #animation cycles
clock = pygame。时间。时钟()
pygame。初始化()
主要= 真

BLUE   = (25 ,25 ,200 )
BLACK = (23 ,23 ,23 )
WHITE = (254 ,254 ,254 )
ALPHA = (0 ,255 ,0 )

世界= pygame的。显示。set_mode ([ worldx , worldy ] )
backdrop = pygame。图像。负载(OS。路径。加入('图像' ,'stage.png' ))。convert ()
backdropbox = world。get_rect()
player = Player ()   #profen player
player。RECT。x = 0
玩家。RECT。y = 0
player_list = pygame。精灵。Group ()
player_list。添加(播放器)
步骤= 10      #如何快速移动

“”“ 
主回路
‘’” 
而主要== 真:
    对于事件的 pygame的。事件。get ():
        if event。type == pygame。退出:
            pygame。退出(); SYS。exit ()
            main = 如果是事件则为False。type == pygame。KEYDOWN:if event。key == pygame。K_LEFT 或事件。key == ord ('a' ):                 玩家。

控制( -steps ,0 )
            if event。key == pygame。K_RIGHT 或事件。key == ord ('d' ):
                玩家。控制(步骤,0 )
            如果事件。key == pygame。K_UP 或事件。key == ord ('w' ):
                print ('jump' )

        if event。type ==pygame的。KEYUP:
            if event。key == pygame。K_LEFT 或事件。key == ord ('a' ):
                玩家。控制(步骤,0 )
            如果事件。key == pygame。K_RIGHT 或事件。key == ord ('d' ):
                玩家。控制( -steps ,0 )
            if event。键 == ord ('q' ):
                pygame。quit ()
                sys。exit ()
                main = False 

#world.fill(黑色)
    世界。blit (背景, backgroundbox )
    播放器。update ()
    player_list。draw ( world ) #refresh player position
    pygame。显示。翻转()
    时钟。打勾( fps)

You have to go very far, learned a lot, but there are a lot of work to do. In the next few articles, you add the enemy of elves, simulated gravity, and so on. At the same time, in Python practice!

We will certainly encounter many difficulties when learning python, as well as the pursuit of new technologies, here's what we recommend learning Python buckle qun: 784758214, here is the python learner gathering place! ! At the same time, he was a senior development engineer python, python script from basic to web development, reptiles, django, data mining and other projects to combat zero-based data are finishing. Given to every little python partner! Daily share some methods of learning and the need to pay attention to small details

Click: Python exchange technology sharing

Guess you like

Origin blog.csdn.net/zhizhun88/article/details/90707108