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.
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
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
Develop small games
1. Material preparation
First of all, let’s preview the final running interface of the game
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:
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()
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:
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()
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!