Pygame mini game: Airplane Pinyin Battle (a gift for your child to learn Pinyin, interstellar travel)

16545229:

The second baby will be in first grade in a year, but he can’t learn pinyin at this stage. I bought a pinyin wall chart and put it on the wall, but I can’t even pull it next to it. I had a sudden idea, why not use python's pygame to make a small game? You can learn while playing, making learning fun! This is a piece of cake for programmers, so I just started doing it, and it took shape in two nights. I will summarize it here and share it with friends in need.

Preface

This is not just a game, but also a popular science movie that will take you to experience interstellar travel. Learn about galaxies, galaxies, constellations, and black holes. The sky is full of stars and the dazzling starry sky can always bring people endless imagination, stimulate the desire to explore, and stimulate the instinct of seeking knowledge.

The pygame mini game "Plane Pinyin Battle" is a game specially designed for children, aiming to help them learn Pinyin letters and stimulate their interest in programming and curiosity about space. This game is both fun and educational. Through the simple Python game production process, children can experience game development and learn the basics of programming.

interest is the best teacher.

The background of the game is themed with space and aviation, providing a wonderful space for children to explore. They can play an astronaut and fly in space while learning the Pinyin alphabet. The follow-up plan is that in the game, children need to use the correct pinyin letters to defeat enemies or pass obstacles according to the letters or Chinese characters that appear on the screen. Through this interactive method, they will learn while having fun, increase their knowledge, cultivate their exploration and imagination about the future of the universe, and increase their curiosity, desire to explore and thirst for knowledge about the future.

The purpose of this game is to allow children to improve their pinyin letter recognition and memory skills while enjoying the game. By interacting with the game, they will gradually become familiar with the pronunciation and writing of Pinyin letters, laying a solid foundation for their future language learning. In addition, by participating in the game-making process, children can develop logical thinking, problem-solving skills and creativity while experiencing the fun of programming.

In fact, I have thought about it very early on, since children love playing games so much, why do most of the games on the market focus on addiction and meaningless monster-fighting and upgrades? Why not create some games with the themes of learning through play, popularizing science knowledge, exploring the unknown, increasing curiosity, and growing simultaneously?

The pygame mini game Airplane: Pinyin Battle revolves around the concept of learning through play, popularizing science knowledge, and stimulating curiosity. It provides children with an interesting and educational learning practice, increases their interest in learning pinyin letters, and provides them with lay a solid foundation for future learning. Let's explore the universe together, learn knowledge, and start the fun of programming!

If you like it, please like it and collect it. It can be used as a gift for your baby.

The source code contains all the materials and can be run.

Download link: https://download.csdn.net/download/qq8864/88314308

Download resources and add me as a friend, and we will provide free technical support. So that you can also play with your baby.

Let’s take a look at the renderings first:

Remember the classic movie "Interstellar"? This small game allows you to experience interstellar travel and see black holes!

Looking up at the stars always gives people endless reverie.

Game introduction

The gameplay is very simple. The original airplane battle game has been redesigned to attack pinyin letters and calculate the score. Each time a letter is hit, its pronunciation is pronounced accordingly. Press the up, down, left and right keys to control the up, down, left and right movement of the aircraft. Press the space bar to send bullets. When a bullet hits a pinyin letter, the corresponding letter's pronunciation will be emitted. There are also moving meteorites that cannot be hit, and points will be deducted if hit. The backgrounds of the games are different, and the wonderful cosmic worlds are selected from the Internet, including the earth, moon, meteorites, Mars and other major planets, the Milky Way, constellations, black holes, and the bright starry sky.

The follow-up plan is that in the game, children need to use the correct pinyin letters to defeat enemies or pass obstacles according to the letters or Chinese characters that appear on the screen. Through this interactive method, they will learn while having fun, increase their knowledge, and cultivate their exploration and imagination about the future of the universe.

Set up a series of levels, each with a different background image, allowing children to appreciate the mysterious universe at the same time. First take off from the earth, fly over the moon, learn about the eight planets, travel through the solar system, avoid meteorites, and finally fly into the starry sky to explore the bright universe.

Flying over the Earth:

Fly to the moon: 

Flyby of Mars:

Flyby eight planets: 

Later, we will fly out of the Milky Way, the Sagittarius constellation, and see the mysterious black hole. Equivalent to interstellar travel, the mysterious universe combined with flight animation is quite shocking!

Environmental preparation

1. Download and install python3

