Python開發【項目】:大型模擬戰爭游戲(外星人入侵)


外星人入侵

游戲概述:

  現在准備用python開始搞一個大型游戲,模擬未來戰爭,地球人狙擊外星人大戰(其實就是小蜜蜂游戲2333),玩家控制一個飛船,用子彈殲滅屏幕上空的外星飛船;項目用到了Pygame模塊,下面是模塊的安裝

Windows系統上Pygame安裝:

訪問https://bitbucket.org/pygame/pygame/downloads/地址,查找與Python版本匹配的Windows安裝程序,cp35表示支持python3.5,本次使用的是python3.5版本

下載擴展名為.whl的文件,復制到項目文件夾中,打開CMD窗口,執行pip命令進行安裝(主要pip跟python的版本綁定) 

切換到文件目錄,執行命令

python -m pip install --user pygame-1.9.2-cp35-cp35m-win32.whl

進入python,執行import pygame 無報錯則表示安裝成功

  

宇宙飛船 

實現功能,屏幕下方顯示一艘宇宙飛船,可以左右移動,按空格鍵可以發射子彈

1、全局配置settings.py:

全局配置、初始各種原始數據,沒啥好說的,有什么需要初始設置的東西放到這里就好了

class Settings():
    '''存儲外星人入侵中所有的設置'''

    def __init__(self):
        '''初始化設置'''

        #設置各種初始數據
class Settings():
    '''存儲外星人入侵中所有的設置'''

    def __init__(self):
        '''初始化設置'''
        self.screen_width = 900
        self.screen_heigt = 600
        self.bg_color = (230,230,230)    # 設置背景色  灰色

        self.ship_speed_factor = 1.9   # 飛船移動速度
        self.ship_image_path = 'images/ship.png'    # 飛船圖片路徑

        self.bullet_speed_factor = 0.5  # 子彈移動速度
        self.bullet_width = 3
        self.bullet_height = 15
        self.bullet_color = 60,60,60
        self.bullets_allowed = 4         # 允許屏幕中出現子彈的數量
完整settings.py代碼

2、程序主體程序alien_invasion.py:

程序運行的主體架構都在此文件中,while 循環之前是各種實例化,while循環之后調用各種函數進行處理

import pygame

from settings import Settings
from ship import Ship
from bullet import Bullet
from pygame.sprite import Group
import game_functions as gf

def run_game():
    pygame.init()       # 初始化背景設置
    ai_settings = Settings()        # 全局設置
screen = pygame.display.set_mode( # 創建screen顯示窗口 (ai_settings.screen_width,ai_settings.screen_heigt) ) pygame.display.set_caption('Alien Invasion') # 標題
# 創建飛船 ship = Ship(ai_settings,screen) # 創建子彈編組 bullets = Group() # 開始游戲主循環 while True: # 監視鍵盤和鼠標事件 gf.check_events(ai_settings,screen,ship,bullets) # 移動飛船 gf.update_ship(ship) # 更新子彈位置 gf.update_bullets(bullets) # 更新屏幕 gf.update_screen(ai_settings,screen,ship,bullets) run_game()
import pygame

from settings import Settings
from ship import Ship
from bullet import Bullet
from pygame.sprite import Group
import game_functions as gf

def run_game():
    pygame.init()       # 初始化背景設置
    ai_settings = Settings()        # 全局設置

    screen = pygame.display.set_mode(           # 創建screen顯示窗口
        (ai_settings.screen_width,ai_settings.screen_heigt)
    )
    pygame.display.set_caption('Alien Invasion')    # 標題

    # 創建飛船
    ship = Ship(ai_settings,screen)
    # 創建子彈編組
    bullets = Group()

    # 開始游戲主循環
    while True:
        # 監視鍵盤和鼠標事件
        gf.check_events(ai_settings,screen,ship,bullets)
        # 移動飛船
        gf.update_ship(ship)
        # 更新子彈位置
        gf.update_bullets(bullets)
        # 更新屏幕
        gf.update_screen(ai_settings,screen,ship,bullets)

run_game()
完整alien_invasion.py代碼

3、宇宙飛船模塊ship.py:

創建飛船Ship類,初始化飛船圖片和位置信息,設置繪制飛船的函數blitme,以及飛船移動update的函數

import pygame

class Ship():
    '''飛船所有信息'''
    def __init__(self,ai_settings,screen):
        # 加載飛船圖片、獲取外接矩行,設置飛船在screen的位置
          ---snip---

        # 移動標志
        self.moving_right = False
        self.moving_left = False

    def blitme(self):
        '''在指定位置繪制飛船'''
             ---snip---

    def update(self):
        # 向右移動飛船、向左移動飛船
          ---snip---
import pygame

class Ship():
    '''飛船所有信息'''

    def __init__(self,ai_settings,screen):
        self.screen=screen
        self.ai_settings = ai_settings

        # 加載飛船圖片、獲取外接矩形
        self.image = pygame.image.load(self.ai_settings.ship_image_path)   # 加載圖片
        self.rect = self.image.get_rect()   # 獲取圖片外接矩形
        self.screen_rect = screen.get_rect()        #獲取屏幕外接矩形

        # 將每搜新飛船放到並木底部中心
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom
        # 設置成浮點類型
        self.center = float(self.rect.centerx)      # self.rect.centerx設置不了浮點數 只能另設置一個變量進行運算

        # 移動標志
        self.moving_right = False
        self.moving_left = False

    def blitme(self):
        '''在指定位置繪制飛船'''
        self.screen.blit(self.image,self.rect)

    def update(self):
        # 向右移動飛船
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.center +=self.ai_settings.ship_speed_factor
        # 向左移動飛船
        if self.moving_left and self.rect.left > self.screen_rect.left:
            self.center -= self.ai_settings.ship_speed_factor

        self.rect.centerx = self.center
完整ship.py代碼

4、創建子彈模塊bullet.py:

創建子彈Bullet類,跟Ship類似,初始化子彈的各種信息,設置子彈相對飛船的初始位置,設置繪制子彈的函數draw_bullet,子彈位置移動函數update(函數名不能改)

import pygame
from pygame.sprite import Sprite
import time

class Bullet(Sprite):
    '''飛船子彈進行管理'''
    def __init__(self,ai_settings,screen,ship):
        # 創建子彈矩形初始位置(0,0,3,15)左上角,設置子彈的初始位置(飛船頂部)
         ---ship---

    def update(self):
        # 子彈位置更新
      ---ship---
    def draw_bullet(self):
        # 繪制子彈圖片
      ---ship---
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#-Author-Lian

import pygame
from pygame.sprite import Sprite
import time

class Bullet(Sprite):
    '''飛船子彈進行管理'''

    def __init__(self,ai_settings,screen,ship):
        super(Bullet,self).__init__()
        self.screen = screen

        # 創建子彈矩形初始位置(0,0,3,15)分別對應lef,top,寬,高
        self.rect = pygame.Rect(0,0,
        ai_settings.bullet_width, ai_settings.bullet_height)

        self.rect.centerx = ship.rect.centerx  # 設置中心點x軸坐標跟飛船一致
        self.rect.top = ship.rect.top          # 設置y軸坐標頂部跟飛船一致

        # 設置成小數進行計算
        self.top = float(self.rect.top)

        self.color = ai_settings.bullet_color
        self.speed_factor = ai_settings.bullet_speed_factor

    def update(self):
        self.top -=self.speed_factor
        self.rect.top = self.top
        print(self.rect.top)

    def draw_bullet(self):
        pygame.draw.rect(self.screen,self.color,self.rect)
完整bullet.py代碼

5、儲存運算的模塊game_functions.py:

項目的主體運算模塊:check_events監視鍵盤和鼠標事件,update_screen更新屏幕不斷地刷新

import sys
import pygame
from bullet import Bullet

def check_events(ai_settings,screen,ship,bullets):
    # 監視鍵盤和鼠標事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # 關閉窗口退出
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event,ai_settings,screen,ship,bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event,ship)

