1. 程式人生 > >python pygame實戰《飛船大戰外星人》

python pygame實戰《飛船大戰外星人》

學了一個月的python,最後兩天學了下pygame,以一個小遊戲結尾這段旅程。

遊戲規則如下:

玩家可以通過上下左右四個鍵控制飛船移動,而且按住鍵不放可以聯絡移動,而不需要不斷地按鍵鬆鍵來控制。

玩家可以按空格鍵發射子彈,每按一次發射一顆,可以連續發射10顆子彈。只要子彈觸碰到外星人,就贏了。子彈數量也可以增加,不過目前還想不到可以無限多子彈的方法,只想到了計算出當子彈遍佈整個介面時候的子彈數目,然後設定出來,多copy幾次程式碼。但這樣並不是最好的方法。

由於時間緊,只設置了一個外星人,而且擊落這一個就贏了。如果沒有,飛船觸碰到外星人或者外星人到了介面底部,那麼就輸了。這個遊戲以後還可以改進成有多個外星人。外星人的移動軌跡是先右下到碰壁反彈,再左下再碰壁再回來。

最後介面上會有輸贏的文字提示。

tips:本文程式碼基於python3.5,最後點選遊戲螢幕就可以退出遊戲

        本文程式碼比較長,自己只寫了一個模組,這樣子邏輯很清晰,整體感也比較強,也不用變數引用來引用去。缺點是缺乏介面導致排查bug會難一點,以及程式碼相對不簡潔。

用到的圖片在文末,供下載。使用時路徑要自己設定。

字型我用到了simkai,ttf的系統字型,也就是楷體。不同電腦可能配置不一樣。

import sys
import pygame
from pygame import locals
import time
import decide#自己寫的一個模組,如果要使用必須將本模組和這個模組放在同一個資料夾裡

