Python小遊戲:外星人入侵

alien_invasion.py:html

"""該遊戲主程序,儘可能作到最簡單"""dom

import pygameide

from settings import Settings字體

from ship import Shipidea

from pygame.sprite import Groupspa

from game_stats import GameStats.net

from button import Button代理

from score_board import Scoreboardorm

import game_function as gfhtm

def run_game():

"""初始化背景設置"""

pygame.init()

""""建立一個Settings實例"""

ai_settings=Settings()

"""建立一個遊戲窗口以及標題"""

screen=pygame.display.set_mode(

(ai_settings.screen_width,ai_settings.screen_height))

pygame.display.set_caption('Alien Invasion')

"""建立一艘飛船實例"""

ship=Ship(ai_settings,screen)

"""建立一個用於存儲子彈和外星人的編組"""

bullets=Group()

aliens=Group()

"""建立外星人羣"""

gf.creat_fleet(ai_settings,screen,ship,aliens)

"""建立存儲遊戲統計信息的實例,並建立記分牌"""

stats = GameStats(ai_settings)

sb = Scoreboard(ai_settings,screen,stats)

建立play按鈕

play_button = Button(ai_settings,screen,"Play")

"""進入主循環"""

while True:

""""監視用戶的操做,鍵盤和鼠標"""

gf.check_events(ai_settings,screen,ship,aliens,bullets,stats,play_button,sb)

if stats.game_active:

"""更新飛船"""

ship.update()

"""更新子彈"""

gf.update_bullet(ai_settings,screen,ship,aliens,bullets,stats,sb)

"""更新外星人"""

gf.update_aliens(ai_settings,screen,ship,aliens,stats,bullets,sb)

"""刷新屏幕"""

gf.update_screen(ai_settings,screen,ship,aliens,bullets,

stats,play_button,sb)

run_game()

game_function.py:

若是把這個遊戲比做一我的,那麼上一段代碼是剛接觸這我的,他給你留下的第一印象,那麼下面這段代碼能夠說是這我的的靈魂了

import sys

import pygame

from random import randint

from bullet import Bullet

from alien import Alien

from time import sleep

def fire_bullet(ai_settings,screen,ship,bullets,stats):

"""開火!"""

確保屏幕上的子彈數在限制範圍內

for i in range(int(stats.level/5) + 1):

if len(bullets) < ai_settings.bullet_allowed:

new_bullet=Bullet(ai_settings,screen,ship)

bullets.add(new_bullet)

def check_keydown(event,ai_settings,screen,ship,bullets,stats):

"""檢查用戶按鍵是否按下以及執行的任務"""

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_UP:

ship.moving_up=True

elif event.key == pygame.K_DOWN:

ship.moving_down=True

elif event.key == pygame.K_SPACE:

發射一顆子彈,而且在限制範圍內

fire_bullet(ai_settings,screen,ship,bullets,stats)

def check_keyup(event,ship):

"""檢查用戶釋放按鍵"""

if event.key == pygame.K_RIGHT:

ship.moving_right=False

elif event.key == pygame.K_LEFT:

ship.moving_left=False

elif event.key == pygame.K_UP:

ship.moving_up=False

elif event.key == pygame.K_DOWN:

ship.moving_down=False

def check_events(ai_settings,screen,ship,aliens,bullets,stats,play_button,sb):

"""響應鍵盤和鼠標事件"""

for event in pygame.event.get():

if event.type == pygame.K_q:

sys.exit()

若是一直按下右鍵或者左鍵,空格鍵,則向右或右移動或者開火

elif event.type == pygame.KEYDOWN:

check_keydown(event,ai_settings,screen,ship,bullets,stats)

釋放右鍵或左鍵,中止移動

elif event.type == pygame.KEYUP:

check_keyup(event,ship)

點擊Play按鈕,開始遊戲

elif event.type == pygame.MOUSEBUTTONDOWN:

mouse_x,mouse_y = pygame.mouse.get_pos()

check_play_button(ai_settings,screen,ship,aliens,bullets,

stats,play_button,mouse_x,mouse_y,sb)