def update_screen(ai_settings,screen,ship,bullets):
    '''更新屏幕上的圖片,並切換到新屏幕'''
    screen.fill(ai_settings.bg_color)  # 設置背景顏色
    ship.blitme()  # 繪制飛船
    # 循環子彈組里面的元素,進行繪制 為空時不執行
    for bullet in bullets.sprites():
        bullet.draw_bullet()    # 繪制子彈
    # 顯示最新屏幕,擦拭舊屏幕
    pygame.display.flip()

def check_keydown_events(event,ai_settings,screen,ship,bullets):
    '''飛船左右移動、發射子彈'''
        ---snip - --
def check_keyup_events(event,ship):
    '''飛船左右移動'''
        ---snip - --
def update_bullets(bullets):
    '''更新子彈位置,刪除子彈'''
        ---snip---
def update_ship(ship):
    '''更新飛船位置'''
        ---snip---
def fire_bullet(ai_settings,screen,ship,bullets):
    # 創建一個子彈對象 加入到子彈組
    if len(bullets) < ai_settings.bullets_allowed:  # 子彈少於允許值時再生成
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)
import sys
import pygame
from bullet import Bullet

def check_events(ai_settings,screen,ship,bullets):
    # 監視鍵盤和鼠標事件
    for event in pygame.event.get():

        if event.type == pygame.QUIT:  # 關閉窗口退出
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event,ai_settings,screen,ship,bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event,ship)

def update_screen(ai_settings,screen,ship,bullets):
    '''更新屏幕上的圖片,並切換到新屏幕'''
    screen.fill(ai_settings.bg_color)  # 設置背景顏色
    ship.blitme()  # 繪制飛船

    # 循環子彈組里面的元素,進行繪制 為空時不執行
    for bullet in bullets.sprites():
        bullet.draw_bullet()    # 繪制子彈

    # 顯示最新屏幕,擦拭舊屏幕
    pygame.display.flip()
    # print('1')

def check_keydown_events(event,ai_settings,screen,ship,bullets):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings,screen,ship,bullets)

def check_keyup_events(event,ship):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False

def update_bullets(bullets):
    '''更新子彈位置,刪除子彈'''
    bullets.update()     # 子彈組每個成員執行self.update()操作
    for bullet in bullets.sprites():
        if bullet.rect.bottom <= 0:  # 子彈出界 刪除
            bullets.remove(bullet)

def update_ship(ship):
    ship.update()

def fire_bullet(ai_settings,screen,ship,bullets):
    # 創建一個子彈對象 加入到子彈組
    if len(bullets) < ai_settings.bullets_allowed:  # 子彈少於允許值時再生成
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)
完整代碼game_functions.py代碼

 

效果圖: 

 

 

 

 

 其他功能---待續....

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM