pygame user controllable object

So far, you can create a Pygame window and render a ball that will fly on the screen. The next step is to make some bats that users can control. This may be much simpler than a ball because it doesn't require physical elements (unless your user controls the movement of objects more complex than up and down, in which case you need more physical elements for platform characters such as Mario). User controllable objects are very easy to create, thanks to Pygame's event queuing system, as you can see.

A simple bat
The principle behind the racket is similar to that of the ball. You need one__ init__ Function to initialize the ball (so you can create an object instance for each bat), an update function to perform changes for each frame before the bat sends the bat to the screen, and a function that defines what the class will actually do. Here are some sample codes:

class Bat(pygame.sprite.Sprite):
    """A movable tennis "racket" used to hit the ball
 return:Bat object
 function:reinit, update, moveup, movedown
 attribute:speed"""

    def __init__(self, side):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_png('bat.png')
        screen = pygame.display.get_surface()
        self.area = screen.get_rect()
        self.side = side
        self.speed = 10
        self.state = "still"
        self.reinit()

    def reinit(self):
        self.state = "still"
        self.movepos = [0,0]
        if self.side == "left":
            self.rect.midleft = self.area.midleft
        elif self.side == "right":
            self.rect.midright = self.area.midright

    def update(self):
        newpos = self.rect.move(self.movepos)
        if self.area.contains(newpos):
            self.rect = newpos
        pygame.event.pump()

    def moveup(self):
        self.movepos[1] = self.movepos[1] - (self.speed)
        self.state = "moveup"

    def movedown(self):
        self.movepos[1] = self.movepos[1] + (self.speed)
        self.state = "movedown"

As you can see, this class is very similar to the ball class in structure.
But the function of each function is different.
First, there is a reinit function. When used at the end of a round, the racket needs to return to its starting position and set any attributes back to their necessary values.
Next, the way the bat moves is slightly more complicated than the ball, because its movement here is very simple (up / down), but it depends on the user to tell it to move, unlike the ball moving at every frame.
In order to understand how the ball moves, it is helpful to look at a quick chart to show the sequence of events

What happens here is that the person who controls the bat presses the key to make the bat move upward.
For each iteration of the main game loop (each frame), the key is whether it is still held down, and then the bat's state attribute object will be set to "move", and the moveup function will be called, causing the ball's y position to reduce the value of the speed attribute (in this case, 10).
In other words, just press this button and the bat will move up 10 pixels per frame.
The state attribute has not been used here, but it is useful to know whether you are dealing with a spin or want some useful debug output.
Once the player lets go of the key, when the second set of boxes is called, and the bat's state attribute object will return to "still", and the movepos attribute will return to (0,0), which means that when the update function is called, it will not put the bat.
So when the player releases the key, the bat stops moving.
ordinary

Entertainment 3:Pygame project
So how do we know when players press keys and release them? With the Pygame event queue system, fool! It's a very easy to use and understand system, so it shouldn't take long:) you've seen the role of event queue in the basic Pygame program, which is used to check whether users quit the application. The code of mobile bat is so simple:

for event in pygame.event.get():
    if event.type == QUIT:
        return
    elif event.type == KEYDOWN:
        if event.key == K_UP:
            player.moveup()
        if event.key == K_DOWN:
            player.movedown()
    elif event.type == KEYUP:
        if event.key == K_UP or event.key == K_DOWN:
            player.movepos = [0,0]
            player.state = "still"

Here, suppose you have created an instance of a bat and call it the object player.
You can see the familiar layout of the for structure, which traverses every event found in the Pygame event queue, which uses event Retrieved by get() function.
When the user presses the key, presses the mouse button and moves the joystick, these operations will be entered into the Pygame event queue and remain there until they are processed.
So in each iteration of the main game loop, you will experience these events, check whether they are the events you want to deal with, and then deal with them appropriately.
Event in Bat Pump() function.
Then the Update function is invoked in each iteration to extract the old events and maintain the current state of the queue.
First, we check whether the user is exiting the program. If so, exit the program.
Then we check whether any keys are pressed, and if so, we check whether they are the designated keys for moving the bat up and down.
If they are, we call the appropriate move function and set the player state appropriately (although the state moves and moves in the moveup() and movedown() functions, which makes the code simpler and does not break the encapsulation, which means that you will assign attributes to the object itself,
Without reference to the instance name of the object).
Note that here we have three states: stationary, moving up and moving down.
Similarly, if you want to debug or calculate spin, these will come in handy.
We will also check whether any keys are "released" (i.e. no longer pressed), and if they are the right keys, we will stop the bat from moving.

Added by a1ias on Wed, 09 Feb 2022 23:08:57 +0200