def check_play_button(ai_settings,screen,ship,aliens,bullets,

stats,play_button,mouse_x,mouse_y,sb):

"""在玩家單擊Play按鈕時開始遊戲"""

button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y)

if button_clicked and not stats.game_active:

重置遊戲設置

ai_settings.init_dynamic_settings()

隱藏光標

pygame.mouse.set_visible(False)

重置遊戲統計信息

stats.reset_stats()

stats.game_active = True

重置記分牌圖像

sb.prep_score()

sb.prep_high_score(screen)

sb.prep_level()

sb.prep_ships(screen)

清空外星人和子彈列表

aliens.empty()

bullets.empty()

建立一羣新的外星人,並讓飛船居中

creat_fleet(ai_settings,screen,ship,aliens)

ship.center_ship(ai_settings)

def update_screen(ai_settings,screen,ship,aliens,bullets,stats,play_button,sb):

"""每次循環都重繪屏幕"""

screen.fill(ai_settings.bg_color)

for bullet in bullets.sprites():

bullet.draw_bullet()

ship.blitme()

aliens.draw(screen)

sb.show_score()

若是遊戲處於非活動狀態,繪製Play按鈕

if not stats.game_active:

play_button.draw_button()

""""刷新屏幕,擦去舊屏幕,顯示新屏幕"""

pygame.display.flip()

def update_bullet(ai_settings,screen,ship,aliens,bullets,stats,sb):

"""更新子彈位置,並刪除已經消失的子彈"""

更新子彈位置

bullets.update()

刪除消失的子彈

for bullet in bullets.copy():

if bullet.rect.bottom<=0:

bullets.remove(bullet)

檢查是否有子彈擊中外星人

check_bullet_alien_colide(ai_settings,screen,ship,aliens,bullets,stats,sb)

def get_number_aliens_x(ai_settings,alien_width):

"""得到水平方向上外星人個數"""

available_space_x = ai_settings.screen_width-2 * alien_width

number_aliens_x = int(available_space_x/(2 * alien_width))

return number_aliens_x

def get_space_rows(ai_settings,ship_height,alien_height):

"""得到垂直方向上外星人的行數"""

available_space_y = (ai_settings.screen_height-(3 * alien_height)-

ship_height)

number_aliens_rows = int(available_space_y/(2 * alien_height))

return number_aliens_rows

def creat_alien(ai_settings,screen,aliens,alien_number,row_number):

"""根據傳入的數據在某個位置建立一個外星人"""

alien = Alien(ai_settings,screen)

alien_width = alien.rect.width

alien.x = alien_width + 2 * alien_width * alien_number

alien.rect.x = alien.x

alien.rect.y = (alien.rect.height +20) + 2 * alien.rect.height * row_number

aliens.add(alien)

def creat_random_alien_x(number_aliens_x,ai_settings,screen,aliens,row_number):

"""在第一行隨機建立若干個外星人"""

for i in range(2,number_aliens_x+2):

random_number_x=randint(2,i)

for alien_number in range(random_number_x - 1,random_number_x):

creat_alien(ai_settings,screen,aliens,alien_number,row_number)

def creat_fleet(ai_settings,screen,ship,aliens):

"""建立外星人羣以及獲取屏幕上最大的行數和每行最多個數"""

alien=Alien(ai_settings,screen)

number_aliens_x = get_number_aliens_x(ai_settings,alien.rect.width)

number_rows = get_space_rows(ai_settings,ship.rect.height,

alien.rect.height)

"""隨機建立行數"""

for j in range(0,number_rows):

random_number_y = randint(0,j)

for row_number in range(random_number_y):

creat_random_alien_x(number_aliens_x,ai_settings,

screen,aliens,row_number)

def check_fleet_edges(ai_settings,aliens):

"""有外星人到達屏幕邊緣"""

for alien in aliens.sprites():

if alien.check_edges():

change_fleet_direction(ai_settings,aliens)

break

def change_fleet_direction(ai_settings,aliens):

"""將外星人下移,並改變它們的方向"""

for alien in aliens.sprites():

alien.rect.y += ai_settings.fleet_drop_speed

ai_settings.fleet_direction *= -1

