Home Backend Development Python Tutorial Can Python write WeChat games?

Can Python write WeChat games?

Jun 19, 2019 pm 05:30 PM
pygame python WeChat mini games

PyPoice is a Python wrapper module for the SDL multimedia library. It contains Python functions and classes that allow support for CDROM, audio and video output, keyboard, mouse and joystick input using SDL.

Can Python write WeChat games?

Pygame is a game library written using the SDL library. It is a set of Python program modules used to develop game software. SDL, full name Simple DirectMedia Layer, SDL is written in C, but it can also be developed in C. Of course, there are many other languages. Pygame is a library that uses it in Python. pygame allows you to create feature-rich games and multimedia programs in Python programs. It is a highly portable module that can support multiple operating systems. It is very suitable for developing small games.

Installation of pygame library

pip install Pygame

Can Python write WeChat games?

Related recommendations: "Python video tutorial

How to use the pygame library

>>> import pygame as pg

>>> a =pg.font.get_fonts() #Query all font formats of the current computer

>>> a

Can Python write WeChat games?

Develop small games

1. Material preparation

First of all, let’s preview the final running interface of the game

Can Python write WeChat games?

According to the game interface, we can Clearly know that you must first prepare game background pictures, airplane pictures, bullet pictures, etc.

2. Code part

Library dependency:

pygame

This game mainly has two py files, the main file plan_main The .py code part is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

from plan_sprite import *

class PlanGame(object):

    """飞机大战主程序"""

    def __init__(self):

        print("游戏初始化")

        # 创建游戏窗口

        self.screen = pygame.display.set_mode(SCREEN_RECT.size)

        # 创建游戏时钟

        self.clock = pygame.time.Clock()

        # 调用私有方法,精灵和精灵组的创建

        self._create_sprite()

        # 设置定时器事件 - 1秒创建一个敌机

        pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)

        # 设置定时器事件 - 0.5秒创建一个子弹

        pygame.time.set_timer(HERO_FIRE, 100)

    def _create_sprite(self):

        # 创建背景精灵和精灵组

        bg1 = BackGround()

        bg2 = BackGround(True)

        self.back_group = pygame.sprite.Group(bg1, bg2)

        # 创建精灵组

        self.enemy_group = pygame.sprite.Group()

        # 创建英雄精灵和精灵组

        self.hero = Hero()

        self.hero_group = pygame.sprite.Group(self.hero)

    def start_game(self):

        print("游戏开始...")

        while True:

            # 设置刷新帧率

            self.clock.tick(FRAME_PER_SECOND)

            # 事件监听

            self._event_handler()

            # 碰撞检测

            self._check_collide()

            # 更新/绘制游戏精灵

            self._update_sprite()

            # 刷新屏幕

            pygame.display.update()

    def _event_handler(self):

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                PlanGame._game_over()

            elif event.type == CREATE_ENEMY_EVENT:

                # 创建敌机精灵

                enemy = Enemy()

                # 将创建的敌机精灵加到精灵组

                self.enemy_group.add(enemy)

            # 第一种按键监听方法

            # if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:

            #     self.hero.speed = 2

            # elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:

            #     self.hero.speed = -2

            # else:

            #     self.hero.speed = 0

                # 第二种:使用键盘模块提供的方法获取按键元组

                keys_pressed = pygame.key.get_pressed()

                # 判断元组中的按键索引值

                if keys_pressed[pygame.K_RIGHT]:

                   self.hero.speed = 2

                elif keys_pressed[pygame.K_LEFT]:

                   self.hero.speed = -2

                else:

                   self.hero.speed = 0

                # 飞机发射子子弹事件

                self.hero.fire()

    def _check_collide(self):

        pygame.sprite.groupcollide(self.enemy_group, self.hero.bullets, True, True)

        enemy_list = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)

        if len(enemy_list):

            self.hero.kill()

            PlanGame._game_over()

    def _update_sprite(self):

        self.back_group.update()

        self.back_group.draw(self.screen)

        self.enemy_group.update()

        self.enemy_group.draw(self.screen)

        self.hero_group.update()

        self.hero_group.draw(self.screen)

        self.hero.bullets.update()

        self.hero.bullets.draw(self.screen)

    @staticmethod

    def _game_over():

        print("游戏结束")

        pygame.quit()

        exit()

