Python makes chicken you are too beautiful keyboard

Let’s watch a video first

QQ small world

In fact, if you look carefully, you can find that the person in this video made a "chicken" sound before he pressed the J key, so this video was actually dubbed in later, but...

Who are we?

We are people who can program!

How can it be done without programming? In fact, this effect can be achieved by using only 20 lines of code. Let’s take a look.

The first step is to guide the database. The library we are going to use this time is Pygame.

import pygame 

Step 2: Initialize the window and set the window size

pygame.init()#初始化
screen = pygame.display.set_mode((500, 500))#设置窗口大小

Step 3: Define the sound function

def playSound(musicFile):#定义播放音乐
    sound = pygame.mixer.Sound(musicFile)
    sound.play()

Step 3: Load image materials

#加载鸡你太美
img = pygame.image.load("img.png")

Step 4: Detect event one: Exit event

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

Step 5: Detect event 2: Keyboard event (1) Detect when the keyboard is pressed

        elif event.type == pygame.KEYDOWN:

Step 6: Detect event three: Keyboard event (2) Detect which key is pressed and make different sounds

            if event.key == pygame.K_j:
                playSound("鸡.mp3")
            elif event.key == pygame.K_n:
                playSound("你.mp3")
            elif event.key == pygame.K_t:
                playSound("太.mp3")
            elif event.key == pygame.K_m:
                playSound("美.mp3")

Step 7: Update and set background color

    screen.blit(img, (0, 0))
    pygame.display.update()

final effect:

Due to system problems, the video cannot be uploaded. If you want to see the final effect, please message me privately. If you want the complete source code, please like and follow. Thank you!

Guess you like

Origin blog.csdn.net/programmer_lyc/article/details/128507401