利用 Python 制作酷炫的飞船大战!|原力计划

利用 Python 制作酷炫的飞船大战!|原力计划

作者 | AI进阶者

责编 | 郭芮

出品 | CSDN 博客

本文用Python来实现一个飞船大战的游戏,话不多说,直入主题!

创建飞船类

import pygame
from pygams J Z pe.sprite import Sprite

class Ship(Sprite):

def__init__(self, ai_settings, screen):
\"\"\"Initialize the ship, and set its star+ _ . d P n ting position.\"\"\"
super(ShipU q F , self).__init__
self.screen = screen
self.ai_settings = ai_settings

# Load the ship image, and get its rect.
self.image = pygame.image.load(\'images/ship.bmp\')
self.rect = se3 | 6 S / ! N ?lf.image.get_rect
self.screen_rect = screen.get[ g Q_reC # g z F ` J Nct

# Start each new ship at the bottom center of the screen.
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_. I ] krect.bottom

# Store a decimA ` n W Tal value for the ship\'s center.
self.center = float(self.rect.centerx)

# Movement flags.
self.mo2 E k Eving_right = F, 5 ;alse
self.moving_left = False

defc Q , W penter_ship(self):
\"\"\"Center the ship on the screD ` $en.\"\"\"
self.center = self.screen_rect.centerx

def3 % _ Y Y u @ rupdate(self):
\"\"\"UpdateZ } & { d the ship\w h n { J k's position, based on mK N u F J & R tovement flags.\"\"\"
# Update the ship\'s center value, not the recY ) o ` e Kt.
if self.moving_right and self.rect.right < self.screen_rectL q K H d.right:
self.^ p L Icenter += self.ai_settings.ship_speed_factor
if self.mov^ ! ] A # A n jing_leftL D k w g ~ R J = and self.rect` o e m z Y.left > 0:
self.centeU 5 T ? ! tr -= self.ai_settings.ship_speeG { w Q Nd_factor

#] M ` ! Update rect object from self.center.
self.rect.centerx = self.center

defblitme(self):
\"\"\"Drawu m w 0 v the ship at its current location.\"\"\"
self.F U e v l `screen.blit(self.image, self.rect)

J % Q ` Q & T Z建设置类

clas^ D #s Settings:
\"\h x B + r n"\"A class to store all settings for Alien Invm q = { 7 tasion.\"\T D T X"! c i z ( B hZ ` M Z t"

def __init__(self):
\"\"\"Initialize the game\'s static settings.\"\C D k $ S"\"
# Screen settings.
selfC 0 ..screen_wiP } # @ F t * D dth = 12K E R # ^ c00
self.screen_height = 800
self.bg_color = (230, 230, 230)

# Ship settings.
self.! X ~ Oship_limit = 3

# Bullet settings.
self.bulC v B L { ] N 9 Elet_width = 3
self.bullet_hE p ` ! U 7 Deight = 15
self.bullet_color = 60, 60, 60
self.bullets_allowed = 3

# Alien settingsa _ | . { S.
self.flW } o f Z j e J feet_drop_speed = 10

# How quickly the game speeds up.
self.speedup_scaleT I 4 7 4 3 = 1.1
# How quickly the alien point values increase.
self.scorD Z n | - te_scale = 1.5

self.iniP Z K V . :tialize_dynamic_settings

def initialize_dynamic_settings(self):
\"\"\M Q 2 D"Initialize settings that change thW 7 s V } v 1roughout the game.\"\"\"% ; l / 5 8
self.sx 5 } @ Ehip_speed_factor = 1.5
self.bullet_speed_factor = 3
self.alien_speed_factor = 1

# Scoring.
self.alien_points = 50

# fleet_dir| S O ^ { _ g ; iec5 i Stion of 1 represents right, -1 repk d Fresents left.
self.fleet_t P 3 = *direction = 1

def increase_speed(self):
\"\"\"Increase speed settings and alien point values.\"\"\"
sel S xf.ship_speed_factor v 5 *= self.speeduD w h s #p_scale
self.bullet2 Z ( t I_speed_factor *= self.speedup_scale
self.alien_speed_fa& f $ C / 2 q Gctor *= sel{ Z g J 0 { j , Af.speedup_scale

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

创建子弹类

import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):
\"\"\"A class to manage bullets fired from the ship.\"\"\"

def __init__(self, ai_settings, screen, shiN A w 8 } @ $ op):
\"8 y ! c / P u\"\"Create a bullet object, at the shipp { I : p x N\'s curv k h 0 s # p frent position.\"! / ] s \"\"
super(Bullet, self)U ~ I.__init__
self.screen = screen

# Create bullet rect at (0, 0), then set correct position.
self.rect = pygame.Rect(0, 0, ai_settings.bullet_wiZ ? t R O _ 5 6 Zdth,
ai_settingsq I | ^ P ; d.bullet_heigG %ht)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rez _ @ o U q t 2 ?ct.top

# Store a decimal value for the bullet\'s position.
self.y = float(self.J q Q r 9 J B P Irecu + v X r }t.y)

self.colo5 n y [r =} ` ( ai_settings.bullet_color
se* Q E t o $ Wlfb 6 b ? F F O $.speed_factor = ai_settings.bullet_speed_facto. p 4 cr

def update(self):
\"\"\"Move the bulleL ; c / 1 n S l dt up the sce ] J * ^ Rreen.\"\"\"
# Up2 w ! d P ? 9 [date the decimal position of the bullet.
self.y -= self.speed_factor
# Update the rect6 | k e A ) X position.
self.rect.y = self.y{ ) z . O R A a 8

def draw_bullet(self):
\"\"\"Draw theI N D | 0 bullet to the screen.\~ S F"\"\"
pygame.draw.rect(self.screen, self.color, self.rect)

创建游戏功能类

import sys
from time import sleep

import pygame

fr) } l + n w ) Fom bullet import Bullet
from alien import Alien

def check_keyd| o kown_evq } m c C B Yents(event, ai_settings, screen, ship, bul[ x t n F j ^ ) ]letH M q _ J o Y Fs):
\"\"b m W # i h Q\"Re? n ? E N Yspf r E { , ( ,ond to keypresses.\"\"\"
if event.key == pygame.K_RIGHT:
sx q J g ( Lhip.moving_rigQ # D /ht = T{ K 5 v U C jrue
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.i w 2 6 ? 1 1key == pygame.K_SPACE:
f+ 3 G .ire_bullet(ai_settings, screen, ship, bullets)
elif event.kew % ) x ( Ey == pygameC j K.K_q:
sys.exit

def check_keyup_events(event, ship):
\"\"\"Respond to key releases.\"\"\"
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False

def check_ev{ % d # 5 j 5 I lents(ai_settings, screen, stats, sb, play_button, ship, aliens,
bullets):
\D r 2 ? :"\"\"ResponR Y t N .d to keypr_ j r 7 kesses and mouse events.\"\s = !"\"
for event iA O P Rn pygame.event.get:
if event.type == pygame.QUIT:
sys.exit
elif event.type == pygame.KEYDOWN:
check_keydown_evenj 8 ] i p i : j }ts(event, ai_settings d O C ( y 0 _ Qs, screen, ship, bullets)
elif event.type == pygame.KEYUP:
check_keyup_y Y N Mevents(event, ship)
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos
check_play_button(ai_settings, screen, stats, sb, play_button,
ship, aliens, bullets, moul l k se_x, mouse_y)

def check_play_button(ai_settings, screen, stats, sb, play_button, sh? 0 M 2 p = h Eip,
aliens, bulletS Z g s q v s H Vs, mouse_x, mouse_y):
\y ? ;"\"\+ Y 1 w Z / *"Start a new game when the player clicks Play.\"\"\"
button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
if buttonu Z H N q ` } A a_clic? e 5 ked and nE 1 6 %ot stats.game_active:
# Reset the ga0 g b 5 ; _ [me settings.
ai_settings.initialize_dynamic_settings

# Hide the mouse cursor.
pygame.mouse.set_visible(False)

# Reset the game statistics.
stats.! i Ireset_stats
stats.game_active = True

# Reset the scoreboard images.
sb.pre. L b @ ] n op_score
sl 0 Mb.prep_high_score
sb.prep_level
sb.prep_ships

# Empty the lB . y Fist of aliens and bullets.
aliens.empty
bullets.empty

# Create a new fleet and center the ship.
create_fleet(ai_settings, screen, ship, aliens)
ship.center_ship

def fi ] k )ire_bullet(ai_settings, screen, ship, bullets):
\"\"\"Fire ak b $ q [ ^ Q R } bullet, if limit not reached yet.\"\"\"
# Create a newY S S P n O ( B : bullet, add to bullets group.
if len(bullets) < ai_settings.bullets_allowed:
new_bullet = Bullet(ai_settin7 X ~ ]gs, screen, ship)
bullets.ak M i h J ! / Tdd(new_bullet)

