打飛機(jī)

-- coding: utf-8 --

@Time : 2018/8/4 10:11

@Author :Hcy

@Email : 297420160@qq.com

@File : 打飛機(jī).py

@Software : PyCharm

import pygame
from sys import exit
from pygame.locals import *
import random

# 設(shè)置游戲屏幕大小
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 800

# 子彈類
class Bullet(pygame.sprite.Sprite):
    def __init__(self, bullet_img, init_pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = bullet_img
        self.rect = self.image.get_rect()
        self.rect.midbottom = init_pos
        self.speed = 10

    def move(self):
        self.rect.top -= self.speed

# 玩家飛機(jī)類
class Player(pygame.sprite.Sprite):
    def __init__(self, plane_img, player_rect, init_pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = []                                 # 用來存儲玩家飛機(jī)圖片的列表
        for i in range(len(player_rect)):
            self.image.append(plane_img.subsurface(player_rect[i]).convert_alpha())
        self.rect = player_rect[0]                      # 初始化圖片所在的矩形
        self.rect.topleft = init_pos                    # 初始化矩形的左上角坐標(biāo)
        self.speed = 8                                  # 初始化玩家飛機(jī)速度印蔬,這里是一個確定的值
        self.bullets = pygame.sprite.Group()            # 玩家飛機(jī)所發(fā)射的子彈的集合
        self.img_index = 0                              # 玩家飛機(jī)圖片索引
        self.is_hit = False                             # 玩家是否被擊中

    # 發(fā)射子彈
    def shoot(self, bullet_img):
        bullet = Bullet(bullet_img, self.rect.midtop)
        self.bullets.add(bullet)

    # 向上移動茴恰,需要判斷邊界
    def moveUp(self):
        if self.rect.top <= 0:
            self.rect.top = 0
        else:
            self.rect.top -= self.speed

    # 向下移動锦针,需要判斷邊界
    def moveDown(self):
        if self.rect.top >= SCREEN_HEIGHT - self.rect.height:
            self.rect.top = SCREEN_HEIGHT - self.rect.height
        else:
            self.rect.top += self.speed

    # 向左移動,需要判斷邊界
    def moveLeft(self):
        if self.rect.left <= 0:
            self.rect.left = 0
        else:
            self.rect.left -= self.speed

    # 向右移動酣藻,需要判斷邊界
    def moveRight(self):
        if self.rect.left >= SCREEN_WIDTH - self.rect.width:
            self.rect.left = SCREEN_WIDTH - self.rect.width
        else:
            self.rect.left += self.speed

# 敵機(jī)類
class Enemy(pygame.sprite.Sprite):
    def __init__(self, enemy_img, enemy_down_imgs, init_pos):
       pygame.sprite.Sprite.__init__(self)
       self.image = enemy_img
       self.rect = self.image.get_rect()
       self.rect.topleft = init_pos
       self.down_imgs = enemy_down_imgs
       self.speed = 2
       self.down_index = 0

    # 敵機(jī)移動,邊界判斷及刪除在游戲主循環(huán)里處理
    def move(self):
        self.rect.top += self.speed

# 初始化 pygame
pygame.init()

# 設(shè)置游戲界面大小鞋怀、背景圖片及標(biāo)題
# 游戲界面像素大小
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# 游戲界面標(biāo)題
pygame.display.set_caption('飛機(jī)大戰(zhàn)')

# 背景圖
background = pygame.image.load('./image/background.png').convert()

# Game Over 的背景圖
game_over = pygame.image.load('./image/gameover.png')

# 飛機(jī)及子彈圖片集合
plane_img = pygame.image.load('./image/shoot.png')

# 設(shè)置玩家飛機(jī)不同狀態(tài)的圖片列表屋休,多張圖片展示為動畫效果
player_rect = []
player_rect.append(pygame.Rect(0, 99, 102, 126))        # 玩家飛機(jī)圖片
player_rect.append(pygame.Rect(165, 360, 102, 126))
player_rect.append(pygame.Rect(165, 234, 102, 126))     # 玩家爆炸圖片
player_rect.append(pygame.Rect(330, 624, 102, 126))
player_rect.append(pygame.Rect(330, 498, 102, 126))
player_rect.append(pygame.Rect(432, 624, 102, 126))
player_pos = [200, 600]
player = Player(plane_img, player_rect, player_pos)

# 子彈圖片
bullet_rect = pygame.Rect(1004, 987, 9, 21)
bullet_img = plane_img.subsurface(bullet_rect)

# 敵機(jī)不同狀態(tài)的圖片列表,多張圖片展示為動畫效果
enemy1_rect = pygame.Rect(534, 612, 57, 43)
enemy1_img = plane_img.subsurface(enemy1_rect)
enemy1_down_imgs = []
enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(267, 347, 57, 43)))
enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(873, 697, 57, 43)))
enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(267, 296, 57, 43)))
enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(930, 697, 57, 43)))

#存儲敵機(jī)梆惯,管理多個對象
enemies1 = pygame.sprite.Group()

# 存儲被擊毀的飛機(jī)酱鸭,用來渲染擊毀動畫
enemies_down = pygame.sprite.Group()

# 初始化射擊及敵機(jī)移動頻率
shoot_frequency = 0
enemy_frequency = 0

# 玩家飛機(jī)被擊中后的效果處理
player_down_index = 16

# 初始化分?jǐn)?shù)
score = 0

# 游戲循環(huán)幀率設(shè)置
clock = pygame.time.Clock()

# 判斷游戲循環(huán)退出的參數(shù)
running = True

# 游戲主循環(huán)
while running:
    # 控制游戲最大幀率為 60
    clock.tick(60)

    # 生成子彈,需要控制發(fā)射頻率
    # 首先判斷玩家飛機(jī)沒有被擊中
    if not player.is_hit:
        if shoot_frequency % 15 == 0:
            player.shoot(bullet_img)
        shoot_frequency += 1
        if shoot_frequency >= 15:
            shoot_frequency = 0

    # 生成敵機(jī)垛吗,需要控制生成頻率
    if enemy_frequency % 50 == 0:
        enemy1_pos = [random.randint(0, SCREEN_WIDTH - enemy1_rect.width), 0]
        enemy1 = Enemy(enemy1_img, enemy1_down_imgs, enemy1_pos)
        enemies1.add(enemy1)
    enemy_frequency += 1
    if enemy_frequency >= 100:
        enemy_frequency = 0

    for bullet in player.bullets:
        # 以固定速度移動子彈
        bullet.move()
        # 移動出屏幕后刪除子彈
        if bullet.rect.bottom < 0:
            player.bullets.remove(bullet)

    for enemy in enemies1:
        #2. 移動敵機(jī)
        enemy.move()
        #3. 敵機(jī)與玩家飛機(jī)碰撞效果處理
        if pygame.sprite.collide_circle(enemy, player):
            enemies_down.add(enemy)
            enemies1.remove(enemy)
            player.is_hit = True
            break
        #4. 移動出屏幕后刪除飛機(jī)
        if enemy.rect.top < 0:
            enemies1.remove(enemy)

    #敵機(jī)被子彈擊中效果處理
    # 將被擊中的敵機(jī)對象添加到擊毀敵機(jī) Group 中凹髓,用來渲染擊毀動畫
    enemies1_down = pygame.sprite.groupcollide(enemies1, player.bullets, 1, 1)
    for enemy_down in enemies1_down:
        enemies_down.add(enemy_down)

    # 繪制背景
    screen.fill(0)
    screen.blit(background, (0, 0))

    # 繪制玩家飛機(jī)
    if not player.is_hit:
        screen.blit(player.image[player.img_index], player.rect)
        # 更換圖片索引使飛機(jī)有動畫效果
        player.img_index = shoot_frequency // 8
    else:
        # 玩家飛機(jī)被擊中后的效果處理
        player.img_index = player_down_index // 8
        screen.blit(player.image[player.img_index], player.rect)
        player_down_index += 1
        if player_down_index > 47:
            # 擊中效果處理完成后游戲結(jié)束
            running = False

    # 敵機(jī)被子彈擊中效果顯示
    for enemy_down in enemies_down:
        if enemy_down.down_index == 0:
            pass
        if enemy_down.down_index > 7:
            enemies_down.remove(enemy_down)
            score += 1000
            continue
        screen.blit(enemy_down.down_imgs[enemy_down.down_index // 2], enemy_down.rect)
        enemy_down.down_index += 1

    # 顯示子彈
    player.bullets.draw(screen)
    # 顯示敵機(jī)
    enemies1.draw(screen)

    # 繪制得分
    score_font = pygame.font.Font(None, 36)
    score_text = score_font.render(str(score), True, (128, 128, 128))
    text_rect = score_text.get_rect()
    text_rect.topleft = [10, 10]
    screen.blit(score_text, text_rect)

    # 更新屏幕
    pygame.display.update()

    # 處理游戲退出
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    # 獲取鍵盤事件(上下左右按鍵)
    key_pressed = pygame.key.get_pressed()

    # 處理鍵盤事件(移動飛機(jī)的位置)
    if key_pressed[K_w] or key_pressed[K_UP]:
        player.moveUp()
    if key_pressed[K_s] or key_pressed[K_DOWN]:
        player.moveDown()
    if key_pressed[K_a] or key_pressed[K_LEFT]:
        player.moveLeft()
    if key_pressed[K_d] or key_pressed[K_RIGHT]:
        player.moveRight()

# 游戲 Game Over 后顯示最終得分
font = pygame.font.Font(None, 48)
text = font.render('Score: '+ str(score), True, (255, 0, 0))
text_rect = text.get_rect()
text_rect.centerx = screen.get_rect().centerx
text_rect.centery = screen.get_rect().centery + 24
screen.blit(game_over, (0, 0))
screen.blit(text, text_rect)

# 顯示得分并處理游戲退出
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
    pygame.display.update()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市怯屉,隨后出現(xiàn)的幾起案子蔚舀,更是在濱河造成了極大的恐慌,老刑警劉巖锨络,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赌躺,死亡現(xiàn)場離奇詭異,居然都是意外死亡羡儿,警方通過查閱死者的電腦和手機(jī)礼患,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來掠归,“玉大人缅叠,你說我怎么就攤上這事》鞯剑” “怎么了痪署?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長兄旬。 經(jīng)常有香客問我狼犯,道長,這世上最難降的妖魔是什么领铐? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任悯森,我火速辦了婚禮,結(jié)果婚禮上绪撵,老公的妹妹穿的比我還像新娘瓢姻。我一直安慰自己,他們只是感情好音诈,可當(dāng)我...
    茶點故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布幻碱。 她就那樣靜靜地躺著绎狭,像睡著了一般。 火紅的嫁衣襯著肌膚如雪褥傍。 梳的紋絲不亂的頭發(fā)上儡嘶,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天,我揣著相機(jī)與錄音恍风,去河邊找鬼蹦狂。 笑死,一個胖子當(dāng)著我的面吹牛朋贬,可吹牛的內(nèi)容都是我干的凯楔。 我是一名探鬼主播,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼锦募,長吁一口氣:“原來是場噩夢啊……” “哼摆屯!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起糠亩,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤鸥拧,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后削解,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡沟娱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年氛驮,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片济似。...
    茶點故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡矫废,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出砰蠢,到底是詐尸還是另有隱情蓖扑,我是刑警寧澤,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布台舱,位于F島的核電站律杠,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏竞惋。R本人自食惡果不足惜柜去,卻給世界環(huán)境...
    茶點故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望拆宛。 院中可真熱鬧嗓奢,春花似錦、人聲如沸浑厚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至物蝙,卻和暖如春炎滞,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背茬末。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工厂榛, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人丽惭。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓击奶,卻偏偏與公主長得像,于是被迫代替她去往敵國和親责掏。 傳聞我的和親對象是個殘疾皇子柜砾,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容