Python official website: Welcome to Python.org

2. Install dependent modules: pygame, pygame-pgu

Python adds environment variables

3. Replace the resource image installed by pip (otherwise, downloading the module will be very slow)

pip  config set  global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

4. Pictures and voice materials

5. iFlytek offline speech synthesis tool

6.goldwave voice production and cropping tool

Source code implementation

The source code implementation is very simple, and anyone with a little basic knowledge can easily understand it. I won’t go into too much introduction here, they are basically some basic usage of pygame. If the challenge fails, a dialog box will pop up, using the pygame-pgu module.

pop-up dialogue box

Simple example of popup dialog:

#退出对话框
class QuitDialog(gui.Dialog):
    def __init__(this,main):
        title = gui.Label("Dialog Box")
        gui.Dialog.__init__(this, title, main)
    def close():
        pygame.quit()
        exit()
       

app = gui.App()                       #初始化gui
con = gui.Container() #生成gui的容器
quitDlg = QuitDialog(con)                    #生成弹窗abc
btn = gui.Button("game over")                 #生成文字为a的按钮
btn.connect(gui.CLICK, quitDlg.close, None)#将按钮与弹窗的弹出绑定
label = gui.Label("Are you sure you want to quit?")
quitDlg.add(label, 2, 2)
quitDlg.add(btn,2,3)                       #将按钮安放在容器(0,0)位置    
app.init(con)           

Display score achieved

Implementation of displaying scores, letters and Chinese characters:

# 加载字体文件
font_path = "./font/SIMYOU.ttf"  # 替换为你的字体文件路径
font_size = 24
font = pygame.font.Font(font_path, font_size)

score = 0
score_txt = "得分:"+str(score) # 要显示的文本
text_surface = font.render(score_txt, True, (255, 255, 255))


#......

    score_txt = "得分:"+str(score)
    text_surface = font.render(score_txt, True, (255, 0, 255))
    screen.blit(text_surface, (680, 10)) 
    
    if show_image:
        screen.blit(fail_image, (300, 100))  # 绘制图像
        
    app.paint()
    pygame.display.update()

Implementation of sprite animation

Principle of animation: In fact, animation is to display static pictures in sequence. If the sequence is displayed faster, the human brain will understand that the characters are continuous. The animation in this mini-game, such as the explosion effect after a bullet hits, is an animation implementation. In fact, it means to load three pictures in advance, and then let the update method of the elf class update the pictures by itself at certain intervals.

The implementation is as follows:

class Explode(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.images = [pygame.image.load('./image/explode' + str(i) + '.png') for i in range(1, 4)]
        self.image_index = 0
        self.image = self.images[self.image_index]
        self.rect = self.image.get_rect()
        self.readt_to_change = 0
        sound = pygame.mixer.Sound('./sound/enemyExplode.wav')
        sound.play()

    def update(self, *args):
        if self.image_index < 2:
            self.readt_to_change += 1
            if self.readt_to_change % 4 == 0:
                self.image_index += 1
                self.image = self.images[self.image_index]
        else:
            self.kill()

Sprites in Pygame 

In Pygame, sprites are the basic elements of various characters, objects and effects in the game. Sprites can contain images, positions, speeds, and other attributes. Multiple sprite objects can be efficiently managed and updated using the sprite class in Pygame.

You can define your own sprite class by inheriting the pygame.sprite.Sprite class in Pygame. When defining an elf class, you usually need to set the elf's initial position, image, and other properties in the __init__ method. For example, the following code defines a simple sprite class MySprite:

import pygame

class MySprite(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill((255, 0, 0))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y 

Handling sprite objects and events

In games, it is often necessary to handle interactions and events with sprite objects. For example, detect collisions between sprites, move sprites, respond to keyboard and mouse events, etc. To handle sprite objects and events, you can use the following code:

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

# 处理键盘事件
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
    my_sprite.rect.x -= 5
if keys[pygame.K_RIGHT]:
    my_sprite.rect.x += 5
if keys[pygame.K_UP]:
    my_sprite.rect.y -= 5
if keys[pygame.K_DOWN]:
    my_sprite.rect.y += 5

# 处理碰撞事件
collision_list = pygame.sprite.spritecollide(my_sprite, my_group, False)
for sprite in collision_list:
    

The pygame.event.get() method is used to get all Pygame events. The pygame.key.get_pressed() method is used to detect the status of keyboard keys. The pygame.sprite.spritecollide() method is used to detect collisions between sprite objects. You can add additional event handling code as appropriate. 

Complete source code implementation 

import pygame
import random
from pgu import gui,timer

# 常量
WIDTH, HEIGHT = 800, 600

# 初始化操作
pygame.init()
pygame.mixer.init()
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))