def run_game():
    pygame.init()#初始化
    scr=pygame.display.set_mode((1366,768),locals.FULLSCREEN)#第一個引數是解析度,第二個是設定成全屏模式,
    pygame.display.set_caption('飛船大戰外星人')#標題
    
    craft_image=pygame.image.load('d://python//pygame//craftnew.bmp')#飛船圖片,記得是bmp字尾
    craft_rect=craft_image.get_rect()#得到相應的方框,便於處理,這是pygame很便捷的一個方面
    scr_rect=scr.get_rect()
    craft_rect.centerx=scr_rect.centerx#設定在介面中央
    craft_rect.bottom=scr_rect.bottom#設定在介面底部
    scr.blit(craft_image,craft_rect)#在介面上畫出飛船
    
    moving_right=False#以下均為標誌
    moving_left=False
    moving_down=False
    moving_up=False
    flag1=False
    flag2=False
    flag3=False
    flag3=False
    flag4=False
    flag5=False
    flag6=False
    flag7=False
    flag8=False
    flag9=False
    flag10=False
    flaga=True
    flagr=True
    flagl=False
    a=1
    
    alien_image=pygame.image.load('d://python//pygame//alien1.bmp')#外星人圖片
    alien_rect=alien_image.get_rect()
    alien_rect.centerx=scr_rect.centerx
    alien_rect.top=scr_rect.top
    myfont=pygame.font.SysFont('simkai.ttf',40)#設定最後的輸出字型
    text_surface1=myfont.render('You are successful!',True,(255,0,0),(255,255,255))
    text_surface2=myfont.render('Sorry,but you fail!',True,(255,0,0),(255,255,255))
    
    while True:
        scr.fill((230,230,230))#螢幕背景調成灰色,rgb都不懂的,要百度了
        scr.blit(alien_image,alien_rect)#在介面上畫出外星人
        if flaga==True:
            if a%5==0:#設定外星人每五次之後就下降一個畫素
               alien_rect.bottom +=1
            a +=1
            
            if flagr==True:#這一段程式碼讓外星人先右下再碰壁反彈,再左下再碰壁再回來
                if alien_rect.right<scr_rect.right:
                    alien_rect.centerx +=2
                elif alien_rect.right==scr_rect.right:
                    flagl=True
                    flagr=False
            elif flagl==True:
                if alien_rect.left>scr_rect.left:
                    alien_rect.centerx -=2
                elif alien_rect.left==scr_rect.left:
                    flagl=False
                    flagr=True


        for event in pygame.event.get():#接受玩家對於遊戲的命令
            if event.type==pygame.MOUSEBUTTONDOWN:#最終是點選螢幕就可以退出遊戲
                pygame.quit()
                sys.exit()
            elif event.type==pygame.KEYDOWN:
                if event.key==pygame.K_RIGHT:
                   moving_right=True
                if event.key==pygame.K_LEFT:
                    moving_left=True
                if event.key==pygame.K_DOWN:
                    moving_down=True
                if event.key==pygame.K_UP:
                    moving_up=True
                if event.key==32:#點選空格鍵。這一段程式碼雖然看起來囉囉嗦嗦,但是都是一樣的
                    if flag1==False:
                        bullet_rect1=pygame.Rect(0,0,5,10)
                        bullet_rect1.centerx=craft_rect.centerx
                        bullet_rect1.top=craft_rect.top
                        bullet_color1=(220,20,60)
                        pygame.draw.rect(scr,bullet_color1,bullet_rect1)
                        flag1=True
                    elif flag2==False:
                        bullet_rect2=pygame.Rect(0,0,5,10)
                        bullet_rect2.centerx=craft_rect.centerx
                        bullet_rect2.top=craft_rect.top
                        bullet_color2=(220,20,60)
                        pygame.draw.rect(scr,bullet_color2,bullet_rect2)
                        flag2=True
                    elif flag3==False:
                        bullet_rect3=pygame.Rect(0,0,5,10)
                        bullet_rect3.centerx=craft_rect.centerx
                        bullet_rect3.top=craft_rect.top
                        bullet_color3=(220,20,60)
                        pygame.draw.rect(scr,bullet_color3,bullet_rect3)
                        flag3=True
                    elif flag4==False:
                        bullet_rect4=pygame.Rect(0,0,5,10)
                        bullet_rect4.centerx=craft_rect.centerx
                        bullet_rect4.top=craft_rect.top
                        bullet_color4=(220,20,60)
                        pygame.draw.rect(scr,bullet_color4,bullet_rect4)
                        flag4=True
                    elif flag5==False:
                        bullet_rect5=pygame.Rect(0,0,5,10)
                        bullet_rect5.centerx=craft_rect.centerx
                        bullet_rect5.top=craft_rect.top
                        bullet_color5=(220,20,60)
                        pygame.draw.rect(scr,bullet_color5,bullet_rect5)
                        flag5=True
                    elif flag6==False:
                        bullet_rect6=pygame.Rect(0,0,5,10)
                        bullet_rect6.centerx=craft_rect.centerx
                        bullet_rect6.top=craft_rect.top
                        bullet_color6=(220,20,60)
                        pygame.draw.rect(scr,bullet_color6,bullet_rect6)
                        flag6=True
                    elif flag7==False:
                        bullet_rect7=pygame.Rect(0,0,5,10)
                        bullet_rect7.centerx=craft_rect.centerx
                        bullet_rect7.top=craft_rect.top
                        bullet_color7=(220,20,60)
                        pygame.draw.rect(scr,bullet_color7,bullet_rect7)
                        flag7=True
                    elif flag8==False:
                        bullet_rect8=pygame.Rect(0,0,5,10)
                        bullet_rect8.centerx=craft_rect.centerx
                        bullet_rect8.top=craft_rect.top
                        bullet_color8=(220,20,60)
                        pygame.draw.rect(scr,bullet_color8,bullet_rect8)
                        flag8=True
                    elif flag9==False:
                        bullet_rect9=pygame.Rect(0,0,5,10)
                        bullet_rect9.centerx=craft_rect.centerx
                        bullet_rect9.top=craft_rect.top
                        bullet_color9=(220,20,60)
                        pygame.draw.rect(scr,bullet_color9,bullet_rect9)
                        flag9=True
                    elif flag10==False:
                        bullet_rect10=pygame.Rect(0,0,5,10)
                        bullet_rect10.centerx=craft_rect.centerx
                        bullet_rect10.top=craft_rect.top
                        bullet_color10=(220,20,60)
                        pygame.draw.rect(scr,bullet_color10,bullet_rect10)
                        flag10=True
                    
            elif event.type==pygame.KEYUP:
                
                if event.key==pygame.K_RIGHT:
                    moving_right=False
                if event.key==pygame.K_LEFT:
                    moving_left=False
                if event.key==pygame.K_DOWN:
                    moving_down=False
                if event.key==pygame.K_UP:
                    moving_up=False
                
        if moving_right==True:
            if craft_rect.right>scr_rect.right:
                pass
            else:
                craft_rect.centerx +=5#在這裡可以更改飛船的移動速度
        if moving_left==True:
            if craft_rect.left<scr_rect.left:
                pass
            else:
                craft_rect.centerx -=5
        if moving_down==True:
            if craft_rect.bottom>scr_rect.bottom:
                pass
            else:
                craft_rect.bottom +=5
        if moving_up==True:
            if craft_rect.top<scr_rect.top:
                pass
            else:
                craft_rect.bottom -=5
        scr.blit(craft_image,craft_rect)#畫出飛船
        if flag1==True:
            if decide.d1(bullet_rect1,alien_rect):#如果子彈觸碰到外星人
                flag1=False
                flaga=False
                print('1st')
                scr.blit(text_surface1,(600,350))
                pygame.display.flip()#重新整理螢幕顯示文字
                time.sleep(3)#控制暫停3秒,然後遊戲結束
                pygame.quit()
                sys.exit()
            if bullet_rect1.top>scr_rect.top :#子彈到達介面外部,就消失了,此時就可以發射第11顆子彈了
                bullet_rect1.bottom -=1
                pygame.draw.rect(scr,bullet_color1,bullet_rect1)
            else:
                flag1=False
        if flag2==True:
            if decide.d1(bullet_rect2,alien_rect):
                flag2=False
                flaga=False
                print('2nd')
                scr.blit(text_surface1,(600,350))
                pygame.display.flip()
                time.sleep(3)
                pygame.quit()
                sys.exit()
            if bullet_rect2.top>scr_rect.top:
                bullet_rect2.bottom -=1
                pygame.draw.rect(scr,bullet_color2,bullet_rect2)
            else:
                flag2=False
        if flag3==True:
            if decide.d1(bullet_rect3,alien_rect):
                flaga=False
                scr.blit(text_surface1,(600,350))
                print('3rd')
                pygame.display.flip()
                time.sleep(3)
                pygame.quit()
                sys.exit()
            if bullet_rect3.top>scr_rect.top:
                bullet_rect3.bottom -=1
                pygame.draw.rect(scr,bullet_color3,bullet_rect3)
            else:
                flag3=False
        if flag4==True:
            if decide.d1(bullet_rect4,alien_rect):
                flag4=False
                flaga=False
                print('4th')
                scr.blit(text_surface1,(600,350))
                pygame.display.flip()
                time.sleep(3)
                pygame.quit()
                sys.exit()
            if bullet_rect4.top>scr_rect.top:
                bullet_rect4.bottom -=1
                pygame.draw.rect(scr,bullet_color4,bullet_rect4)
            else:
                flag4=False
        if flag5==True:
            if decide.d1(bullet_rect5,alien_rect):
                flag5=False
                flaga=False
                print('5th')
                scr.blit(text_surface1,(600,350))
                pygame.display.flip()
                time.sleep(3)
                pygame.quit()
                sys.exit()
            if bullet_rect5.top>scr_rect.top:
                bullet_rect5.bottom -=1
                pygame.draw.rect(scr,bullet_color5,bullet_rect5)
            else:
                flag5=False
        if flag6==True:
            if decide.d1(bullet_rect6,alien_rect):
                flag6=False
                flaga=False
                print('6th')
                scr.blit(text_surface1,(600,350))
                pygame.display.flip()
                time.sleep(3)
                pygame.quit()
                sys.exit()
            if bullet_rect6.top>scr_rect.top:
                bullet_rect6.bottom -=1
                pygame.draw.rect(scr,bullet_color6,bullet_rect6)
            else:
                flag6=False
        if flag7==True:
            if decide.d1(bullet_rect7,alien_rect):
                flag7=False
                flaga=False
                print('7th')
                scr.blit(text_surface1,(600,350))
                pygame.display.flip()
                time.sleep(3)
                pygame.quit()
                sys.exit()
            if bullet_rect7.top>scr_rect.top:
                bullet_rect7.bottom -=1
                pygame.draw.rect(scr,bullet_color7,bullet_rect7)
            else:
                flag7=False
        if flag8==True:
            if decide.d1(bullet_rect8,alien_rect):
                flag8=False
                flaga=False
                print('8th')
                scr.blit(text_surface1,(600,350))
                pygame.display.flip()
                time.sleep(3)
                pygame.quit()
                sys.exit()
            if bullet_rect8.top>scr_rect.top:
                bullet_rect8.bottom -=1
                pygame.draw.rect(scr,bullet_color8,bullet_rect8)
            else:
                flag8=False
        if flag9==True:
            if decide.d1(bullet_rect9,alien_rect):
                flag9=False
                flaga=False
                print('9th')
                scr.blit(text_surface1,(600,350))
                pygame.display.flip()
                time.sleep(3)
                pygame.quit()
                sys.exit()
            if bullet_rect9.top>scr_rect.top:
                bullet_rect9.bottom -=1
                pygame.draw.rect(scr,bullet_color9,bullet_rect9)
            else:
                flag9=False
        if flag10==True:
            if decide.d1(bullet_rect10,alien_rect):
                flag10=False
                flaga=False
                print('10th')
                scr.blit(text_surface1,(600,350))
                pygame.display.flip()
                time.sleep(3)
                pygame.quit()
                sys.exit()
            if bullet_rect10.top>scr_rect.top:
                bullet_rect10.bottom -=1
                pygame.draw.rect(scr,bullet_color10,bullet_rect10)
            else:
                flag10=False
        if alien_rect.bottom==scr_rect.bottom or decide.d2(alien_rect,craft_rect):#判斷失敗的兩個條件
            scr.blit(text_surface2,(600,350))
            pygame.display.flip()
            time.sleep(3)
            pygame.quit()
            sys.exit()
        scr.blit(alien_image,alien_rect)
        pygame.display.flip()
        
