In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to use Pygame to make your game character move, I believe many inexperienced people don't know what to do about it. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
We will use Pygame to add keyboard controls so that you can control the movement of your character.
There are many functions in Pygame that can be used to add (except keyboard) other controls, but if you are tapping Python code, then you must have a keyboard, which will be the control method we will use next. Once you understand keyboard control, you can explore other options for yourself.
In the second article in this series, you have created a button to quit the game, and the principles for mobile characters are the same. However, it's a little more complicated to make your character move.
Let's start with the simple part: set the controller button.
Set buttons for the player goblins who control you
Open your Python game script in IDLE, Ninja-IDE, or a text editor.
Because the game needs to "monitor" keyboard events all the time, the code you write needs to run continuously. Do you know where to put code that needs to run continuously during the game cycle?
If you answer "put it in the main loop", then you are right! Remember that unless the code is in a loop, (in most cases) it will only run once. If it is written in a class or function that has never been used, it may not run at all.
To have Python listen for incoming keys, add the following code to the main loop. The current code doesn't have any effect yet, so use print statements to signal success. This is a common debugging technique.
While main = = True: for event in pygame.event.get (): if event.type = = pygame.QUIT: pygame.quit () Sys.exit () main = False if event.type = = pygame.KEYDOWN: if event.key = = pygame.K_LEFT or event.key = = ord ('a'): print ('left') if event.key = = pygame.K_RIGHT or event.key = = ord (' d'): print ('right') if event. Key = = pygame.K_UP or event.key = = ord ('w'): print ('jump') if event.type = = pygame.KEYUP: if event.key = = pygame.K_LEFT or event.key = = ord (' a'): print ('left stop') if event.key = = pygame.K_RIGHT or event.key = = ord (' d'): Print ('right stop') if event.key = = ord (' q'): pygame.quit () sys.exit () main = False
Some people prefer to use the keyboard letters W, A, S and D to control the player's characters, while others prefer to use direction keys. So make sure you include two options.
Note: when you are programming, it is important to consider all users at the same time. If you write code just to run it yourself, chances are you'll be the only user of the program you write. More importantly, if you want to find a job that makes money by writing code, the code you write should make it work for everyone. Giving your users options, such as providing options to use arrow keys or WASD, is the hallmark of a good programmer.
Use Python to start your game and view the output of the console window when you press the "up and down" arrow keys or the A, D and W keys.
$python. / your-name_game.py left left stop right right stop jump
This verifies that Pygame can detect keystrokes correctly. Now is the time to complete the arduous task of getting the goblins to move.
Write player mobility function
In order for your leprechaun to move, you must create an attribute for your leprechaun to represent movement. When your leprechaun is not moving, this variable is set to 0.
If you are animating your leprechaun, or if you decide to animate it in the future, you must also track the frame to keep the walking cycle on track.
Create the following variables in the Player class. The first two lines serve as a context contrast (if you keep following, you already have these two lines in your code), so you only need to add three lines:
Def _ _ init__ (self): pygame.sprite.Sprite.__init__ (self) self.movex = 0 # move in X direction self.movey = 0 # move self.frame in Y direction = 0 # frame count
With these variables set, it's time to write code for goblin movement.
The player leprechaun does not need to respond to control all the time, and sometimes it is not moving. The code to control goblins is only a small part of all the things players goblins can do. In Python, when you want an object to do something independent of the rest of the code, you can put your new code into a function. The function of Python begins with the keyword def, which stands for defining the function.
Create the following function in your Player class to add a few pixels to the position of your goblin on the screen. Don't worry about adding a few pixels for now, which will be determined in subsequent code.
Def control (self,x,y):''control the player's movement' 'self.movex + = x self.movey + = y
In order to move goblins in Pygame, you need to tell Python to redraw goblins in the new location and where the new location is.
Because player goblins are not always on the move, updates only need to be a function in the Player class. After adding this function to the control function you created earlier.
To make it look like a leprechaun is walking (or flying, or whatever your leprechaun should do), you need to change its position on the screen when you press the appropriate key. To move it across the screen, you need to redefine its position (specified by the self.rect.x and self.rect.y properties) to its current position plus any movex or movey that has been applied. (the number of pixels moved will be set later. )
Def update (self):''update leprechaun location' 'self.rect.x = self.rect.x + self.movex
Do the same for the Y direction:
Self.rect.y = self.rect.y + self.movey
For animation, push the animation frame as the leprechaun moves, and use the corresponding animation frame as the player's image:
# move if self.movex to the left
< 0: self.frame += 1 if self.frame >3*ani: self.frame = 0 self.image = self.images [self.frame//ani] # move if self.movex > 0: self.frame + = 1 if self.frame > 3*ani: self.frame = 0 self.image = self.images [(self.frame//ani) + 4]
Tell the code how many pixels to add to your goblin position by setting a variable, and then use this variable when triggering your player's goblin function.
First, create this variable in your settings section. In the following code, the first two lines are contextual, so you only need to add the third line to your script:
Player_list = pygame.sprite.Group () player_list.add (player) steps = 10 # how many pixels to move
Now that you have the appropriate functions and variables, use your keys to trigger the function and pass the variable to your leprechaun.
To do this, replace the print statement in the main loop with the name of the player goblin (player), the function (.control), and the number of steps you want the player goblin to move along the X and Y axes in each loop.
If event.type = = pygame.KEYDOWN: if event.key = = pygame.K_LEFT or event.key = = ord ('a'): player.control (- steps,0) if event.key = = pygame.K_RIGHT or event.key = = ord ('d'): player.control (steps 0) if event.key = = pygame.K_UP or event.key = = ord ('w'): print ('jump') if event.type = = pygame.KEYUP: if event.key = = pygame.K_LEFT or event.key = = ord (' a'): player.control (steps 0) if event.key = = pygame.K_RIGHT or event.key = = ord ('d'): player.control (- steps,0) if event.key = = ord ('q'): pygame.quit () sys.exit () main = False
Remember, the steps variable represents how many pixels your goblin will move when a key is pressed. If you press the D or right arrow keys, your leprechaun's position increases by 10 pixels. So when you stop pressing this button, you must (step) minus 10 (- steps) to get your goblin's momentum back to zero.
Now try your game. Note: it doesn't work as you might expect.
Why can't your leprechaun move? Because the main loop hasn't called the update function yet.
Add the following code to your main loop to tell Python to update the location of your player's goblins. Add the line with comments:
Player.update () # Update player location player_list.draw (world) pygame.display.flip () clock.tick (fps)
Start your game again to see your player goblins move back and forth on the screen under your command. There is no vertical movement yet, because this part of the function is controlled by gravity, but this is a lesson in another article.
At the same time, if you have a joystick, you can try to read the documentation on the joystick module in Pygame to see if you can get your goblins moving in this way. Or, see if you can interact with your goblins through the mouse.
Most importantly, have fun!
All the code used in this tutorial
For ease of reference, here is all the code used in this series of articles so far.
#! / usr/bin/env python3# drawing World # add player and player Control # add player Mobile Control # 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 Player (pygame.sprite.Sprite):' def _ _ init__ (self): pygame.sprite.Sprite.__init__ (self) self.movex = 0 self.movey = 0 self.frame = 0 self.images = [] for i in range (1Magne5): img = pygame.image.load (os.path.join ('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 control (self,x Y):''control the player's movement' 'self.movex + = x self.movey + = y def update (self):' 'update the goblin 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 >3*ani: self.frame = 0 self.image = self.images [self.frame//ani] # move if self.movex > 0: self.frame + = 1 if self.frame > 3*ani: self.frame = 0 self.image = self.images [(self.frame//ani) + 4] '' set''worldx = 960worldy = 720 fps = 40 # frame refresh rate ani = 4 # Animation Loop clock = pygame.time.Clock () pygame.init () main = True BLUE = (25pint 25200) BLACK = (23pc 23q23) WHITE = (254254254) ALPHA = (0m255p0) world = pygame.display.set_mode ([worldx Worldy]) backdrop = pygame.image.load (os.path.join ('images') Convert () backdropbox = world.get_rect () player = Player () # generate player player.rect.x = 0player.rect.y = 0player_list = pygame.sprite.Group () player_list.add (player) steps = 10 # moving speed''main cycle' 'while main = = True: for event in pygame.event.get (): if event.type = = pygame.QUIT: pygame.quit () Sys.exit () main = False if event.type = = pygame.KEYDOWN: if event.key = = pygame.K_LEFT or event.key = = ord ('a'): player.control (- steps,0) if event.key = = pygame.K_RIGHT or event.key = = ord ('d'): player.control (steps) 0) if event.key = = pygame.K_UP or event.key = = ord ('w'): print ('jump') if event.type = = pygame.KEYUP: if event.key = = pygame.K_LEFT or event.key = = ord (' a'): player.control (steps 0) if event.key = = pygame.K_RIGHT or event.key = = ord ('d'): player.control (- steps,0) if event.key = = ord ('q'): pygame.quit () sys.exit () main = False # world.fill (BLACK) world.blit (backdrop Backdropbox) player.update () player_list.draw (world) # Update player position pygame.display.flip () clock.tick (fps) finish reading the above Have you mastered how to use Pygame to make your game characters move? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.