Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of simple aircraft Battle realized by 200Lines of Pygame Library Code

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail the example analysis about the realization of simple aircraft war in Pygame library. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Write at the beginning, because this Mini Game experiment is mainly to help me familiarize myself with the use of the pygame library, so there may be some imperfections in the game, please forgive me.

Introduction to installation and use of Library pygame

Pygame is a cross-platform python module designed for video games, including images and sounds. Based on SDL, it allows real-time video game development without being bound by low-level languages, and developers can focus on the game architecture.

Introduction of main modules in pgame

(1) pygame

The pygame module automatically imports other pygame-related modules.

The pygame module includes a surface function that returns a new surface object. The init () function is the core of the pygame game and must be called before entering the game's main loop. Init () initializes all other modules automatically.

(2) pygame.locals

Include names (variables) used in your own module scope. Includes the names of event types, keys, video modes, and so on.

(3) pygame.display

Includes functions that deal with the way pygame is displayed. Including normal window and full screen mode. Some common methods in pygame.display are as follows:

Flip: update the display.

Update: use update when updating parts.

Set_mode: sets the type and size of the display.

Set_caption: sets the title of the pygame program.

Get_surface: returns a surface object that can be used for drawing before calling flip and blit.

(4) pygame.font

Includes the font function to represent different fonts.

(5) pygame.sprite

Game wizard, Group is used as a container for sprite objects. Calling the update object of the group object automatically calls the update method of all sprite objects.

(6) pygame.mouse

Hide the mouse cursor and get the mouse position.

(7) pygame.event

Track events such as mouse clicks, keystrokes, and releases.

(8) pygame.image

Used to process images saved in GIF, PNG, or JPEG files.

Note: except for local module and font module, other modules are involved in the program.

Installation of pygame

You can choose to use the python packages search pygame below the toolbar in pycharm to install, or you can use the pip install pygame method commonly used in the cmd command.

Installation timeout network speed is slow, direct timeout, you can specify a domestic source image.

Pip install-I domestic image address packet name

For example: pip install-I https://mirrors.aliyun.com/pypi/simple/ numpy

Domestic commonly used source image address:

Tsinghua: https://pypi.tuna.tsinghua.edu.cn/simple

Ali Yun: http://mirrors.aliyun.com/pypi/simple/

University of Science and Technology of China: https://pypi.mirrors.ustc.edu.cn/simple/

Douban: http://pypi.douban.com/simple/

Verify installation

To verify that pygame is installed successfully, use the pip list statement in the cmd command. If the installation is successful, we can find it in the results below.

Program principle

First of all, create the main form of the game, the size of the main form is the size of your background picture.

Import pygame# game initialization pygame.init () # create game main window screen = pygame.display.set_mode ((480700)) # draw background image incense # 1 load image data background = pygame.image.load ('. / image/background.png') # 2 blit draw image # draw screen.blit (background, (0)) pygame.display.update () # unload all modules pygame.quit ()

When drawing the direction of the image, we need to pay attention to the direction of the mainframe, the enemy plane, the background and the direction of the bullet.

After the background image is drawn, we can draw our mainframe and enemy aircraft. We can call the update method after all the drawing work is completed.

# draw an airplane picture hero = pygame.image.load ('. / image/hero2.png') screen.blit (hero, (150300)) pygame.display.update ()

In fact, the principle of the aircraft war is the same as that of cartoons. We need to respond to the instructions pressed one by one to form a coherent picture. Here we need to use the time module in the pygame library.

# create clock object screen drawing rate clock = pygame.time.Clock () # Game Loop while True: # specify the execution frequency of the internal code of the loop body 60 times per second clock.tick (60) # will move the aircraft before occlusion to achieve animation screen.blit (background, (0,0) screen.blit (hero,hero_rect))

If you want to stop the program, you will find that clicking the close in the upper right corner of the form does not respond, because you have not yet listened to the event in the loop, and then judge the time

Event_list = pygame.event.get () for event in event_list: # determine whether it is an exit event if event.type = = pygame.QUIT: print ("quit the game...") # Uninstall all modules pygame.quit () exit ()

With regard to the generation of enemy aircraft, we need to use the sprite wizard and the elf group module to create two identical enemy planes, but the flight speed of the enemy aircraft is different, and then add the enemy plane sprites to the enemy aircraft elf group, and then we can continue to draw the enemy plane elf group in the loop.

Enemy = GameSprite (". / image/enemy0.png") enemy1 = GameSprite (". / image/enemy0.png", 2) enemy_group = pygame.sprite.Group (enemy,enemy1) # Sprite group call method enemy_group.update () enemy_group.draw (screen)

Sort out and simplify some of the above code, and finally we can get such an effect diagram that both the host and the enemy aircraft can move.

