Fight Aliens 飞船发射子弹初级版

有了飞船,我们要发射子弹,不然如何保护我们的领地呢?我们在AlienGame目录下新建bullet.py文件,即子弹的模块
代码如下: 
# -*- coding: utf-8 -*-
# 作者: guos
# 日期: 2023/3/29
import pygame

class Bullet:
    """
        表示子弹的类
    """
    def __init__(self, screen, gc, ship):
        # fill(color, rect)
        self.color = (0, 0, 0)  # 子弹的颜色
        # Rect(left, top, width, height), left -> x轴; top -> y轴; width -> 宽度; height -> 高度;
        self.rect = pygame.Rect(0, 0, 3, 15)  # 表示子弹矩形位置 和大小

        # 设置子弹的位置,子弹的x和y和飞船保持一致
        self.rect.centerx = ship.rect.centerx
        self.rect.centery = ship.rect.centery


        self.screen = screen
        self.gc = gc


    def draw_bullet(self):
        """
            在屏幕中绘制子弹
        :return:
        """
        self.screen.fill(self.color, self.rect)


    def update(self):
        """
            更新子弹的位置,实现飞出去的效果
        :return:
        """
        self.rect.y -= 1

相应的 main.py文件代码更新如下:

# -*- coding: utf-8 -*-
# 作者: guos
# 日期: 2023/3/29


# 游戏的主文件,使用该文件来启动游戏
import pygame
import sys
import time

from game_config import GameConfig
from ship import Ship
from bullet import Bullet


# 创建配置对象
gc = GameConfig()


# 初始化
pygame.init()
# 设置窗口大小
screen = pygame.display.set_mode(gc.size)
# 设置窗口的标题
pygame.display.set_caption(gc.title)


# 创建一个飞船实例对象
ship = Ship(screen, gc)


#  弹夹 -- 存放子弹的列表
bullets = []

# 创建主循环
while True:
    # 处理事件
    for event in pygame.event.get():
        # 处理退出的事件
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            # 键盘按下
            if event.key == pygame.K_LEFT:
                # 向左移动,设置飞船的移动方向,而不是控制飞船移动 -1
                # 这里把这个方向 放入到 配置对象里
                gc.ship_dir = -1
            elif event.key == pygame.K_RIGHT:
                # 向右移动 1
                gc.ship_dir = 1
            elif event.key == pygame.K_SPACE:
                # 当我们按下空格键后创建,并append到弹夹中
                # 创建子弹实例对象
                bullets.append(Bullet(screen, gc, ship))
        elif event.type == pygame.KEYUP:
            # 何时将 ship_dir 设置为0
            # 当键盘松开,如果此时为向左移动或者向右移动时
            if gc.ship_dir == 1 and event.key == pygame.K_RIGHT or gc.ship_dir == -1 and event.key == pygame.K_LEFT:
                gc.ship_dir = 0


    # 设置窗口背景颜色, rgb值
    screen.fill(gc.bg_color)


    # 更新飞船的位置 必须在显示之前
    ship.update()


    # 遍历弹夹实现子弹无限发射,而不是按一下发一个
    for bl in bullets:
        # 更新子弹的位置
        bl.update()
        # 子弹显示 子弹在飞船后面展示会显示在飞船上面,如果想在飞船下面,先展示子弹
        bl.draw_bullet()

    # 飞船显示
    ship.blit_ship()

    # 对窗口进行重绘
    pygame.display.flip()

 

posted @ 2023-03-29 17:06  以赛亚  阅读(14)  评论(0编辑  收藏  举报