2020/12/12練習

Turing's Cat發表於2020-12-12

1程式碼:


import pygame
from pygame.sprite import Sprite


def update(self):
    self.x += (self.setting.spaceship_speed * self.setting.fleet_direction)
    self.rect.x = self.x
def update(self):
    if self.mv_right and self.rect.right < self.screen_rect.right:  # 小飛機的有邊框小於整個頁面的有邊框
        self.center += self.setting.plane_speed  # settings中的屬性
    if self.mv_left and self.rect.left > 0:  # 小飛機的左邊框大於0
        self.center -= self.setting.plane_speed
        self.rect.centerx = self.center
class Plane:
    def __init__(self, screen, setting):
        super().__init__()
        self.screen = screen
        self.setting = setting
        self.img_plane = pygame.image.load("./imgs/plane.png")
        self.rect = self.img_plane.get_rect()  # 得到小飛機的的矩形區域
        self.screen_rect = self.screen.get_rect()  # 得到screen的矩形區域
        # print(self.screen_rect)
        self.rect.centerx = self.screen_rect.centerx  # 水平居中
        self.rect.bottom = self.screen_rect.bottom  # 底部
        self.center = float(self.rect.centerx)
        self.mv_right = False
        self.mv_left = False

def blitme(self):
    self.screen.blit(self.img_plane, self.rect)

def center_plane(self):
    self.center - self.screen_rect.centerx

class Bullet(Sprite):  # 繼承pygame.sprite中的Sprite類
    def __init__(self, setting, screen, plane):
        super().__init__()
        self.screen = screen
        # 在(0,0)處建立一個表示子彈的矩形
        # pygame.Rect
        # 用於儲存直角座標的pygame物件
        self.rect = pygame.Rect(0,0, setting.bullet_width, setting.bullet_height)
        # 設定顯示的位置
        self.rect.centerx = plane.rect.centerx
        self.rect.top = plane.rect.top
        self.y = float(self.rect.y)
        self.speed = setting.bullet_speed

    def update(self):
        # 向上移動子彈
        self.y -= self.speed
        # 根據self.y的值更新self.rect.y
        self.rect.y = self.y

    def draw_bullet(self):
        """繪製子彈"""
        # pygame.draw.rect()畫一個矩形的形狀
        pygame.draw.rect(self.screen, self.color, self.rect)

class Spaceship(Sprite):
    def __init__(self, setting, screen):
        super().__init__()
        self.screen = screen
        self.setting = setting
        self.img = pygame.image.load("./imgs/enemy.png")
        self.rect = self.img.get_rect()
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height
        self.rect.w = self.rect.width
        self.rect.h = int(self.rect.height / 2) # 將高度設定為一半
        self.x = float(self.rect.x)

    def blitme(self):
        self.screen.blit(self.img, self.rect)

    def check_edges(self):
        screen_rect = self.screen.get_rect()
        if self.rect.right >= screen_rect.right:
            return True
        elif self.rect.left <= 0:
            return True

相關文章