Use pygame to implement a music player (two)

In the previous article, we have realized the picture display and music playback, and then the button click is realized. Clicking the button needs to be implemented through event handling.

Pygame is event-driven, which means that if there are no events, the game will stop and wait for user actions (events). Therefore, there must be an event loop in the game to keep detecting user events, otherwise the program will end directly. In pygame, events such as user keystrokes, mouse operations, window changes, etc. will be generated. These events are queued in the order of occurrence. We can take events out of the event queue for processing in the event loop.

  • Event acquisition

    We can use the following methods to get events from the event queue. The following methods all return event objects.

    Method name parameter Features
    pygame.event.get(type或typelist) type or typelist, if type or typelist is specified, only events of the specified type are obtained Get and delete events from the queue.
    pygame.event.poll() no Return from the queue and delete an event. If the event queue is empty, an event of type pygame.NOEVENT will be returned immediately.
    pygame.event.wait() no Return from the queue and delete an event. If the queue is empty, the function will continue to wait until there is an event in the queue. When the program is waiting, it will stay asleep and will not continue until an event occurs.

    Please note that if you use pygame.event.get() to get and delete only specified events from the queue, over time, the queue may be filled with events that you don't care about.

  • Event type

    The event object has a type attribute, which indicates the type of event. The system has defined the event type. The constants of these event types can be obtained from pygame.locals

    event Way of production parameter
    QUIT The user presses the close button none
    ATIVEEVENT Pygame is activated or hidden gain, state
    KEYDOWN Keyboard is pressed unicode, key, mod
    KEYUP Keyboard is let go key, mod
    MOUSEMOTION Mouse movement pos, rel, buttons
    MOUSEBUTTONDOWN Mouse down pos, button
    MOUSEBUTTONUP Mouse let go pos, button
    VIDEORESIZE Pygame window zoom size, w, h
    VIDEOEXPOSE Part of the Pygame window is exposed (expose) none
    USEREVENT A user event was triggered code

    The event type supports equivalence comparison. If two events have the same type and attribute value, then the two events are considered equal.

  • Mouse event

    • MOUSEMOTION mouse movement event, the event will occur when the mouse moves, it has three parameters:

      • buttons: A tuple containing three numbers. The three values ​​represent the left, middle, and right buttons, respectively. 1 is pressed.

      • pos: the position of the mouse cursor

      • rel: represents the distance from the last time the mouse event was generated

    • MOUSEBUTTONUP mouse button release event

      • event.pos The current coordinates of the mouse (x, y), relative to the upper left corner of the window

      • event.button The number n of the button pressed by the mouse is 0/1/2, corresponding to three keys respectively

    • MOUSEBUTTONDOWN mouse button down event

      • event.pos The current coordinates of the mouse (x, y), relative to the upper left corner of the window

      • event.button The number n of the mouse button pressed is an integer, the left button is 1, and the right button is 3, device-related

We can define the positions of the previous, stop, next and volume buttons in the background image as follows:

NEXTBUTTONPOS = pygame.Rect(300,292,69,66)  # 下一首按钮的位置
STOPBUTTONPOS = pygame.Rect(210,292,69,66)  # 停止按钮的位置
PREVIOUSBUTTONPOS = pygame.Rect(110,292,69,66)  # 前一首按钮的位置
VOLUMEBUTTONPOS = pygame.Rect(30,325,28,21)  # 音量按钮的位置

In pygame, the Rect type can describe the position of the object, and the upper left corner of the screen is the origin:

Pygame stores and manipulates the rectangular area through the Rect object. A Rect object can be created by several values ​​of left, top, width, and height. Rects can also be created by Pygame objects, they have the following properties:

x,y  # 坐标
top, left, bottom, right  # top是y,left是x
topleft # 左上角坐标,是一个元组(x,y)
midtop, midleft, midbottom, midright
center, centerx, centery
width, height  # 宽,高
w,h # 宽,高
size # 大小,元组(w,h)

The most important thing is that it has a collidepoint (point) to test whether a point is in the rectangle, we can use this method to test whether the button is clicked

running = True
while running:
    # 处理用户的事件
    for event in pygame.event.get():
        # type事件类型
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN: # 按下鼠标
            if NEXTBUTTONPOS.collidepoint(event.pos):
                print("下一首按钮")
            elif PREVIOUSBUTTONPOS.collidepoint(event.pos):
                print("前一首按钮")
            elif STOPBUTTONPOS.collidepoint(event.pos):
                print("停止按钮")
            elif VOLUMEBUTTONPOS.collidepoint(event.pos):
                print("音量按钮")

event.pos represents the coordinates of the mouse, which is a point, so that you can test whether the mouse clicks on the button

1. The next button is implemented

First calculate the value of index and get the subscript of the song to be played. If it crosses the boundary, it should be set to 0 to achieve loop playback. Here, modular arithmetic can be used to solve the problem of cross-border.

 if NEXTBUTTONPOS.collidepoint(event.pos): # 下一首
       index  = (index + 1) % len(song_list) # 计算下一首的下标
       play(index)

2. The realization of the previous song

elif PREVIOUSBUTTONPOS.collidepoint(event.pos): # 前一首
    index = (len(song_list) - 1)  if index == 0 else (len(song_list) - 1)
    play(index)

3. The stop button is implemented

elif STOPBUTTONPOS.collidepoint(event.pos):
     pygame.mixer.music.stop()

4. Volume button implementation

Press the left mouse button to increase the volume, and the right mouse button to decrease the volume

volume = pygame.mixer.music.get_volume()  # 获取当前的音量
if event.button == 1:  #左键增加
       volume = (volume+0.1) if volume <= 0.9 else 1  
       pygame.mixer.music.set_volume(volume)  # 设置音量
elif event.button == 3:  # 右键减少
       volume = (volume-0.1) if volume > 0.1 else 0
       pygame.mixer.music.set_volume(volume)

To be continued.....

 

Guess you like

Origin blog.csdn.net/chengshaolei2012/article/details/114146310