def update_aliens(ai_settings,screen,ship,aliens,stats,bullets,sb):

"""檢測有外星人位於屏幕邊緣或者相撞或者外星人到達底部,更新外星人的位置"""

check_fleet_edges(ai_settings,aliens)

aliens.update()

檢測飛船與外星人的撞擊

if pygame.sprite.spritecollideany(ship,aliens):

ship_hit(ai_settings,screen,ship,aliens,stats,bullets,sb)

檢查是否有外星人到達屏幕底部

check_aliens_bottom(ai_settings,screen,ship,aliens,stats,bullets,sb)

def check_bullet_alien_colide(ai_settings,screen,ship,aliens,bullets,stats,sb):

"""檢測子彈和外星人的碰撞"""

collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)

兩個True可以使得子彈與外星人碰撞後消失,並返回一個字典

碰撞以後加分

if collisions:

for aliens in collisions.values():

i = randint(0,10)

if i>8:

stats.score += (ai_settings.alien_points + 10) * len(aliens)

sb.prep_score()

else:

stats.score += ai_settings.alien_points * len(aliens)

sb.prep_score()

檢查是否刷新最高分

check_high_score(stats,sb,screen)

if len(aliens) == 0:

刪除現有的子彈,加快遊戲速度,建立新的外星人

ship.center_ship(ai_settings)

bullets.empty()

ai_settings.increase_speed()

提升等級

stats.level += 1

ai_settings.increase_bullet_size()

sb.prep_level()

creat_fleet(ai_settings,screen,ship,aliens)

def ship_hit(ai_settings,screen,ship,aliens,stats,bullets,sb):

"""飛船與外星人相撞,生命減1,清除外星人和子彈列表

並建立新的外星人,飛船放在屏幕底部中央位置"""

if stats.ship_left > 0:

stats.ship_left -= 1

sb.prep_ships(screen)

清空外星人和子彈列表

aliens.empty()

bullets.empty()

新建一個飛船和外星人羣

creat_fleet(ai_settings,screen,ship,aliens)

ship.center_ship(ai_settings)

暫停0.5秒

sleep(0.5)

else:

ai_settings.bullet_width = 3

stats.game_active = False

pygame.mouse.set_visible(True)

def check_aliens_bottom(ai_settings,screen,ship,aliens,stats,bullets,sb):

"""檢查是否有外星人到達底部"""

screen_rect = screen.get_rect()

for alien in aliens.sprites():

if alien.rect.bottom >= screen_rect.bottom:

ship_hit(ai_settings,screen,ship,aliens,stats,bullets,sb)

break

def check_high_score(stats,sb,screen):

"""檢查是否產生了新的最高分"""
XM代理申請http://www.kaifx.cn/broker/xm...

if stats.score > stats.high_score:

stats.high_score = stats.score

sb.prep_high_score(screen)

後面的文件基本是做爲分支吧,一些屬性還有一些初始化的數據,都是爲game_function文件提供資源的

settings.py:

class Settings():

def __init__(self):

"""設置長度和寬度以及背景色屬性"""

self.screen_width = 800

self.screen_height = 700

self.bg_color=(255,255,255)

self.ship_limit = 2

"""子彈設置"""

self.bullet_width = 3

self.bullet_height=15

self.bullet_color=(60,60,60)

self.bullet_allowed=8

"""外星人移動設置"""

self.fleet_drop_speed = 10

"""以什麼樣的速度加快遊戲節奏"""

self.speed_up_scale = 1.1

self.init_dynamic_settings()

"""外星人點數的提升"""

self.score_scale = 1.5

"""子彈大小提升"""

self.bullet_scale = 10

def init_dynamic_settings(self):

self.speed = 1.5

self.bullet_speed = 3

self.alien_speed = 0.2

fleet_direction爲1表示向右移動,-1表示向左移動

self.fleet_direction = -1

計分

self.alien_points = 10

def increase_speed(self):

"""提升速度設置和外星人點數設置"""

self.speed *= self.speed_up_scale

self.bullet_speed *= self.speed_up_scale

self.alien_speed *= self.speed_up_scale

