One, foreword

Ready to write a basketball game, players run with the ball, jump shot. In each frame of the picture including athletes and basketball, the use of multiple frames of pictures, to achieve the effect of athletes dribble running.

The width and height of each frame of an athlete’s dribbling movement may be different. For example, taking a long stride and keeping both legs together may not be the same width and height. If the collision of two characters is not considered and the width and height of all frames are maximized to make all frames the same width and height, all frames can be placed in a large figure to achieve animation.

The collision of two characters in Pygame is actually a collision of rectangular boxes outside the graph, i.e. two rectangular boxes overlap, indicating that two characters collide. For fidelity, each rectangle should be as close to the interior as possible. Therefore, there is no guarantee that each frame will be the same width and height. In this case, each frame must be saved in a list.

This small game dribble only 4 frames of modeling, used to complete the ball running animation, note that the ball is also a part of the modeling. The diagram below. Matchstick man is used because it is easy to find and draw one yourself. The background of all 4 frames is set to transparent.

Two, so that athletes follow the mouse to run and dribble

Operation effect picture:

Also need to use the above method to generate 4 frames of modeling files saved to the specified location, copy the source program to run.

import pygame, sys
bgcolor = pygame.Color('blue')                  # create color
pygame.init()
size = width, height = 600.300                  # create a game window of specified size
screen = pygame.display.set_mode(size)          # Set the window title
pygame.display.set_caption("The pitcher dribbles with the mouse.")  
images=[]
for n in range(4):
    p = pygame.image.load('pic/'+str(n+1) +'.png')
    r=p.get_rect()      
    p = pygame.transform.scale(p, (r.width//6, r.height//6))    # Resize the image
    images.append(p)
fclock = pygame.time.Clock()
fps = 4                  
x,y=0.0
frameNum=0
direction=0
running = True
while running:    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:           Handle the exit event
            running = False
        if event.type == pygame.MOUSEMOTION:    # get the mouse position
            a,b=event.pos    
    screen.fill(bgcolor)   # Set the background color
    p=images[frameNum]
    if a-x<0:               # Face the mouse
        p=pygame.transform.flip(p,True.False)
    x,y=a,b
    screen.blit(p, (x, y)) # Draw graphics at the specified position on the screen
    frameNum+=1
    if frameNum==4:
        frameNum=0
    pygame.display.flip()   # Refresh the game scene
    fclock.tick(fps)# The program has been running for several seconds in this frame. To ensure FPS, this statement guarantees delay for the rest of the time
pygame.quit()
Copy the code

Third, added a basketball court background, and players can only move in the court

In order to make the program logic clear, the code is easy to read, will dribble all code with class encapsulation. As you can see, even if the mouse moves off the court, the player does not move off the court.

Operation effect picture:

In addition to generating 4 frames of modeling files to save to the specified location, but also screenshot the background of the basketball court, save as a file under the folder of the source program in the sub-folder PIC. The size of the background picture of the basketball court is 800*600.

import pygame
class Player() :
    def __init__(self,screen) :
        self.screen=screen
        self.images=[]
        for n in range(4) :Save 4 frames of images to the list
            p = pygame.image.load('pic/'+str(n+1) +'.png')      The file name is 1.png,2.png...
            r=p.get_rect()      
            p = pygame.transform.scale(p, (r.width//6, r.height//6))    # Resize the image
            self.images.append(p)
        self.frameNum=0                 # frame number
        self.x,self.y=0.0               # Coordinates the image on the form
        self.mouseX,self.mouseY=0.0     # Mouse coordinates
    def draw(self) :                     # Displays the specified frame graphic in the game window
        p=self.images[self.frameNum]    # get the specified frame graph
        if self.mouseX-self.x<0:
            p=pygame.transform.flip(p,True.False)
        self.x,self.y=self.mouseX,self.mouseY
        if self.x<1:                    #4 if statements keep players on the basketball court
            self.x=1
        if self.x+90>width:
            self.x=width-90
        if self.y<230:
            self.y=230
        if self.y+120>height:
            self.y=height-120
        self.screen.blit(p, (self.x, self.y)) # Draw graphics at the specified position on the screen
        self.frameNum+=1
        if self.frameNum==4:
                self.frameNum=0
bgcolor = pygame.Color('blue')
pygame.init()
size = width, height = 800.600          # create a game window of specified size
screen = pygame.display.set_mode(size)  # Set the window title
pygame.display.set_caption("The pitcher dribbles with the mouse.")
bg_img = pygame.image.load("PIC/basketball court 1.png").convert()
fclock = pygame.time.Clock()    Create clock to control frequency
fps = 4                         # define refresh frequency
player=Player(screen)
running = True
while running:    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:           Handle the exit event
            running = False
        if event.type == pygame.MOUSEMOTION:
            player.mouseX,player.mouseY=event.pos    
    #screen.fill(bgcolor) # set the background color
    screen.blit(bg_img, (0.0))  # Draw background
    player.draw()    
    pygame.display.flip()# Refresh the game scene
    fclock.tick(fps)# The program has been running for several seconds in this frame. To ensure FPS, this statement guarantees delay for the rest of the time
pygame.quit()
Copy the code

The background of the basketball court is shown below, and its size is 800*600.

directlyClick to collect ❤ Dry Goods Full

②Python development environment installation tutorial

③Python400 self-study video

④ Common vocabulary of software development

⑤Python learning roadmap

⑥ Over 3000 Python ebooks