Home Backend Development Python Tutorial How to make games with python

How to make games with python

Jun 25, 2019 pm 03:06 PM
python

Have you ever wondered how computer games are made? It's actually not as complicated as you think!

How to make games with python

PyGame is a Python library that makes it easier for you to write a game. It provides functions such as image processing and sound playback, and they can be easily integrated into your game. Go to the official website and click here to download the PyGame installation package that suits you.

Let’s take masturbation as an example (recommended learning: Python video tutorial)
1. Create the game framework and game background

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

 #这个模块放一些常用的工具和基础类和精灵类

 #在其他模块调用

 import pygame

 import random

 #设置游戏屏幕大小 这是一个常量

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

 #敌机的定时器事件常量

 CREATE_ENEMY_EVENT = pygame.USEREVENT

 

 #定制一个精灵类,需要继承pygame提供的精灵类

 #需要定义的属性有:

 #image图片 

 #rect坐标

 #speed速度

 

 #接下来开始写敌机方面的内容 产生敌机

 #先定义一个事件常量

 CREATE_ENEMY_EVENT = pygame.USEREVENT

 #我们还可以定义一个事件常量(发射子弹)

 HERO_FIRE_EVENT = pygame.USEREVENT + 1

 

 class GameSprite(pygame.sprite.Sprite):

     def __init__(self,new_image,new_speed=1):

        super().__init__()

         #图片

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

         #速度

         self.speed = new_speed

         #位置 获取图片的宽和高 get_rect()(0,0,宽,高)

         self.rect = self.image.get_rect()

         #精灵移动的速度 包括英雄精灵 背景精灵 敌机精灵 子弹精灵

         self.speed = new_speed

 

     def update(self):

         #默认垂直方向移动 y轴控制垂直方向

         self.rect.y += self.speed

         #self.rect.x += 1

 #以上是游戏的基础类,接下来设置背景类

 #明确背景类继承自游戏的精灵类

 class Background(GameSprite):

     def __init__(self,is_alt = False):

         #is_alt判断是否为另一张图像

         #False表示第一张图像

         #Ture表示另外一张图像

         #两张图像交替循环

         #传图片

         super().__init__("/home/zhangyuan/下载/beijing.png")

         if is_alt:

             #如果是第二张图片 初始位置为-self.rect.height

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

     #def __init__(self,new_image):

     #   super().init__(new_image)

     def update(self):

         #调用父类方法

         super().update()

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

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

Copy after login

2. Create Enemy Elf

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

class Enemy(GameSprite):

    def __init__(self):

 

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

    #随机速度

    self.speed = random.randint(10, 15)

    #设置敌机的初始位置

    self.rect.left = SCREEN_RECT.width

    max_ = SCREEN_RECT.height -self.rect.height

    self.rect.bottom = random.randint(0, max_)

 

def update(self):

     

    panduan = random.randint(0, 1)

    if panduan == 0:

        self.rect.y -= self.speed

        self.rect.x -= self.speed

    else:

        self.rect.y += self.speed

        self.rect.x -= self.speed

    #判断敌机是否飞出屏幕  如果飞出屏幕将敌机从精灵组删除

    if self.rect.y >= SCREEN_RECT.height or self.rect.right <=0 or self.rect.bottom <=0:

        self.kill()

Copy after login

3. Create Hero Elf

1

2

3

4

5

6

7

8

9

10

class Bullet(GameSprite):

 

        def __init__(self):

            super().__init__("/home/zhangyuan/images/bullet1.png",-5)

        def update(self):

            super().update()

 

      #判断是否超出屏幕 如果是 从精灵组删除

      if self.rect.bottom < 0:

          self.kill()

Copy after login

5. Collision Detection

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#第一个参数和第二个参数是要参与碰撞检测的精灵

#第三个参数为Ture的时候 就是当碰撞的时候被碰撞的精灵从精灵组移除

pygame.sprite.groupcollide( self.enemy_group,self.hero.bullet, True, True)#子弹

#判断列表时候有内容

    if len(enemies)>0:

        #让英雄牺牲

        self.hero.kill()

        #结束游戏

        PlaneGame.__game_over()

@staticmethod

def __game_over():

    print("游戏结束")

    #这是pygame提供的卸载模块功能

    pygame.quit()

    #这是pygame本身提供的退出脚本的功能

    exit()

    #需要先卸载pygame模块 然后退出脚本

 

   if __name__ == "__main__":

     game = PlaneGame()

     game.star_game()

Copy after login

The process is roughly like this. Pygame can also make many games. Only after special research Know the fun

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to make games with python. 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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

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.

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.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

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.

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.

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.

See all articles