run_game()

附上效果截圖:



子彈撞到外星人,遊戲勝利


飛船碰到外星人,遊戲失敗


外星人已到達介面底部,遊戲失敗

用到的圖片



醜陋的介面請不要介意哈哈哈。


相關推薦

python pygame實戰飛船大戰外星人

學了一個月的python,最後兩天學了下pygame,以一個小遊戲結尾這段旅程。 遊戲規則如下: 玩家可以通過上下左右四個鍵控制飛船移動,而且按住鍵不放可以聯絡移動,而不需要不斷地按鍵鬆鍵來控制。 玩家可以按空格鍵發射子彈,每按一次發射一顆,可以連續發射10顆子彈。只要子

python-pygame飛機大戰version2

plane_main.py import pygame from plane_sprites import * class PlaneGame(object): def __init__(self): self.screen = pygame.display.s

python-pygame飛機大戰version1

分為兩個檔案,一個為遊戲入口檔案,進行遊戲的初始化,開啟遊戲迴圈 需求分析: 飛機大戰需要做的事情 1,迴圈前的準備 2,迴圈開始 迴圈前的準備: 載入畫布 載入時鐘 載入英雄 迴圈開始: 設定迴圈的幀 __ 設定事件監聽 __event_handler 檢測碰撞 __check_c

