World War II airplane notes programmers dark horse

World War II Aircraft

Foreword

Recently, a friend exhortations by doing a simple little game, this white for a long time have not touched this stuff, and want to know the new need to ponder, then writing on this blog, I just use the blog to record their learning experiences, lower level.
A long time ago, I watched instructional videos python programmers dark horse in the b station, which is not a small space and detailed explanation of the game using the pygame library to do an aircraft of World War II. But just muddle along with the code, there are many things worth to summarize, so this blog a dark horse source , the dark horse share of aircraft material and notes composition.
Turning to the dark horse, his department video very basic, detailed, as he said: understand Chinese can learn. Interested python language students do not know how to start, can be considered to see twelve sets.

The first step: running order

    def start_game(self):
       print("游戏开始...")
       while True:
           #1.刷新频率
           self.clock.tick(FRAME_PER_SEC)
           #2.事件监听
           self.__event_handler()
           #3.碰撞检测
           self.__check_collide()
           #4.更新/绘制精灵
           self.__updata_sprites()
           #5.更新检测
           pygame.display.update()

The program is mainly applied to the library: pygame (core)
after the game to run the program directly, set the refresh rate, the event listener (if there is press the key pressed down), collision detection (enemy planes with the machine, bullets with the enemy) , rendering image (according to the previous step, determining the position of the field bullet, bullet, and the machine draw), full update (e.g., approaching enemy aircraft, bullet front row).

Step two: the game window

The game window is created:

    SCREEN_RECT = pygame.Rect(0,0,480,720)
    self.screen = pygame.display.set_mode(SCREEN_RECT.size)   #常量 > 700

The next screen will be carried on all of the main elements, and the player should leave the reaction space, the optimal rectangle.
Here pygame.Rect applied to the class, passing parameters (left, top, width, height ), then passed set_mode function belongs Rect class, called size SCREEN_RECT object: (480, 720). So a 480 wide, 720 long game window will be created.

The third step: the enemy Wizard

World War II aircraft similar to lightning, in this game, the position of the enemy appeared, the number of flight speed and appearance are random.
Here to use the pygame library Elves and Elf group (class) concept: https: //blog.csdn.net/houyanhua1/article/details/84193317. In this class, the more important are image, rect, the most critical is also the most commonly used is the update member functions, we often due to their own needs to rewrite the function.

	class GameSprite(pygame.sprite.Sprite):  #(继承父类) 其中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, *args):    #*args 一定保留
	        #屏幕上垂直移动
	        self.rect.y += self.speed

Create a sprite class that inherits from pygame.sprite.Sprite, add initialization function content, written to load img, set the rect content. updata function is used to update the status, e.g. enemy bullets forward.

	class Enemy(GameSprite):
	    def __init__(self):
	        #调用父类 指定图片
	        super().__init__("./image/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(0,max_x)

	    def update(self, *args):
	        super().update()
	        #若敌机飞出游戏屏幕
	        if self.rect.y >= SCREEN_RECT.height:
	            #将精灵从所有的组移出  并被del调用
	            self.kill()
	            #print("飞出了屏幕")

Enemy sprite class inherits class defines several properties in the initialization. In addition, when the top-down enemy planes flying out of the game screen, you need to destroy a heavy burden increase indefinitely enemy will give computer.
There is a new problem: the enemy after a call enemy1.update update the drawing when () will have a displacement of data, but the actual situation, the number of games in the enemy often a lot, do not require a call to member function?
Pygame group using sprites, and defines timing generation event listener enemy, the enemy will generate a sprite group into which, when the need to draw, to update the group of sprites.

	#创建敌机的定时器常量
	CREATE_ENEMY_EVENT = pygame.USEREVENT  #用户事件的常量
	pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)  #时间一到,触发名叫CREAT_ENEMY_EVENT的事件
	
	#事件监听
	for event in pygame.event.get():
	    if event.type == CREATE_ENEMY_EVENT:
               #创建敌机精灵
               enemy = Enemy()
               #添加到精灵组
               self.enemy_group.add(enemy)
    
    #更新并绘制敌机精灵组
    def __updata_sprites(self):
    	#精灵组调用update
	    self.enemy_group.update()
    	self.enemy_group.draw(self.screen)

Step four: Dynamic Background

In the absence of the key pressed the press when the machine is stationary, in order to create visual effects fly using dynamic background paddling practice. FIG connected to the same two vertical, continued downward displacement, the initial cycle.
Continued moving, loading pictures, with length and width property, which is not exactly their own definition of class and GameSprite like like? By the same token, the machine, the bullets have similar properties, we need only to extend and rewrite the like.

	class Background(GameSprite):
    	"""游戏背景精灵"""
	    def __init__(self,is_alt=False):
	        #调用父类方法
	        super().__init__("./image/background.png")   #传入背景图片
	        #判断图像
	        if is_alt:
	            self.rect.y = -self.rect.height
	    def update(self, *args):
	        #1.调用父类的更新,默认速度为1
	        super().update()
	        #2.判断是否移出屏幕
	        if self.rect.y >= SCREEN_RECT.height:
	            self.rect.y = -self.rect.height
    
	def __create_sprites(self):
	        #背景精灵组
	        bg1 = Background()
	        bg2 = Background(1)
	        self.back_group = pygame.sprite.Group(bg1,bg2)
	
	#更新并绘制
    self.back_group.update()
    self.back_group.draw(self.screen)
Released three original articles · won praise 0 · Views 220

Guess you like

Origin blog.csdn.net/chunqingzhanna/article/details/104082945