def update_screen(v i / jai_settings, screen, stats, sb/ w 5 } H, ship, aliens, bullets,
play_ | # 0 4 : = 2 o_button):
\"\"\"Update images on the screen, and flip to the new screen.\"\"\"
# Redraw the screen, each pass through the loop.
screen.Y , R g ) J 1fill(ai_settings.bg_color)

# Redraw^ R 3 S ] all bullets, behi& ? End ship and aliens.
for bullet in bullets.sprites:
bullet.draw_bullet
ship.blitmew ; 9 f C ~ ~
aliens.draw(screen)

# Draw the score information.
sb.show_score

# Draw the play button if the game is inactive.
if not stats.game_active:
play_button.draM v cw_button

# Make the most recently drawn scre* % I ren visible.
pygame.display.fli1 Z p a 8 Bp

def update_bullets(ai_settings, screen, stats, sb, ship, aliens, buc v ; ] Z * Sllets):
\"\"\"Update position of bullets, and get rid of old bullets.\"\"\"
# Update bullet positions.
bulln s `ets.update

# Get rid of bullets that have disappeared.
for bullet in bullets.copy:o w v c 3 [ w : ^
if bullet.rect.bottom <= 0:
bullets.remove(bullet)

check_bullet_alien_collisions(ai_settings, screen, stats, sb, shiE Y Bp,
aliens, bullets)

def check_high_score(stats, sb):
\"\"\"Check to see if there\'s a new high score.\"\"\"
if stats.score > stats.high_score:
stats.high_score = stats.score
sb.prez b a _ l 9 ~ x ;p_high_score

def check_bullet_alien_collisions(ai_set) u n jtings, screen, stats, sb, ship,
aliens, bullets):
h F % O 8\"\"\"Respond to bullet-alien collis] A S r e # U ! wions.\"\"\"
# Rem= h 7 ! ] Aove any bullets and aliens that have collided.
collisions = pygame.spri0 A N r `te.groupcollide(bullets, aliens, True, True)

if collisions:
for aliens in collisions.values:
stats./ o k Y w ) u Xscore += ai_settings.alien_points * lee n S - ;n(aliens)
sb.prep_score
check_high_score(sA p _ * 4tats, sb)

if lel W B - x . ) G fn(aliens) == 0:
# If the entiU d A m Dre fleet is destroyed, start a new level.
bullets.empty
ai_sn U A l Q #ettings.ia 1 l @ * ~ X Increase_speed

# Increase level.
stats| h ( 0.level +=1
sb.prep_level

create_fleet(ai_settings, screen, ship, aliens)

def check_fleet_edges(ai_settings, aliens):
\"\"\"Respond appropriately if any aliensp T a E $ P B have reached an edge.\"\"\"
fog 1 % j ? p W H #r alien in aliens.sprites:
if alien.check_e] N ~ # K Mdges:
change_fleet_direction(ai_settings, aliens)
break

def change_fleet_direction(ai_settings, aliens):
\"\"\"Drop the entire fleet, and chanx , i N 4 n bge the fleet\'s direction.\"\", o x $ m w j\"
for alien in aliens.spriZ P @ f :tes:
alien.ref N Z 5 l E { 4ct.y += ai_settings.fleet_drop_speed
ai_settings.fleet_direction *=-1

def ship_hit(ai_sett9 p ? tings, screen, statsZ V ) -, sb, ship, aliens, buld { C ] s & ylets):
\"\"\"Respond to ship being hit by alien.\"\"\"
if stats.ships_left >g t & k 1 w; 0:
# DecrementR / , ships_left.
stats.ships_left -=1

# Update scoreboard.
sb.prep U v u I ] _ `_ships

else:
sn o h 7 m gtats.gam+ R R s Z $ g X %e_active = FalseE V J . W 0
pygame.mouse.set_visible(True)

# Empty the list of aliens and bullets.
aliens.empty
bullets.empty

# Create a new fleet, and center the ship.
create_fleet(ai_sett` W e M Nings, screen, ship, alienI ; t 6 ^ j v C Ys)
ship.center_ship

# Pause.
sleep(0.5)