《零基礎入門學習Python》第095講:Pygame:飛機大戰6

今天繼續飛機大戰的開發,遊戲每30秒就隨機下放一個補給包,可能是超級子彈或者全屏炸彈。 補給包有自己的圖片(如下圖),也有自己的執行軌跡(由上而下) 因此,我們可以單獨寫一個模組來實現:命名為 supply #supply.py import pygame from random i

《零基礎入門學習Python》第093講:Pygame:飛機大戰4

現在處於敵強我弱的局面:敵人很多,我只要一個,無處可逃。我們就需要武器來反抗: 定義子彈: 子彈有兩種:一種是一次只發射一顆,一種是補給發放的超級子彈,一次可以射2顆子彈。子彈的運動軌跡是直線向上的,速度要略快于飛機的速度,子彈如果超出螢幕範圍的話,我們就重新繪製子彈,飛機在哪裡,子彈就

Python:用Pygame實現飛機大戰小遊戲

2、開啟main.py檔案,寫入程式碼。 # main.py import pygame import sys import traceback import myplane import enemy import bullet imp

python專案實戰:pygame控制鍵盤方向鍵隨意移動

前言 本文為大家介紹一個利用python控制控制鍵盤方向鍵隨意移動,用到python的第三方庫pygame,下面就來看看吧 匯