# 设置游戏标题
pygame.display.set_caption('飞机拼音大作战--关注作者:blog.csdn.net/qq8864')

# 添加音乐
pygame.mixer.music.load('./sound/bgLoop.wav')
pygame.mixer.music.set_volume(0.5)  # 音量
pygame.mixer.music.play(-1, 0)
# 添加系统时钟
FPS = 40
clock = pygame.time.Clock()
# 创建用户自定义事件,每隔2000毫秒触发一次事件,随机创建敌人
CREATE_ENEMY = pygame.USEREVENT
pygame.time.set_timer(CREATE_ENEMY, 2000)

# 加载字体文件
font_path = "./font/SIMYOU.ttf"  # 替换为你的字体文件路径
font_size = 24
font = pygame.font.Font(font_path, font_size)

score = 0
score_txt = "得分:"+str(score) # 要显示的文本
text_surface = font.render(score_txt, True, (255, 255, 255))

fail_image = pygame.image.load("./image/failed.png")
show_image = False  # 控制是否显示图片

tup_target = ('a','o','e','i','u','ü','b','p','m','f','d','t','n','l')
#退出对话框
class QuitDialog(gui.Dialog):
    def __init__(this,main):
        title = gui.Label("Dialog Box")
        gui.Dialog.__init__(this, title, main)
    def close():
        pygame.quit()
        exit()
       

app = gui.App()                       #初始化gui
con = gui.Container() #生成gui的容器
quitDlg = QuitDialog(con)                    #生成弹窗abc
btn = gui.Button("game over")                 #生成文字为a的按钮
btn.connect(gui.CLICK, quitDlg.close, None)#将按钮与弹窗的弹出绑定
label = gui.Label("Are you sure you want to quit?")
quitDlg.add(label, 2, 2)
quitDlg.add(btn,2,3)                       #将按钮安放在容器(0,0)位置    
app.init(con)           
# ========游戏开始页面静态效果==========
# class Hero(pygame.sprite.Sprite)
# class Bullet(pygame.sprite.Sprite)
# class Enemy(pygame.sprite.Sprite)
# class Explode(pygame.sprite.Sprite)
# class BackGround(pygame.sprite.Sprite)
# 主角
class Hero(pygame.sprite.Sprite):
    def __init__(self, speed):
        super().__init__()
        self.image = pygame.image.load('./image/plane.png')
        self.images = [pygame.image.load('./image/planeDie' + str(i) + '.png') for i in range(1, 4)]
        self.image_index = 0
        self.readt_to_change = 0
        self.dired = 0 #默认三条命
        self.rect = self.image.get_rect()
        self.rect.width *= 0.5
        self.rect.height *= 0.5
        self.image = pygame.transform.scale(self.image, (self.rect.width, self.rect.height))
        self.rect.x, self.rect.y = 0, 100
        self.speed = speed
        self.ready_to_fire = 0

    def update(self, *args):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            self.rect.y -= self.speed
        if keys[pygame.K_DOWN]:
            self.rect.y += self.speed
        if keys[pygame.K_LEFT]:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT]:
            self.rect.x += self.speed
        if keys[pygame.K_SPACE]:
            if self.ready_to_fire == 0:
                self.fire()
            self.ready_to_fire += 1
            if self.ready_to_fire > 5:
                self.ready_to_fire = 0
        else:
            self.ready_to_fire = 0
        if self.rect.x < 0:
            self.rect.x = 0
        if self.rect.y < 0:
            self.rect.y = 0
        if self.rect.y > HEIGHT - self.rect.height:
            self.rect.y = HEIGHT - self.rect.height
            
        if self.dired != 0:
            if self.image_index <= 2:
                self.readt_to_change += 1
                if self.readt_to_change % 4 == 0:
                    self.image = self.images[self.image_index]
                    self.image_index += 1
            else:
                self.image_index = 0
                self.kill()
            

    def fire(self):
        bullet = Bullet(10)
        bullet.rect.x = self.rect.right
        bullet.rect.centery = self.rect.centery
        bullet_sprite.add(bullet)
        # 音效
        sound = pygame.mixer.Sound('./sound/laser.wav')
        sound.play()