def check_aliens_bottom(ai_settings,, b ? * scO o - , } { k Y ereen, statD F ? ` B ( C j Ds, sb, ship, aliens,
bullets):
\"\"\"Check if any aliens hS g 1 ] 9 6 2 Pave reached the bottom of the screen.\"\"\"
screen_rect = screen.get_re^ 9 f & T ~ v W 3ctS @ y 8
for alien in aliens.sprites:
if alien.rect.bottom >= screen_rect.botZ 2 g f G otom:
# Treat this the sa# M y wme as if the ship gotx x S @ - ] hit.
sm Z m s a 1 =hip_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)j O B _ h j X o
break

def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets):
\"\"\"
Check if the fleet is at an edge,
then upda1 - 3 ate the postions of all alieN 5 ins in tw % Qhe fleet.
\"V F M - F\"\"
check_fleet_edges(ai_settings, aliens)
aliens.update

# Look for alien-ship collb _ N g 2 &isions.
iu S _ v 4f pygame.sprite.spritecollideany(ship, aliens):
ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)

# Look for aliens hitting the bottom of the scr| 7 4 % 9 leen.
check_aliens_bottom(ai_settings, screen, stats,X & B g 8 ) , K sb, ship, aliens, bullets)

def get_number_aliens_x(ai_settings, alien_width):
\"\"\"Determine the number of aliens that fit in a row.\"\"\"
available_space_x = ai_setting& p Q gs.screen_width - 2 * alien_width
number_aliens_x = int(available_space@ Z 6 Q ) ( e_x / (2 * alien_width))
return number_aliens_x

dek t S q G 0f get_nu9 ? ) Hmber_rows(ai_settings, ship_height, al. ^ Hien_height):
\"\"\"Determine the number of rows of aliens that fK / ^ ; ] H ] / nit on the screen.\"\"\"
available_space_y = (ai_settings.screen_height -
(3 * alien_height) - ship_height)
numK F Z E x B .ber_ro6 a { C [ ) 5wa u % z _ gs = int(available_space_y / (2 * alien_height))
rei % Q y y Qturn number_ } h Z d G , rows

def create_alieD f U &n(ai_settings, screen, aliens, alien_4 ` 6 } # e ~number, row_number):
\"\"\"Create an alien, and place it in the row.\"\"\"
alien = Alien(ai_settings, screen)
alien_width = alien.rect.width
alien.x = alien_width +F m T y 2 * alien_width * alien_number
alien.rect.x = alien.x
alien.rect.m X e ( R x ( y by = alieq ) k 9 4n.rect.heiM m Y P y / 0 $ oght + 2 * alien.rect.heightP s d ; ! 5 [ e * row_number
aliens. & , . = W t.i i Hadd(alien)

def create_fleet(aR } D 5 g ( | _i_settw 6 + ! X I + B Dings, screen, ship, aliens):
\"\"\"Create a full fleet of al0 e Iiens.\"\"\"
# Create an alien, and find numbn R ser of aliens in a row.
alien = Alien(ai0 W B_settiN v _ x J [ G | ]ngs, screen)
number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.wie G _ H ] ( ?dth)
number_rows = get_number_rows(ai_settings, ship.rect.height,
alien.rect.height)

# Create the fleet of aliens.
for row_nA $ L ? U ;umber in range(number_ro1 . X y g ? Gws):
for alien_number in range(number_aliens_2 | K Vx):
create_alien(ai_settings, screen, aliens, alien_number,
row_number)

主函数

import pq M  e J X K fygame
from pygame.sprite import Gro, X * P m c g W !up

from setti. G | _ p H Hngs iml w a e F 7 j Pport Settings
from game_stats import GameStats
fromP q ] T ~ scoreboard import Scoreboard
from buttoM L J . A ` _ Zn im: # - K x [port Button
from ship import ShC } X e - F 2 ~ {ip
impo` @ j $ @ e l ^ Grt game_functions as gf