Import pygamefrom plane_sprites import * # Game initialization pygame.init () # create game main window screen = pygame.display.set_mode ((480700)) # draw background image Xiang # 1 load image data background = pygame.image.load ('. / image/background.png') # 2 blit draw image # draw screen.blit from the upper left corner (background (0recover0)) # 3 update update screen display # pygame.display.update () # drawing airplane pictures hero = pygame.image.load ('. / image/hero2.png') screen.blit (hero, (150300)) # after all the drawing work is completed Uniformly call update method pygame.display.update () # create clock object screen drawing rate clock = pygame.time.Clock () # define aircraft initial position hero_rect = pygame.Rect (150300100122) # enemy wizard create enemy = GameSprite (". / image/enemy0.png") enemy1 = GameSprite (". / image/enemy0.png", 2) enemy_group = pygame.sprite.Group (enemy Enemy1) # Game Loop while True: # specify the execution frequency of the code inside the loop body 60 times per second clock.tick (60) # listening time event_list = pygame.event.get () # if len (event_list) > 0: # print (event_list) for event in event_list: # determine yes No for the exit event if event.type = = pygame.QUIT: print ("quit the game...") # Uninstall all modules pygame.quit () exit () hero_rect.y-= 1 if hero_rect.y = SCREEN_RECT.height: self.rect.y =-self.rect.heightclass Enemy (GameSprite): # enemy wizard def _ _ init__ (self): # 1 call parent method to create enemy wizard super (). _ init__ (". / image/enemy0.png") # 2 refers to Self.speed = random.randint (1) # 3 specify the initial random position of the enemy aircraft self.rect.bottom = 0 max_x = SCREEN_RECT.width-self.rect.width self.rect.x = random.randint (0 Max_x) def update (self): #! Call the parent method to fly vertically super (). Update () # 2 to determine whether to fly off the screen. If so, you need to remove if self.rect.y from the spirit group > = SCREEN_RECT.height: print ("fly off the screen Need to remove from the spirit group. ") # kill method can remove the wizard from the elf family, and the wizard automatically destroys self.kill () def _ _ del__ (self): print (" enemy plane death% s "% self.rect) host class and bullet class.

SCREEN_RECT.centerx is used to ensure that the host is initially in the middle of the screen, and the y about the host should subtract part of the distance from the SCREEN_RECT.bottom of the screen because it draws a diagram at the beginning.

In the same way as the enemy plane, the bullet class needs to judge whether to fly out of the screen range. If the bullet is removed from the spirit group by using the kill () method, the initial position of the bullet should be above the host, that is, the x of the bullet is equal to the x of the host.

# protagonist plane class Hero (GameSprite): def _ _ init__ (self): # call parent class to set hero image and speed super (). _ _ init__ (". / image/hero2.png" 0) # set host position self.rect.centerx = SCREEN_RECT.centerx self.rect.bottom = SCREEN_RECT.bottom-50 # bullet wizard group self.bullet_group = pygame.sprite.Group () def update (self): # move horizontally Self.rect.x + = self.speed # Control hero cannot be 0 if self.rect.x

< 0: self.rect.x =0 elif self.rect.right >

SCREEN_RECT.right: self.rect.right = SCREEN_RECT.right # bullet firing def fire (self): print ("firing bullet...") # create bullet wizard bullet = Bullet () # set bullet position bullet .bullet .bottom = self.rect.y-20 bullet.rect.centerx = self.rect.centerx # add to the bullet wizard group self.bullet_group.add (bullet) # bullet class Bullet (GameSprite): def _ _ init__ (self): # call the parent method to set the bullet image speed Super (). _ _ init__ (". / image/bullet1.png" -2) def update (self): # call the parent method to make the bullet fly vertically super (). Update () # to determine whether the bullet flew out of if self.rect.bottom

< 0: self.kill() def __del__(self): print("子弹被销毁")主游戏类 在主类中进行精灵组的创建,背景精灵组的创建是为了达到背景滚动的效果 #精灵组的创建def __create_sprites(self): #创建背景精灵和精灵1组 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 __init__(self): print("游戏初始化") #创建游戏窗口 self.screen = pygame.display.set_mode(SCREEN_RECT.size) #创建游戏时钟 self.clock = pygame.time.Clock() self.__create_sprites() #敌机生成和主机开火的定时器 pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)#单位是ms pygame.time.set_timer(HERO_FIRE_EVENT,500)事件监听方法 关于事件的监听过程中,需要对敌机生成和子弹飞行、主机移动指令做出对应反应 def __event_handler(self): for event in pygame.event.get(): if event.type == pygame.QUIT: PlaneGame.__game_over() elif event.type == CREATE_ENEMY_EVENT: print("敌机生成...") #创建敌机精灵 enemy = Enemy() #敌机精灵加入精灵组 self.enemy_group.add(enemy) elif event.type == HERO_FIRE_EVENT: print("发射子弹...") self.hero.fire() #飞机移动 keyss_pressed = pygame.key.get_pressed() if keyss_pressed[pygame.K_RIGHT]: print("向右移动") self.hero.speed = 2 elif keyss_pressed[pygame.K_LEFT]: print("向左移动") self.hero.speed = -2 else: self.hero.speed = 0碰撞检测 对于子弹碰撞敌机和敌机碰撞主机的情况进行判定 #碰撞检测def __check_collide(self): #子弹摧毁敌机 pygame.sprite.groupcollide(self.hero.bullet_group,self.enemy_group,True,True) #敌机撞毁英雄 enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True) if len(enemies) >

0: self.hero.kill () PlaneGame.__game_over () Sprite Group Update display # Sprite Update display def _ _ update_sprites (self): # background Sprite Group self.back_group.update () self.back_group.draw (self.screen) # enemy Sprite Group self.enemy_group.update () Self.enemy_group.draw (self.screen) # host wizard group self.hero_group.update () self.hero_group.draw (self.screen) # bullet wizard group self.hero.bullet_group.update () self.hero.bullet_group.draw (self.screen)

The beginning and end of the game

Def start_game (self): print ("Game begins...") While True: # 1 set refresh frame rate self.clock.tick (SCREEN_PER_SEC) # 2 time monitor self.__event_handler () # 3 collision detection self.__check_collide () # 4 update enemy aircraft Self.__update_sprites () # 5 updates show pygame.display.update () @ staticmethoddef _ _ game_over (): print ("game over") pygame.quit () exit () example analysis of the Pygame library's 200 lines of code to implement a simple aircraft battle is here. I hope the above content can be of some help to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report