if __name__ == '__main__':

    # 创建游戏对象

    game = PlanGame()

    # 启动游戏

    game.start_game()

Copy after login

The following is the initialization aircraft sprite file, the file name is plan_sprite.py. The main functions include initializing the aircraft sprite class, enemy aircraft class, bullet class, setting background class, etc. The code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

import random

import pygame

# 定义常量

SCREEN_RECT = pygame.Rect(0, 0, 480, 700)

FRAME_PER_SECOND = 60

# 创建敌机的定时器常量

CREATE_ENEMY_EVENT = pygame.USEREVENT

HERO_FIRE = pygame.USEREVENT + 1  # 英雄发射子弹事件

class GameSprite(pygame.sprite.Sprite):

    # 飞机大战游戏精灵

    def __init__(self, image_name, speed=1):

        # 调用父类的初始化方法

        super().__init__()

        # 设置属性

        self.image = pygame.image.load(image_name)

        self.rect = self.image.get_rect()

        self.speed = speed

    def update(self):

        self.rect.y += self.speed

class BackGround(GameSprite):

    """游戏背景对象"""

    def __init__(self, is_alt=False):

        super().__init__("./images/background.png")

        if is_alt:

            self.rect.y = -self.rect.height

    def update(self):

        # 1.调用父类的方法

        super().update()

        # 2、判断是否移出屏幕,当背景移出屏幕,将图像设置到图像上方

        if self.rect.y >= SCREEN_RECT.height:

            self.rect.y = -self.rect.height

class Enemy(GameSprite):

    def __init__(self):

        # 调用父类的方法,创建敌机精灵,同时指定敌机图片

        super().__init__("./images/enemy1.png")

        # 指定敌机的随机速度

        self.speed = random.randint(1, 3)

        # 指定敌机的初始位置

        self.rect.bottom = 0

        max_x = SCREEN_RECT.width - self.rect.width

        self.rect.x = random.randint(1, max_x)

    def update(self):

        # 调用父类方法,保持垂直飞行

        super().update()

        # 判断是否飞出屏幕,若是,则从精灵组中删除敌机精灵

        if self.rect.y >= SCREEN_RECT.height:

            self.kill()

    def __del__(self):

        # print("敌机挂了 %s",self.rect)

        pass

class Hero(GameSprite):

    """飞机精灵"""

    def __init__(self):

        # 调用父类方法,设置image_name

        super().__init__("./images/me1.png", 0)

        # 设置飞机初始位置

        self.rect.centerx = SCREEN_RECT.centerx     # 设置飞机初始位置居中

        self.rect.bottom = SCREEN_RECT.bottom - 20      # 初始化飞机位置为距底部向上少20

        # 创建子弹精灵组

        self.bullets = pygame.sprite.Group()

    def update(self):

        # 飞机水平移动

        self.rect.x += self.speed

        if self.rect.left < 0:      # 防止飞机从左边边界移出

            self.rect.left = 0

        elif self.rect.right > SCREEN_RECT.right:       # 同理,防止飞机从右边移出边界

            self.rect.right = SCREEN_RECT.right

    def fire(self):

        # 创建子弹精灵

        bullet = Bullet()

        # 设置子弟位置

        bullet.rect.bottom = self.rect.y - 20

        bullet.rect.centerx = self.rect.centerx

        # 将精灵添加到精灵组

        self.bullets.add(bullet)

class Bullet(GameSprite):

    """子弹精灵"""

    def __init__(self):

        super().__init__("./images/bullet1.png", -2)        # 初始化子弹,-2为子弹移动速度

    def update(self):

        # 调用父类方法,子弹垂直飞行

        super().update()

        if self.rect.bottom < 0:

            self.kill()

Copy after login

The above is the detailed content of Can Python write WeChat games?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles