Pygame基础9-射击

简介: Pygame基础9-射击

简介

玩家用鼠标控制飞机(白色方块)移动,按下鼠标后,玩家所在位置出现子弹,子弹匀速向右飞行。

代码

没有什么新的东西,使用两个精灵类表示玩家和子弹

有一个细节需要注意,当子弹飞出屏幕时,要将子弹清除(kill)。(否则虽然看不见子弹了,但是子弹还是(一直)存在,会占用内存。

import pygame
import sys

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill((255, 255, 255))
        self.rect = self.image.get_rect(center = (screen_size[0]//2, screen_size[1]//2))
    def update(self):
        self.rect.center = pygame.mouse.get_pos()
    def shoot(self):
        return Bullet(self.rect.centerx, self.rect.centery)
        

class Bullet(pygame.sprite.Sprite):
    def __init__(self,pos_x, pos_y):
        super().__init__()
        self.image = pygame.Surface((50, 10))
        self.image.fill((255, 0, 0))
        self.rect = self.image.get_rect(center = (pos_x, pos_y))
        self.speed = 5
    def update(self):
        self.rect.x += self.speed
        # 如果子弹超出屏幕,就删除。否则子弹会(在屏幕外)一直存在。
        if self.rect.right > screen_size[0] + 20:
            self.kill()

# 初始化
pygame.init()
screen_size = (800, 600)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("Pygame Demo")
clock = pygame.time.Clock()

pygame.mouse.set_visible(False)

player = Player()
player_group = pygame.sprite.Group()
player_group.add(player)

bullet_group = pygame.sprite.Group()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            bullet = player.shoot()
            bullet_group.add(bullet)

    # update
    # draw
    screen.fill((0, 0, 0))   
    # 先画子弹,再画玩家,否则玩家会被子弹挡住。
    bullet_group.update()
    bullet_group.draw(screen)
    
    player_group.update()
    player_group.draw(screen)
    
    pygame.display.flip()
    clock.tick(60)


相关文章
|
1月前
|
Python
pygame之五子棋的实现
pygame之五子棋的实现
|
12天前
|
Python
使用Pygame做一个乒乓球游戏(2)使用精灵重构
使用Pygame做一个乒乓球游戏(2)使用精灵重构
|
12天前
|
Python
使用Pygame做一个乒乓球游戏
使用Pygame做一个乒乓球游戏
|
12天前
|
Python
Pygame基础3-动画
Pygame基础3-动画
|
1月前
|
Python
pygame 烟花效果
pygame 烟花效果
31 0
|
10月前
|
Python
pygame编写井字棋游戏
pygame编写井字棋游戏
152 0
|
Python
python及pygame雷霆战机游戏项目实战13 子弹增强
python及pygame雷霆战机游戏项目实战13 子弹增强
117 0
|
Python
python及pygame雷霆战机游戏项目实战03 碰撞检测
python及pygame雷霆战机游戏项目实战03 碰撞检测
147 0
|
Python
python及pygame雷霆战机游戏项目实战02 敌人精灵
python及pygame雷霆战机游戏项目实战02 敌人精灵
90 0
|
Python
python及pygame雷霆战机游戏项目实战06 更多类型的敌机
python及pygame雷霆战机游戏项目实战06 更多类型的敌机
106 0