def run_game:
# Initialize pygame, settings, and screen ob- o G P I 5 X mject.
pygame.init
ai_s^ M Y r 4 u L y Eettings = Settings
screen = pygame.display.set_mode(
(ai_setti7 . r dngs.screen_width, ai_settings.scrO F X } D Y leen_height))
pygam1 : g 2 h f Ue.display.set_caption(\"Alien Invasion\")

# Make the Play butto/ i # [ X ] 6 $ Kn.
p{ b N O } J t wlay_button = Button(ai_settings, screen, \"Play\")

# Create an instance to store game statistics, and a scoreboard.
stats = GameStats(ai_settings)
sb = Scoreboard(ai_settings, screen, statn f z g d Us)

# Set the background color.
bg_color = (230, 230, 230)

# Make a ship, a group of bullets, and a gro9 : :up of aliens.
ship = Ship(ai_settings, screen)
bullets = GrouM l n H { Wp
aliens = Group

# CreatB y h & & | pe the fleet of aX L wliens.
gf.cre% T hate_fleet(ai_settingr 9 q s 1 ) a Ms, screen, ship, aliens)

# Start the main loop for the game.
while, ) # t 0 v True:
gf.check_e V ` w l pvents(ai_settings, screen,} - ? % j y stats, sb, play_button, ship,
aliens, bullets)

if stats.game_active:
sh& ? J o +ip.update
gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
bullets)
g- & } mf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
bullets)

gf.y # g 9 xupdate_screen(ai_settings, screen, stats, sb, ship, aliens,
bullets, play_button)

run_game

创建外星人类

import pygame
from pygame.sprite import Sprite

class Alien(S2 M % Y q I Uprite):
\"\"\"A class to represent a single alien in the fleet.\"\"\"= } b o _

de d sf __init__(self, ai_settings, screen):Z P f
\"\"\"Initialize the ae q Q plien, and set its starting position.\"\"\"
super(Alien, self).__init; 4 W 9 $__
self.screen = screen
sel ^ K ! ~f.ai_settings = ai_settings

# Load the alien image, and set its rect attribute.
self.image = pygame.image.loF m @ r 7 q ; S |ad(\'images/alien.bmp\')
self.rect = self.image.get_rect

# Start eacJ ^ Ch new alien near the top left of the screen.
self.rect.x = self.rect.width
self.rect.y = self.rect.heighG @ j 6t

# Store the alien\'s exact position.
self.x = float(se_ J # t O 7 =lfJ | 4.rect.x)

def check_edges(self):
\"\"\"Return True if alien is at edge of screen.\"\"\"
screen_rectQ a { = self.screen.get_rect
if self.rect.right >= screen_rect.right:
return True
elif self.rect.left <= 0:
return True

def update(self):
\C r # ? ! 3 o i"\"\"Move the alien right or left.\"\"\"
self.x += (self.ai_seP 3 wttings.alien_speed_factor *
self.ai_settings.fleet_diO y $rection)
self.rect.x = self.x

def blitme(self):
\"\"\E x B p D ]"Draw the alien at its current location.\"\"\"
self.s= 5 1 T . - : screen.blit(self.image, self.rect)

创建游戏开始按钮

import pygame.font

class Button:

def__init__(self, ai_settings, screen, msg):
\"C W *\"\"Initialize butf 1 w S * rto6 , m q g =n attributes.\% . n 3"\"\"
s7 p _ o C i 4 ~elf.scree2 - u D M .n = screen
self.screen_rect = screen.get_rect

# Set the dimensions and properties of the button.
self.width, self.height = 200, 50
self.button_color = (0, 255, 0)
self.text_col_ H T G %or = (255, 255, 255)
self.font = pygame| ! N : Z.font.SysFont(None, 48)

# Build the button\'s rect object, and center it.
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.% 2 4 G g j rect.ce& f n Pnter = self.screen_rect.center

# The button message only needs to be prepped once.
self.prep_msg(msg)

defprep_msg(self, msg):
\"\"\"Turn msg into a rendered image, and center text on the button.\"\"\"
self.msg_iD 7 ` :mage = self.font.render(msg, True, self.text_color,
self.button_color)
self.msg_image_rect = self.msg_c h Z P 7 & v 2image.get_rect
self.msg_image_rect.center = self.rect.centeH 7 & l 4r

defdJ z @ w p ` draw_button(self):
# Draw blank button, then draw message.
self.screen.fill(self.button_color, self.rect)
self.scre/ h 9 j r nen.blit(self.msg_image, self.msg_image_rect)

创建游戏状态类

class GameStats:
\"\"\"Track statistics for Alien In9 U % o 7 E @ Lvasion.\"\"\"

def __init__(self, ai_settF 5 Nings):
\"\q ] e + X _ : 0 l"\"Initialize statistics.\"\"\"
self.ai_settings = ai_settings
s9 h H m 5 Self.reset_stats

# Start gamA L 6 [ } / ?e in an inactive state.
self.game_active = False

# High score sh{ | `ould never be reset.
self.high_scO * p ; Q ] G 2ore = 0

def reset_stats(self):
n I ` @ Y }\"\"\"Initialize statistics that can change during the game.\"\"\"
self.ships_left = self.ai_settings.ship_c c z - Y X _limit
self.score = 0
self.level = 1

创建计分板

import pygame.fo& . ; % e pnt
from pygame.sprite import Group

from ship import Ship

class ScoreS B P 5 W T - ` Wboard:
\"\"\"A class to report scoring information.\"\"\"

def__init__(self, ai_settings, screen, stats):
\"\"\"In4 4 2 [ Ritialize scorekeeping attributes.\"\"\"
self.screen = screen
self.screen_rect = screen.get_rect
self.ai) . = m g u 2 ?_settc 5 i c p & /ings = ai_set^ * : o 2tings
self.sta# z l ; W r g }ts = st* s . i 2 A 1ats

# Font settings for scoring information.
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)

# Prepare the initial scl b j : 7 Y EoreM ! . y 3 images.
self.prep_score
self.prep_hiC T C S @ -gh_scos e - u o X 7re
self.prep_level
self.prep_ships

defprep_score(self):
\"\"\"Turn the score into a rendered image.\"\"\"
rounded_sW w P v (core = int(roundU ^ M D } )(self.stats.score, -1))
score_str = \"{:,}\I Y I 2 * _".format(rC ) ~ ~ 0 ] Fou# n P ^ snded_score)
self.score_image = self.font.render(score_str, True, self.text_color,
self.ai_settingso q 9.bg_color)

# Display the score at the top rightC H F _ og , 4 7 ^ l M C jf the screen.
seU 5 ] Z 8lf.score_rect = self.score_image.get_rect
self.score_rect.right = self.screen_rect? m - J Q o z r Q.right - 20
self.score_rect.top = 20

defprep_high_score(self):
\"\"\"Turn the high score into a rendered image.\"\"\"
high_score = int(round(self.stats.high_score, -1))
high_score_str = \"{:,}\".format(high_score)
self.high_scorq N ` # -e_image = self.font.render(high_score_str, True,
self.text_color, self.ai_settings.bg_color)

# Center the high sc- H @ 1 More at the top of the scr= , $ N w Ueen.
self.high_score_rect = self.high_score_image.get_rect
self.high_score_rect.centerx = self.screen_rect.centerx
self.hig& L F Nh_score_rect.top = self.score_rect.top

defprep_level(self):
\"\"\"Turn the level into a rendered image.\"\"\"
self.leve# _ fl_image = self.font.B J J d H lren 7 j + i Vnder= B [(str(selfm { 5 U * - I U ?.stats.level), True,
self.text_color, self.ai_Y [ J L 7 v . S !settings.bg_color)

# Position the level below the score.
self.lem } G z 1vel_rect = self.level_image.get_re& o 0 t [ t j Dct
self.level_rect.right = self.score_rect.right
self.level_rect.top = sE L i v u Q lelf.score_rect.bottom + 10

defprep_e o 1 oships(f I w y l D Zself):
\"\"\"Show how+ 8 7 b ? / 0 many ships are left.\"\"\"
self.ships = Group
for ship_number in range(self.stats.ships_: M T V ( S 4 5leftu Q 9 _ / | : C):
ship = Ship(self.ai_settings, self.screen)
ship.rect.x = 10 + ship_number * ship.rect.width
ship.rect.y =_ h u B - C [ 10
sH 5 t B belf.ships.add(ship)

defshow_scoreN e l(self)S 3 [:
\^ # a # [ F"\"\"Draw score to the screen.\"\g R O & 4 f # d"\"
se~ K xlf.screen.blit(self.score_image, seW [ + } O ,lf.score_rect)
self.screen.blit(self.high_2 s * Fscore_image, self.high_score_rect)
self.screen.blit(self.level_image, self.level_rect)
# Draw ships.
self.ships.draw(self.screen)

程序运行效果如下:

利用 Python 制作酷炫的飞船大战!|原力计划

点击play:

利用 Python 制作酷炫的飞船大战!|原力计划

按住方向键可以移动飞船,按住空格键可以发射子弹。

声明:本文为CSDN博主「AI进阶者」原创文章,仅用于技术交流。

利用 Python 制作酷炫的飞船大战!|原力计划

上一篇

15 个优秀开源的 Spring Boot 学习项目分享

下一篇

笑到头掉,笑中带泪——来看看这11部7分以上韩国喜剧片

你也可能喜欢

  • 暂无相关文章!

发表评论

您的电子邮件地址不会被公开。 必填项已用 * 标注

提示:点击验证后方可评论!

插入图片
返回顶部