51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

Python实战项目:外星人入侵(源码分享)

本文最后更新于 2024-09-02,文章内容可能已经过时。

来自高能用户++高峰君主++的投稿

效果展示 {#%E6%95%88%E6%9E%9C%E5%B1%95%E7%A4%BA}

准备工作 {#%E5%87%86%E5%A4%87%E5%B7%A5%E4%BD%9C}


首先,确保你有安装cfg的库和pygame的库,没有安装的看下安装方法


库的安装方法 {#%E5%BA%93%E7%9A%84%E5%AE%89%E8%A3%85%E6%96%B9%E6%B3%95}


首先,win+r,在运行框里输入cmd或者CMD,进入终端,输入以下两行代码


pip install pygame
pip install cfg


注:cfg容易安装错误,具体看报错,如有报错评论区留言,我会一一答复


科普小知识 {#%E7%A7%91%E6%99%AE%E5%B0%8F%E7%9F%A5%E8%AF%86}


1.凡是安装Python的第三方库,只需要输入pip install 库的名字(当然有一些特例)


2.凡是程序运行不起来,整体代码大部分报错,一般是没安装库,一个Python文件里面引用的库一般在开头:import 库的名字,检查这里有没有报错或者黄色下划线就好了,如果有,就用方法一安装库,如果没有,可能是自身代码的问题了


完整代码 {#%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81}


import os
import sys
import cfg
import random
import pygame
from modules import *

'''开始游戏'''
def startGame(screen):
clock = pygame.time.Clock()
# 加载字体
font = pygame.font.SysFont('arial', 18)
if not os.path.isfile('score'):
f = open('score', 'w')
f.write('0')
f.close()
with open('score', 'r') as f:
highest_score = int(f.read().strip())
# 敌方
enemies_group = pygame.sprite.Group()
for i in range(55):
if i \< 11:
enemy = enemySprite('small', i, cfg.WHITE, cfg.WHITE)
elif i \< 33:
enemy = enemySprite('medium', i, cfg.WHITE, cfg.WHITE)
else:
enemy = enemySprite('large', i, cfg.WHITE, cfg.WHITE)
enemy.rect.x = 85 + (i % 11) \* 50
enemy.rect.y = 120 + (i // 11) \* 45
enemies_group.add(enemy)
boomed_enemies_group = pygame.sprite.Group()
en_bullets_group = pygame.sprite.Group()
ufo = ufoSprite(color=cfg.RED)
# 我方
myaircraft = aircraftSprite(color=cfg.GREEN, bullet_color=cfg.WHITE)
my_bullets_group = pygame.sprite.Group()
# 用于控制敌方位置更新
# --移动一行
enemy_move_count = 24
enemy_move_interval = 24
enemy_move_flag = False
# --改变移动方向(改变方向的同时集体下降一次)
enemy_change_direction_count = 0
enemy_change_direction_interval = 60
enemy_need_down = False
enemy_move_right = True
enemy_need_move_row = 6
enemy_max_row = 5
# 用于控制敌方发射子弹
enemy_shot_interval = 100
enemy_shot_count = 0
enemy_shot_flag = False
# 游戏进行中
running = True
is_win = False
# 主循环
while running:
screen.fill(cfg.BLACK)
for event in pygame.event.get():
# --点右上角的X或者按Esc键退出游戏
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
# --射击
if event.type == pygame.MOUSEBUTTONDOWN:
my_bullet = myaircraft.shot()
if my_bullet:
my_bullets_group.add(my_bullet)
# --我方子弹与敌方/UFO碰撞检测
for enemy in enemies_group:
if pygame.sprite.spritecollide(enemy, my_bullets_group, True, None):
boomed_enemies_group.add(enemy)
enemies_group.remove(enemy)
myaircraft.score += enemy.reward
if pygame.sprite.spritecollide(ufo, my_bullets_group, True, None):
ufo.is_dead = True
myaircraft.score += ufo.reward
# --更新并画敌方
# ----敌方子弹
enemy_shot_count += 1
if enemy_shot_count \> enemy_shot_interval:
enemy_shot_flag = True
enemies_survive_list = \[enemy.number for enemy in enemies_group\]
shot_number = random.choice(enemies_survive_list)
enemy_shot_count = 0
# ----敌方移动
enemy_move_count += 1
if enemy_move_count \> enemy_move_interval:
enemy_move_count = 0
enemy_move_flag = True
enemy_need_move_row -= 1
if enemy_need_move_row == 0:
enemy_need_move_row = enemy_max_row
enemy_change_direction_count += 1
if enemy_change_direction_count \> enemy_change_direction_interval:
enemy_change_direction_count = 1
enemy_move_right = not enemy_move_right
enemy_need_down = True
# ----每次下降提高移动和射击速度
enemy_move_interval = max(15, enemy_move_interval-3)
enemy_shot_interval = max(50, enemy_move_interval-10)
# ----遍历更新
for enemy in enemies_group:
if enemy_shot_flag:
if enemy.number == shot_number:
en_bullet = enemy.shot()
en_bullets_group.add(en_bullet)
if enemy_move_flag:
if enemy.number in range((enemy_need_move_row-1)11, enemy_need_move_row11):
if enemy_move_right:
enemy.update('right', cfg.SCREENSIZE\[1\])
else:
enemy.update('left', cfg.SCREENSIZE\[1\])
else:
enemy.update(None, cfg.SCREENSIZE\[1\])
if enemy_need_down:
if enemy.update('down', cfg.SCREENSIZE\[1\]):
running = False
is_win = False
enemy.change_count -= 1
enemy.draw(screen)
enemy_move_flag = False
enemy_need_down = False
enemy_shot_flag = False
# ----敌方爆炸特效
for boomed_enemy in boomed_enemies_group:
if boomed_enemy.boom(screen):
boomed_enemies_group.remove(boomed_enemy)
del boomed_enemy
# --敌方子弹与我方飞船碰撞检测
if not myaircraft.one_dead:
if pygame.sprite.spritecollide(myaircraft, en_bullets_group, True, None):
myaircraft.one_dead = True
if myaircraft.one_dead:
if myaircraft.boom(screen):
myaircraft.resetBoom()
myaircraft.num_life -= 1
if myaircraft.num_life \< 1:
running = False
is_win = False
else:
# ----更新飞船
myaircraft.update(cfg.SCREENSIZE\[0\])
# ----画飞船
myaircraft.draw(screen)
if (not ufo.has_boomed) and (ufo.is_dead):
if ufo.boom(screen):
ufo.has_boomed = True
else:
# ----更新UFO
ufo.update(cfg.SCREENSIZE\[0\])
# ----画UFO
ufo.draw(screen)
# --画我方飞船子弹
for bullet in my_bullets_group:
if bullet.update():
my_bullets_group.remove(bullet)
del bullet
else:
bullet.draw(screen)
# --画敌方子弹
for bullet in en_bullets_group:
if bullet.update(cfg.SCREENSIZE\[1\]):
en_bullets_group.remove(bullet)
del bullet
else:
bullet.draw(screen)
if myaircraft.score \> highest_score:
highest_score = myaircraft.score
# --得分每增加2000我方飞船增加一条生命
if (myaircraft.score % 2000 == 0) and (myaircraft.score \> 0) and (myaircraft.score != myaircraft.old_score):
myaircraft.old_score = myaircraft.score
myaircraft.num_life = min(myaircraft.num_life + 1, myaircraft.max_num_life)
# --敌人都死光了的话就胜利了
if len(enemies_group) \< 1:
is_win = True
running = False
# --显示文字
# ----当前得分
showText(screen, 'SCORE: ', cfg.WHITE, font, 200, 8)
showText(screen, str(myaircraft.score), cfg.WHITE, font, 200, 24)
# ----敌人数量
showText(screen, 'ENEMY: ', cfg.WHITE, font, 370, 8)
showText(screen, str(len(enemies_group)), cfg.WHITE, font, 370, 24)
# ----历史最高分
showText(screen, 'HIGHEST: ', cfg.WHITE, font, 540, 8)
showText(screen, str(highest_score), cfg.WHITE, font, 540, 24)
# ----FPS
showText(screen, 'FPS: ' + str(int(clock.get_fps())), cfg.RED, font, 8, 8)
# --显示剩余生命值
showLife(screen, myaircraft.num_life, cfg.GREEN)
pygame.display.update()
clock.tick(cfg.FPS)
with open('score', 'w') as f:
f.write(str(highest_score))
return is_win


'''主函数'''
def main():
# 初始化
pygame.init()
pygame.display.set_caption('外星人入侵 ------ 九歌')
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.mixer.init()
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
while True:
is_win = startGame(screen)
endInterface(screen, cfg.BLACK, is_win)

`'''run'''
if `name` == '`main`':
main()`



最后 {#%E6%9C%80%E5%90%8E}


那么完整代码写完后就可以双击运行代码啦,如果有报错记得按我说的方法排查一下!

如果实在是cfg安装不上或者有BUG解决不了,请访问下面这个链接下载完整项目:(GITHUB在国内可能被墙,如遇此情况请过一会儿再刷新GitHub页面试试) {#%E5%A6%82%E6%9E%9C%E5%AE%9E%E5%9C%A8%E6%98%AFcfg%E5%AE%89%E8%A3%85%E4%B8%8D%E4%B8%8A%E6%88%96%E8%80%85%E6%9C%89bug%E8%A7%A3%E5%86%B3%E4%B8%8D%E4%BA%86%EF%BC%8C%E8%AF%B7%E8%AE%BF%E9%97%AE%E4%B8%8B%E9%9D%A2%E8%BF%99%E4%B8%AA%E9%93%BE%E6%8E%A5%E4%B8%8B%E8%BD%BD%E5%AE%8C%E6%95%B4%E9%A1%B9%E7%9B%AE%EF%BC%9A%EF%BC%88github%E5%9C%A8%E5%9B%BD%E5%86%85%E5%8F%AF%E8%83%BD%E8%A2%AB%E5%A2%99%EF%BC%8C%E5%A6%82%E9%81%87%E6%AD%A4%E6%83%85%E5%86%B5%E8%AF%B7%E8%BF%87%E4%B8%80%E4%BC%9A%E5%84%BF%E5%86%8D%E5%88%B7%E6%96%B0github%E9%A1%B5%E9%9D%A2%E8%AF%95%E8%AF%95%EF%BC%89}

https://github.com/gfjz/alien-invasion


感谢你们的阅读?


赞(2)
未经允许不得转载:工具盒子 » Python实战项目:外星人入侵(源码分享)