class Bullet(pygame.sprite.Sprite):
    def __init__(self, speed):
        super().__init__()
        self.image = pygame.image.load('./image/bullet.png')
        self.rect = self.image.get_rect()
        self.speed = speed

    def update(self, *args):
        self.rect.x += self.speed
        if self.rect.x > WIDTH:
            self.kill()


class Enemy(pygame.sprite.Sprite):
    count_ = 0
    def __init__(self, speed):
        super().__init__()
        Enemy.count_ += 1
        self.image = pygame.image.load('./image/'+'enemy'+str( Enemy.count_)+".png")
        self.rect = self.image.get_rect()
        self.rect.x = 800
        self.rect.y = random.randint(0, HEIGHT)
        self.speed = speed
        self.id = Enemy.count_
        self.name = 'enemy'+str( Enemy.count_)
        print("self.id=",self.id)
        print("Enemy.count=",Enemy.count_)
        if Enemy.count_ >= 50:
            Enemy.count_=0

    def update(self, *args):
        self.rect.x -= self.speed
        if self.rect.right < 0:
            self.kill()


class Explode(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.images = [pygame.image.load('./image/explode' + str(i) + '.png') for i in range(1, 4)]
        self.image_index = 0
        self.image = self.images[self.image_index]
        self.rect = self.image.get_rect()
        self.readt_to_change = 0
        sound = pygame.mixer.Sound('./sound/enemyExplode.wav')
        sound.play()

    def update(self, *args):
        if self.image_index < 2:
            self.readt_to_change += 1
            if self.readt_to_change % 4 == 0:
                self.image_index += 1
                self.image = self.images[self.image_index]
        else:
            self.kill()


class BackGround(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('./image/background1.jpg')
        self.rect = self.image.get_rect()
        self.ready_to_move = 0
        self.index = 1

    def update(self, *args):
        self.rect.x -= 3
        if self.rect.right <= 0:
            self.index+=1
            self.image = pygame.image.load('./image/background'+str(self.index)+'.jpg')
            self.rect = self.image.get_rect()
            self.rect.x = self.rect.width
            if self.index == 4:
                self.index = 3


# 初始化精灵组
bg_sprite = pygame.sprite.Group()
hero_sprite = pygame.sprite.Group()
enemy_sprite = pygame.sprite.Group()
bullet_sprite = pygame.sprite.Group()
explode_sprite = pygame.sprite.Group()

# 定义人物

hero1 = Hero(4)
hero_sprite.add(hero1)

enemy1 = Enemy(5)
enemy2 = Enemy(7)

bg1 = BackGround()
bg2 = BackGround()
bg2.rect.x = bg2.rect.width
bg_sprite.add(bg1, bg2)

# 保持游戏运行状态(游戏循环)
while True:
    # ===========游戏帧的刷新===========
    clock.tick(FPS)

    # 检测事件
    for event in pygame.event.get():
        # 检测关闭按钮被点击的事件
        if event.type == pygame.QUIT:
            # 退出
            pygame.quit()
            exit()
        if event.type == CREATE_ENEMY:
            enemy_sprite.add(Enemy(random.randint(1, 4)))
        app.event(event)    #将pygame的事件传递给pgu,很重要

    # 碰撞检测,返回字典,得到二者信息
    collision = pygame.sprite.groupcollide(enemy_sprite, bullet_sprite, True, True)
    for enemy in collision.keys():
        explode = Explode()
        explode.rect = enemy.rect
        explode_sprite.add(explode)
        print("enemy.id:"+str(enemy.id))
        score+=1

    # 碰撞检测,返回字典,得到二者信息
    collision1 = pygame.sprite.groupcollide(enemy_sprite, hero_sprite, True, False)
    for enemy in collision1.keys():
        hero1.dired += 1
        quitDlg.open()
        show_image = True
        break
        #explode = Explode()
        #explode.rect = enemy.rect
        #explode_sprite.add(explode)
        #quitDlg.open()
        
    # screen.fill((0,0,0))
    for group in [bg_sprite, hero_sprite, enemy_sprite, bullet_sprite, explode_sprite]:
        group.update()
        group.draw(screen)
    #screen.fill((0,0,0))    #生成一个屏幕  
    score_txt = "得分:"+str(score)
    text_surface = font.render(score_txt, True, (255, 0, 255))
    screen.blit(text_surface, (680, 10)) 
    
    if show_image:
        screen.blit(fail_image, (300, 100))  # 绘制图像
        
    app.paint()
    pygame.display.update()
    #app.paint()             #将pgu容器的内容画出

Voice material production

A fun game is definitely indispensable for the production of exquisite pictures and sounds. Here we create background pictures, and we select some beautiful and shocking universe pictures from the Internet as backgrounds. For other Pinyin letters, beautiful and colorful Pinyin letters are intercepted from the Internet.

Here we focus on the production of Pinyin pronunciation files. It is almost difficult to find a single ready-made WAV file of Chinese Pinyin on the Internet. Here are two methods. One is to find audio files that cover the pronunciations of all the regular and complete Pinyin letters and use goldwave software to edit them. The advantage is that the pronunciation is more standard, but editing is more troublesome and you need to find the corresponding audio files.

Another method is to use iFlytek's offline speech synthesis technology to synthesize speech. For example, enter the letter 'a' and let it synthesize the pronunciation. But I tried it and found that it was in English. But there is still a way. Just input the corresponding Chinese characters of a - a o - oh e - uh i - 一 u - wu, synthesize the entire speech, and then cut it through the goldwave software.

const char* text  = "啊,我,额,一,无,与,波,破,摸,佛,的,特,呢,了,个,可,和,及,器,洗,之,吃,时,日,子,此,思,一,无"; //合成文本

For example, use iFlytek's offline language synthesis technology to synthesize the above paragraph, separated by commas. Then use the goldwave audio cutting and production tool to cut each piece of audio and save it into a wav format audio file with pinyin letters. However, the pronunciation may not be standard due to the pitch, so try to find words with accurate pronunciation and a single tone.

The closest pronunciation I found is as follows:

韵母:a, o, e, i, u, ü, ai, ei, ui, ao, ou, iu, ie, üe, er, an, en, in, un, ün, ang, eng, ing, ong

阿,窝,额,一,屋,迂,挨,诶,微,凹,欧,优,页,约,儿,安,恩,音,温,晕,盎,鞥,英,翁

声母:b, p, m, f, d, t, n, l, g, k, h, j, q, x, zh, ch, sh, r, z, c, s ,y,w

播,泼,摸,佛,的,特,呢,嘞,哥,蝌,喝,机,其,西,织,吃,狮,日,资,疵,丝,衣,屋

Editing is also very convenient, because it is separated by commas. Each small green waveform below is a pronunciation file. 

C code for sound synthesis:

/*
* 语音合成(Text To Speech,TTS)技术能够自动将任意文字实时转换为连续的
* 自然语音,是一种能够在任何时间、任何地点,向任何人提供语音信息服务的
* 高效便捷手段,非常符合信息时代海量数据、动态更新和个性化查询的需求。
*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include "../../include/qtts.h"
#include "../../include/msp_cmn.h"
#include "../../include/msp_errors.h"
typedef int SR_DWORD;
typedef short int SR_WORD ;

/* wav音频头部格式 */
typedef struct _wave_pcm_hdr
{
	char            riff[4];                // = "RIFF"
	int				size_8;                 // = FileSize - 8
	char            wave[4];                // = "WAVE"
	char            fmt[4];                 // = "fmt "
	int				fmt_size;				// = 下一个结构体的大小 : 16

	short int       format_tag;             // = PCM : 1
	short int       channels;               // = 通道数 : 1
	int				samples_per_sec;        // = 采样率 : 8000 | 6000 | 11025 | 16000
	int				avg_bytes_per_sec;      // = 每秒字节数 : samples_per_sec * bits_per_sample / 8
	short int       block_align;            // = 每采样点字节数 : wBitsPerSample / 8
	short int       bits_per_sample;        // = 量化比特数: 8 | 16

	char            data[4];                // = "data";
	int				data_size;              // = 纯数据长度 : FileSize - 44 
} wave_pcm_hdr;

/* 默认wav音频头部数据 */
wave_pcm_hdr default_wav_hdr = 
{
	{ 'R', 'I', 'F', 'F' },
	0,
	{'W', 'A', 'V', 'E'},
	{'f', 'm', 't', ' '},
	16,
	1,
	1,
	16000,
	32000,
	2,
	16,
	{'d', 'a', 't', 'a'},
	0  
};
/* 文本合成 */
int text_to_speech(const char* src_text, const char* des_path, const char* params)
{
	int          ret          = -1;
	FILE*        fp           = NULL;
	const char*  sessionID    = NULL;
	unsigned int audio_len    = 0;
	wave_pcm_hdr wav_hdr      = default_wav_hdr;
	int          synth_status = MSP_TTS_FLAG_STILL_HAVE_DATA;

	if (NULL == src_text || NULL == des_path)
	{
		printf("params is error!\n");
		return ret;
	}
	fp = fopen(des_path, "wb");
	if (NULL == fp)
	{
		printf("open %s error.\n", des_path);
		return ret;
	}
	/* 开始合成 */
	sessionID = QTTSSessionBegin(params, &ret);
	if (MSP_SUCCESS != ret)
	{
		printf("QTTSSessionBegin failed, error code: %d.\n", ret);
		fclose(fp);
		return ret;
	}
	ret = QTTSTextPut(sessionID, src_text, (unsigned int)strlen(src_text), NULL);
	if (MSP_SUCCESS != ret)
	{
		printf("QTTSTextPut failed, error code: %d.\n",ret);
		QTTSSessionEnd(sessionID, "TextPutError");
		fclose(fp);
		return ret;
	}
	printf("正在合成 ...\n");
	fwrite(&wav_hdr, sizeof(wav_hdr) ,1, fp); //添加wav音频头,使用采样率为16000
	while (1) 
	{
		/* 获取合成音频 */
		const void* data = QTTSAudioGet(sessionID, &audio_len, &synth_status, &ret);
		if (MSP_SUCCESS != ret)
			break;
		if (NULL != data)
		{
			fwrite(data, audio_len, 1, fp);
		    wav_hdr.data_size += audio_len; //计算data_size大小
		}
		if (MSP_TTS_FLAG_DATA_END == synth_status)
			break;
	}
	printf("\n");
	if (MSP_SUCCESS != ret)
	{
		printf("QTTSAudioGet failed, error code: %d.\n",ret);
		QTTSSessionEnd(sessionID, "AudioGetError");
		fclose(fp);
		return ret;
	}
	/* 修正wav文件头数据的大小 */
	wav_hdr.size_8 += wav_hdr.data_size + (sizeof(wav_hdr) - 8);
	
	/* 将修正过的数据写回文件头部,音频文件为wav格式 */
	fseek(fp, 4, 0);
	fwrite(&wav_hdr.size_8,sizeof(wav_hdr.size_8), 1, fp); //写入size_8的值
	fseek(fp, 40, 0); //将文件指针偏移到存储data_size值的位置
	fwrite(&wav_hdr.data_size,sizeof(wav_hdr.data_size), 1, fp); //写入data_size的值
	fclose(fp);
	fp = NULL;
	/* 合成完毕 */
	ret = QTTSSessionEnd(sessionID, "Normal");
	if (MSP_SUCCESS != ret)
	{
		printf("QTTSSessionEnd failed, error code: %d.\n",ret);
	}

	return ret;
}

int main(int argc, char* argv[])
{
	int         ret                  = MSP_SUCCESS;
	const char* login_params         = "appid = 99999, work_dir = .";//登录参数,appid与msc库绑定,请勿随意改动
	/*
	* rdn:           合成音频数字发音方式
	* volume:        合成音频的音量
	* pitch:         合成音频的音调
	* speed:         合成音频对应的语速
	* voice_name:    合成发音人
	* sample_rate:   合成音频采样率
	* text_encoding: 合成文本编码格式
	*
	*/
	const char* session_begin_params = "engine_type = local,voice_name=xiaoyan, text_encoding = UTF8, tts_res_path = fo|res/tts/xiaoyan.jet;fo|res/tts/common.jet, sample_rate = 16000, speed = 50, volume = 50, pitch = 50, rdn = 2";
	const char* filename             = "tts_sample.wav"; //合成的语音文件名称
	const char* text                 = "啊,我,额,一,无,与,波,破,摸,佛,的,特,呢,了,个,可,和,及,器,洗,之,吃,时,日,子,此,思,一,无"; //合成文本
	/* 用户登录 */
	ret = MSPLogin(NULL, NULL, login_params); //第一个参数是用户名,第二个参数是密码,第三个参数是登录参数,用户名和密码可在http://www.xfyun.cn注册获取
	if (MSP_SUCCESS != ret)
	{
		printf("MSPLogin failed, error code: %d.\n", ret);
		goto exit ;//登录失败,退出登录
	}

	printf("\n###########################################################################\n");
	printf("###########################################################################\n\n");

	/* 文本合成 */
	printf("开始合成 ...\n");
	ret = text_to_speech(text, filename, session_begin_params);
	if (MSP_SUCCESS != ret)
	{
		printf("text_to_speech failed, error code: %d.\n", ret);
	}
	printf("合成完毕\n");

exit:
	printf("按任意键退出 ...\n");
	getchar();
	MSPLogout(); //退出登录

	return 0;
}

Corresponding makefile:

#common makefile header

DIR_INC = ../../include
DIR_BIN = ../../bin
DIR_LIB = ../../libs

TARGET	= tts_offline_sample
BIN_TARGET = $(DIR_BIN)/$(TARGET)

CROSS_COMPILE = 
CFLAGS = -g -Wall -I$(DIR_INC)

ifdef LINUX64
LDFLAGS := -L$(DIR_LIB)/x64
else
LDFLAGS := -L$(DIR_LIB)/x86 
endif
LDFLAGS += -lmsc -lrt -ldl -lpthread -lstdc++

OBJECTS := $(patsubst %.c,%.o,$(wildcard *.c))

$(BIN_TARGET) : $(OBJECTS)
	$(CROSS_COMPILE)gcc $(CFLAGS) $^ -o $@ $(LDFLAGS)

%.o : %.c
	$(CROSS_COMPILE)gcc -c $(CFLAGS) $< -o $@
clean:
	@rm -f *.o $(BIN_TARGET)

.PHONY:clean

#common makefile foot

Summary of the game development process with Pygame

The following is the general usage process:

1. Set up Pygame: Use pip to install the Pygame library and import it in the Python script.

2. Initialize Pygame: Use to pygame.init()initialize the Pygame module.

3. Set up the game window: Use pygame.display.set_mode()to create a game window. Set window size, title, and other properties.

4. Game Loop: Create a loop to continuously run the game. This loop handles user input, updates game logic, and renders game graphics.

5. Handle events: Inside the game loop, use pygame.event.get()to handle various events, such as keyboard or mouse input. Respond to these events according to the needs of the game.

6. Update game state: Update the game state based on user input and other factors. This includes moving game objects, detecting collisions, updating scores, and more.

7. Render graphics: Use pygame.Surfaceand pygame.drawfunctions to render game graphics to the game window. Includes drawing game objects, backgrounds, text, and other visual elements.

8. Display Update: Use pygame.display.flip()or pygame.display.update()to update the game window to show the changes of the current frame.

9. Game logic: Implement game-specific logic, rules and mechanics. This may include levels, scores, props, enemy AI, etc.

10. Exit the game: handle the game exit event and use pygame.quit()to clean up resources.

Here is a simple Pygame game example showing a window and a moving character:

import pygame
from pygame.locals import *

# 初始化Pygame
pygame.init()

# 设置游戏窗口
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('我的游戏')

# 游戏循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

    # 更新游戏状态

    # 渲染图形
    screen.fill((0, 0, 0))  # 用黑色填充屏幕
    pygame.draw.rect(screen, (255, 0, 0), (100, 100, 50, 50))  # 在(100, 100)处绘制一个红色矩形

    # 显示更新
    pygame.display.flip()

# 退出游戏
pygame.quit()

Finally, if you need a complete runnable program, please add the author's WeChat account on the homepage or follow the official account and leave a message to request it.

Other resources

python+pygame game development using Py2exe to package games-Tencent Cloud Developer Community-Tencent Cloud

Baidu security verification

Detailed explanation of the process of packaging python modules into .exe files - Zhihu

6 ways to package Python code and turn your program into an exe application! _python packaged exe_JPX-NO's blog-CSDN blog

pip domestic image source - Python installation of third-party libraries (one article is enough, all useful information) - Zhihu

python--pygame implements menu column settings at all levels_pygame drop-down menu_DY.work's blog-CSDN blog

python Xuanji fighting skills--tkinter library_Ma Xiaoyao's blog-CSDN blog

Summary of commonly used third-party libraries in Python - Zhihu

GitHub - ppizarror/pygame-menu: A menu for pygame (pygame-ce also supported!). Simple, and easy to use

The most complete tutorial on Python pygame (GUI programming) module (1)_Detailed explanation of pygame module_Python-ZZY's blog-CSDN blog

Pygame tutorial (very detailed)

Guess you like

Origin blog.csdn.net/qq8864/article/details/132742982