數學之路-python計算實戰(4)-Lempel-Ziv壓縮(2)

per tex alink header 一次 borde tar 文本文 寫入文件 Format characters have the following meaning; the conversion between C and Python values shou

數學之路-python計算實戰(1)-ubuntu安裝pypy

sudo 安裝過程 zip ima cut popu -o ack sin Get the source code. The following packages contain the source at the same revision as the above b

python 爬蟲實戰4 爬取淘寶MM照片

寫真 換行符 rip 多行 get sts tool -o true 本篇目標 抓取淘寶MM的姓名,頭像,年齡 抓取每一個MM的資料簡介以及寫真圖片 把每一個MM的寫真圖片按照文件夾保存到本地 熟悉文件保存的過程 1.URL的格式 在這裏我們用到的URL是 http:/

2017.08.10 Python爬蟲實戰之爬蟲攻防

ebs 1-1 間隔 ima pic setting fin 數據 del 1.創建一般的爬蟲:一般來說,小於100次訪問的爬蟲都無須為此擔心 (1)以爬取美劇天堂為例,來源網頁:http://www.meijutt.com/new100.html,項目準備: scrapy

2017.08.10 Python爬蟲實戰之爬蟲攻防篇

5.1 inux ice 一個 1.0 ninja 多網站 alt bject 1.封鎖user-agent破解: user-agent是瀏覽器的身份標識,網站就是通過user-agent來確定瀏覽器類型的。有很多網站會拒絕不符合一定標準的user-agent請求網頁,如果

python pygame模塊 打飛機遊戲

機器 con wid 初始化 imp convert turn 每次 調整 settings.py用於設置屏幕的基本設置 # -*- coding: gbk -*- __author__ = ‘HZQ‘ import pygame class Settings():

python實戰:一個目錄一鍵啟動管理小工具

app Coding put str top ini add nal 讀取 簡單的學習了幾天的python,總覺得最好根據自身的需求來做點小工具實戰一下。 上班的時候由於有很多目錄需要打開。每次都要一個個的找那些目錄。我覺得,我需要一個小工具。然後登記下,所有需要打開的目錄

Python 基礎實戰 -- 統計代碼量

textbox imp spl items 目前 nbsp ati extension print 1 import os 2 import easygui as g 3 4 def StatisticeCodeLine(dir_name): 5 fi

Python 爬蟲實戰(二):使用 requests-html

分享 -html 調用 交流 html 技術 python-re find 自己的 Python 爬蟲實戰(一):使用 requests 和 BeautifulSoup,我們使用了 requests 做網絡請求,拿到網頁數據再用 BeautifulSoup 解析,就在前不久

《跟老齊學Python Django實戰》讀後感

會有 內容 migration 讀後感 onetoone OS redis 部分 mar 1.說一下這本書,講解的很細致,內容選取足夠入門Django。 2.在學習這本書要註意的幾點: <1>如果你想跟著敲這本書的代碼必須要安裝:Django版本1.10.1(當

Python 爬蟲實戰—盤搜搜

and 一個 ace 共享 urllib ring view 實戰 post 近期公司給了個任務:根據關鍵搜索百度網盤共享文件並下載。 琢磨了幾天寫下了一段簡單的demo代碼,後期優化沒有處理。 主要的思路:(1)根據關鍵字爬取盤搜搜的相關信息       (2)解析並獲取

python-pygame的觸碰方法

[] urn quit set 方法 python AI center ID 1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author: ss 4 5 import pygame 6

路飛學院-Python爬蟲實戰密訓班-第1章

bsp enc fin 以及 sign 模塊 nco comm soc 學習筆記: 通過本章的學習,學習到了requests和BeautifulSoup模塊的安裝及使用方法。以及爬取給類網站的方法和知識點。 1、requests和Be