self.alien_points = int(self.alien_points * self.score_scale)

def increase_bullet_size(self):

self.bullet_width += self.bullet_scale

ship.py:

import pygame

from pygame.sprite import Sprite

class Ship(Sprite):

def __init__(self,ai_settings,screen):

"""初始化飛船並設置其初始位置"""

super(Ship,self).__init__()

self.screen=screen

加載飛船圖像並獲取其外接矩形

self.image=pygame.image.load('images/ship.bmp')

self.rect=self.image.get_rect()#獲取飛船的矩形

self.screen_rect=screen.get_rect()#獲取屏幕矩形

self.ai_settings=ai_settings

將每艘新飛船放在屏幕底部中央位置

self.rect.centerx=self.screen_rect.centerx

self.rect.centery=self.screen_rect.centery

self.rect.bottom=self.screen_rect.bottom

self.center_x=float(self.rect.centerx)

self.center_y=float(self.rect.centery)

"""連續檢測按鍵,設置未按下右鍵爲False"""

self.moving_right=False

self.moving_left=False

self.moving_up=False

self.moving_down=False

def update(self):

"""若是連續按方向鍵,則一直移動,而且不超過邊界"""

if self.moving_right and self.rect.right < self.screen_rect.right:

self.center_x+=self.ai_settings.speed

使用兩個if,這樣玩家同時按下兩個鍵,

將先增大rect.centerx值,再下降,則飛船位置不變

if self.moving_left and self.rect.left > 0:

self.center_x-=self.ai_settings.speed

if self.moving_up and self.rect.top > 0:

self.center_y-=self.ai_settings.speed

if self.moving_down and self.rect.bottom < self.screen_rect.bottom:

self.center_y+=self.ai_settings.speed

self.rect.centerx=self.center_x

self.rect.centery=self.center_y

"""在指定位置繪製飛船"""

def blitme(self):

self.screen.blit(self.image,self.rect)

def center_ship(self,ai_settings):

self.center_x = ai_settings.screen_width/2

self.center_y = ai_settings.screen_height - 28

alien.py:

import pygame

from pygame.sprite import Sprite

class Alien(Sprite):

def __init__(self,ai_settings,screen):

super().__init__()

"""初始化外星人並設置其初始位置"""

self.screen=screen

self.ai_settings=ai_settings

加載外星人圖像並設置rect屬性

self.image=pygame.image.load('images/alien.bmp')

self.rect=self.image.get_rect()

每一個外星人都在屏幕左上角附近

self.rect.x=self.rect.width

self.rect.y=self.rect.height

存儲外星人準確位置

self.x=float(self.rect.x)

def check_edges(self):

"""若是外星人碰到屏幕邊緣,則返回True"""

screen_rect = self.screen.get_rect()

if self.rect.right >= screen_rect.right:

return True

elif self.rect.left <= 0:

return True

def update(self):

"""移動外星人"""

self.x += (self.ai_settings.alien_speed *

(self.ai_settings.fleet_direction))

self.rect.x=self.x

def blitme(self):

"""在指定位置繪製飛船"""

self.screen.blit(self.image,self.rect)

bullet.py:

import pygame

from pygame.sprite import Sprite

class Bullet(Sprite):

def __init__(self,ai_settings,screen,ship):

在飛船位置建立一個子彈對象

super(Bullet,self).__init__()

self.screen=screen

self.rect=pygame.Rect(0,0,ai_settings.bullet_width

,ai_settings.bullet_height)

self.rect.centerx = ship.rect.centerx

self.rect.top = ship.rect.top

self.y=float(self.rect.y)

self.color=ai_settings.bullet_color

self.speed=ai_settings.bullet_speed

def update(self):

"""向上移動子彈"""

更新子彈的小數值

self.y -= self.speed

self.rect.y=self.y

def draw_bullet(self):

"""在屏幕上繪製子彈"""

pygame.draw.rect(self.screen,self.color,self.rect)

button.py:

import pygame.font

class Button():

def __init__(self,ai_settings,screen,msg):

"""初始化按鈕屬性"""

self.screen = screen

self.screen_rect = screen.get_rect()

