Python implementation aircraft war game (complete code attached files and material)

Foreword

Self Python's records, but not like do not spray!
This program is based on the code B station programmers dark horse of video codes based on personal summary to be thinking, writing on the blog purely to record their learning process!

Had thought to use the Python pygame module development aircraft war game, suddenly excited, after all, is the best way to learn to apply their knowledge, let alone make a game, but when I really started finding and did not imagine so easy. Of course, everything is hard in the beginning, and then have some experience behind the road will be much easier.

pygame module installation

The first step in the development of this game is to install pygame module, when I installed the pygame entirely, and can run its built-in games in accordance with the requirements of the teacher using the command line in a terminal, but to open the file when import pygame module, Whether I get Zage always "NO module named pygame", I installed unloading, unloaded the equipment, crunching over the past fiddle, always fix mentality collapse. So I gave up, but unwilling, access to a multi-party data, hard work pays off, and finally stumbled on a solution in my previous blog. https://blog.csdn.net/qq_43779324/article/details/104594396, of course, there are other heavyweights better solution, I had never found strange, by the way Tucao about CSDN search function, not often found that Tau the horse's mouth, I can search Google gradually getting to CSDN blog content, you can not search within the software? Specific installation methods, you can look at this: https: //blog.csdn.net/sinat_40043477/article/details/78276460 depth_1-utm_source = distribute.pc_relevant.none-task & utm_source = distribute.pc_relevant.none-task?

Getting pygame

After the completion of good pygame modules are installed, we will officially begin our game developed! Prior to this, we first come to know about Python, pygame module, pygame is a Python in a 2D game development library support for editing sound and image, of course, in the popularity of the current 3D games, pygame gradually decline, but this It does not prevent us learn something. pygame program like this is the following general structure, the init () function starts, quit () function exits, the intermediate is a specific game code.

import pygame
pygame.init()
# 编写游戏的代码
print("游戏的代码...")
pygame.quit()

Used to describe a rectangular area Rect

Python game coordinate system to describe the location of various components of the game, the origin in the upper left, x right horizontal axis, y-axis level downwards. Describes a rectangular area width and height but also because one can only express its position coordinates of the upper left corner, and then add the width and height on the set dead.

import pygame
hero_rect = pygame.Rect(100, 500, 120, 125)
print("英雄的原点%d %d" % (hero_rect.x, hero_rect.y))
print("英雄的尺寸%d %d" % (hero_rect.width, hero_rect.height))
print("%d %d" % hero_rect.size)

Create a game window

pygame the expertise to provide a module pygame.display for creating, managing the game window. There are two methods:

  • pygame.display.set_moudle (): used to initialize the game window. There are four parameters width and height, windows, whether full screen, the color of the window.
  • pygame.display.update (): used to refresh the contents of the display screen, for later use.
import pygame
pygame.init()
# 创建游戏的窗口
pygame.display.set_mode((480, 700))
while True:
    pass
pygame.quit()

Game window width 480, high 700, in pixels, the set is behind us background image consistent. while loop is the main game loop, as long as no command to exit the game, we should have been implemented.

Draw image

After the game window is created, it is necessary to put something, or you would stare at a black hemp window to see Shane! The load pygame () function to load image data, blit () function to draw the image, update () function updates the display screen, each drawing a picture will be called once the update method, of course, also be placed last update method is called only once.

import pygame
pygame.init()
# 创建游戏的窗口
screen = pygame.display.set_mode((480, 700))
# 绘制背景图像
# 1.加载图像数据
bg = pygame.image.load("./images/background.png")
# 2.blit绘制图像
screen.blit(bg, (0, 0))
# 3.update更新屏幕显示
pygame.display.update()
# 绘制英雄的飞机
hero = pygame.image.load("./images/me1.png")
screen.blit(hero, (180,500))
pygame.display.update()
while True:
    pass
pygame.quit()

After these get that done will look like:
Here Insert Picture Description

Game Loop

The game loop means the beginning of the game, the role of the game loop is to ensure that the game will not exit, transform the image position to achieve animation effects and detection of interactive content with the user. Specifically includes setting a refresh frame rate, the user interaction is detected, the position of the image update, updates the screen display and the like.

while True:
	pass

Game Clock

pygame specializes in a class pygame.time.Clock can easily setup screen rendering speed - refresh frame rate. Initialized in the game to create a clock object and let the clock object in the game loop calls the tick () method, tick () method will be based on the last time is called, set the game automatically cycle delay.

......
# 创建时钟对象
clock = pygame.time.Clock()
while True:
    # 可以指定循环体内部的代码执行频率
    clock.tick(60)
......

Monitor events

After the event is the game starts, the user operation done for the game. For example: the user clicks the mouse, press the keyboard, and so on.
Listening is to determine the user's specific operation, only captures the user's specific operation, in order to respond focused.
pygame by pygame.event.get () event can obtain the current list of operations made by the user

import pygame
pygame.init()
# 创建游戏的窗口
screen = pygame.display.set_mode((480, 700))
# 绘制背景图像
bg = pygame.image.load("./images/background.png")
screen.blit(bg, (0, 0))
#  pygame.display.update()
# 绘制英雄的飞机
hero = pygame.image.load("./images/me1.png")
# screen.blit(hero, (180,500))
# 可以在所有绘制工作完成之后统一调用update方法
pygame.display.update()
# 创建时钟对象
clock = pygame.time.Clock()
# 1.定义rect记录飞机的初始位置
hero_rect = pygame.Rect(150, 300, 102, 126)
# 游戏循环->意味着游戏的正式开始
while True:
    # 可以指定循环体内部的代码执行频率
    clock.tick(60)
    # 监听事件
    event_list = pygame.event.get()
    if len(event_list) > 0:
        print(event_list)
        # 判断飞机的位置
    if hero_rect.y <= 0:
        hero_rect.y = 700
        # 2.修改飞机的位置
    hero_rect.y -= 1
    # 3.调用blit方法绘制图像
    screen.blit(bg, (0, 0))
    screen.blit(hero, hero_rect)
    # 4.调用update方法更新显示
    pygame.display.update()
pygame.quit()

Here Insert Picture Description
MouseMotion mouse is moved, KeyDown is to press the keyboard, KeyUp is to release the keyboard.

Elves and Elf group

I'm not talking about Digimon ah! Two sprites and sprite-based groups are pygame provided, in order to simplify the image is loaded, the change in position of the image rendering function of the development step and the like.
pygame.sprite.Sprite-- image, and to store images of rect position.
pygame.sprite.Group-- object that contains multiple sprites.
Sprite image class has two attributes rect recording image data and position information, update () method of updating the location information.
Elf group class add () method to increase the group spirit; sprites () method returns the sprite list with a; update () method so that all the elves update method is called group; draw () the image group used in the sprite drawn to the Surface rect position.

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

Frame structures

Borrow the dark horse of the picture. The following is the general framework of this game: First game initialization, set the game window, create a game clock, create sprites and elves group. Then set the refresh frame rate for event monitoring, collision detection, update drawn sprites group, updates the screen display, etc. in the game loop.
Here Insert Picture Description
Store a variety of files Wizard:
Here Insert Picture Description
Main program:
Here Insert Picture Description
The final game window is like this, I feel I can play a year.
Here Insert Picture Description

At last

I also found the aircraft battle a small turtle produced a B station, he there are scores, you can pick what weapons, than this more fun, but the program is very complicated, most people can not read, or the dark horse speak carefully Some easy to understand, strongly suggest that you learn Python's go and see.
Code link dark horse: https: //pan.baidu.com/s/1-Lh9dW1haDjnOKjIC3yAXA
extraction code: w36i
code linking small turtles: https: //pan.baidu.com/s/10P6xM1yPQlueO9Xy-boCtg
extraction code: uicm
as can not run, I welcome private letter.

Published 15 original articles · won praise 63 · views 3967

Guess you like

Origin blog.csdn.net/qq_43779324/article/details/104730181