設置按鈕大小以及其餘屬性

self.width,self.height = 200,50

self.button_color = (0, 255, 0)

self.text_color = (60,60,60)

self.font = pygame.font.SysFont(None,48)

建立按鈕的rect對象,並使其居中

self.rect = pygame.Rect(0, 0, self.width, self.height)

self.rect.center = self.screen_rect.center

按鈕的標籤只須要建立一次

self.prep_msg(msg)

def prep_msg(self,msg):

"""將msg渲染爲圖像,並使其在按鈕上居中"""

self.msg_image = self.font.render(msg,True,self.text_color,

self.button_color)

self.msg_image_rect = self.msg_image.get_rect()

self.msg_image_rect.center = self.rect.center

def draw_button(self):

繪製一個用顏色填充的按鈕,再繪製文本

self.screen.fill(self.button_color,self.rect)

self.screen.blit(self.msg_image,self.msg_image_rect)

game_stats.py:

class GameStats():

"""跟蹤遊戲的統計信息"""

def __init__(self,ai_settings):

self.ai_settings = ai_settings

self.game_active = False

self.reset_stats()

任何狀況下都不能重置最高分

self.high_score = 0

def reset_stats(self):

"""初始化在遊戲運行過程當中可能變化的統計信息"""

self.ship_left = self.ai_settings.ship_limit

self.score = 0

self.level = 1

self.bullet_width = 3

scord_board.py:

import pygame.font

from pygame.sprite import Group

from ship import Ship

class Scoreboard():

"""顯示得分的類"""

def __init__(self,ai_settings,screen,stats):

"""初始化顯示得分的屬性"""

self.screen = screen

self.screen_rect = screen.get_rect()

self.ai_settings = ai_settings

self.stats = stats

顯示得分時的字體設置

self.text_color = (30,30,30)

self.font = pygame.font.SysFont(None,48)

準備初始得分圖像以及當前最高得分

self.prep_score()

self.prep_high_score(screen)

self.prep_level()

self.prep_ships(screen)

def prep_score(self):

"""將得分轉化爲可渲染的圖像"""

rounded_score = int(round(self.stats.score,-1))

score_str ="Score:"+"{:,}".format(rounded_score)

self.score_image = self.font.render(score_str,True,self.text_color,

self.ai_settings.bg_color)

將得分放在屏幕右上角

self.score_rect = self.score_image.get_rect()

self.score_rect.right = self.screen_rect.right - 20

self.score_rect.top = 20

def prep_high_score(self,screen):

"""將最高得分渲染爲圖片"""

high_score = int(round(self.stats.high_score,-1))

high_score_str = "High Score:"+"{:,}".format(high_score)

self.high_score_image = self.font.render(high_score_str,True,self.text_color,

self.ai_settings.bg_color)

"""將最高得分放在屏幕左上角"""

self.high_score_rect = self.high_score_image.get_rect()

self.high_score_rect.left = self.screen_rect.left + 20

self.high_score_rect.top = 20

def prep_level(self):

"""將等級渲染爲圖像"""

self.level_image = self.font.render("Level:"+str(self.stats.level),True,

self.text_color,self.ai_settings.bg_color)

將等級放在右下角

self.level_rect = self.level_image.get_rect()

self.level_rect.right = self.score_rect.right

self.level_rect.bottom = self.score_rect.bottom + 650

def show_score(self):

"""在屏幕上顯示得分,最高分,等級"""

self.screen.blit(self.score_image,self.score_rect)

self.screen.blit(self.high_score_image,self.high_score_rect)

self.screen.blit(self.level_image,self.level_rect)

繪製剩餘飛船

self.ships.draw(self.screen)

def prep_ships(self,screen):

"""顯示剩餘的飛機"""

self.ships = Group()

for ship_number in range(self.stats.ship_left + 1):

ship =Ship(self.ai_settings,self.screen)

ship.rect.x = 10 + ship_number * ship.rect.width

ship.rect.y = self.screen_rect.top + 640

self.ships.add(ship)

原文連接:https://blog.csdn.net/weixin_44412311/article/details/106590762

相關文章
相關標籤/搜索