拼夕夕版飞机大作战

简介: 拼夕夕版飞机大作战

14个py小游戏源代码分享第二弹

4拼夕夕版飞机大作战

import sys
import cfg
import pygame
from modules import *

'''游戏界面'''
def GamingInterface(num_player, screen):

# 初始化
pygame.mixer.music.load(cfg.SOUNDPATHS['Cool Space Music'])
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
explosion_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['boom'])
fire_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['shot'])
font = pygame.font.Font(cfg.FONTPATH, 20)
# 游戏背景图
bg_imgs = [cfg.IMAGEPATHS['bg_big'], cfg.IMAGEPATHS['seamless_space'], cfg.IMAGEPATHS['space3']]
bg_move_dis = 0
bg_1 = pygame.image.load(bg_imgs[0]).convert()
bg_2 = pygame.image.load(bg_imgs[1]).convert()
bg_3 = pygame.image.load(bg_imgs[2]).convert()
# 玩家, 子弹和小行星精灵组
player_group = pygame.sprite.Group()
bullet_group = pygame.sprite.Group()
asteroid_group = pygame.sprite.Group()
# 产生小行星的时间间隔
asteroid_ticks = 90
for i in range(num_player):
    player_group.add(Ship(i+1, cfg))
clock = pygame.time.Clock()
# 分数
score_1, score_2 = 0, 0
# 游戏主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    # --玩家一: ↑↓←→控制, j射击; 玩家二: wsad控制, 空格射击
    pressed_keys = pygame.key.get_pressed()
    for idx, player in enumerate(player_group):
        direction = None
        if idx == 0:
            if pressed_keys[pygame.K_UP]:
                direction = 'up'
            elif pressed_keys[pygame.K_DOWN]:
                direction = 'down'
            elif pressed_keys[pygame.K_LEFT]:
                direction = 'left'
            elif pressed_keys[pygame.K_RIGHT]:
                direction = 'right'
            if direction:
                player.move(direction)
            if pressed_keys[pygame.K_j]:
                if player.cooling_time == 0:
                    fire_sound.play()
                    bullet_group.add(player.shot())
                    player.cooling_time = 20
        elif idx == 1:
            if pressed_keys[pygame.K_w]:
                direction = 'up'
            elif pressed_keys[pygame.K_s]:
                direction = 'down'
            elif pressed_keys[pygame.K_a]:
                direction = 'left'
            elif pressed_keys[pygame.K_d]:
                direction = 'right'
            if direction:
                player.move(direction)
            if pressed_keys[pygame.K_SPACE]:
                if player.cooling_time == 0:
                    fire_sound.play()
                    bullet_group.add(player.shot())
                    player.cooling_time = 20
        if player.cooling_time > 0:
            player.cooling_time -= 1
    if (score_1 + score_2) < 500:
        background = bg_1
    elif (score_1 + score_2) < 1500:
        background = bg_2
    else:
        background = bg_3
    # --向下移动背景图实现飞船向上移动的效果
    screen.blit(background, (0, -background.get_rect().height + bg_move_dis))
    screen.blit(background, (0, bg_move_dis))
    bg_move_dis = (bg_move_dis + 2) % background.get_rect().height
    # --生成小行星
    if asteroid_ticks == 0:
        asteroid_ticks = 90
        asteroid_group.add(Asteroid(cfg))
    else:
        asteroid_ticks -= 1
    # --画飞船
    for player in player_group:
        if pygame.sprite.spritecollide(player, asteroid_group, True, None):
            player.explode_step = 1
            explosion_sound.play()
        elif player.explode_step > 0:
            if player.explode_step > 3:
                player_group.remove(player)
                if len(player_group) == 0:
                    return
            else:
                player.explode(screen)
        else:
            player.draw(screen)
    # --画子弹
    for bullet in bullet_group:
        bullet.move()
        if pygame.sprite.spritecollide(bullet, asteroid_group, True, None):
            bullet_group.remove(bullet)
            if bullet.player_idx == 1:
                score_1 += 1
            else:
                score_2 += 1
        else:
            bullet.draw(screen)
    # --画小行星
    for asteroid in asteroid_group:
        asteroid.move()
        asteroid.rotate()
        asteroid.draw(screen)
    # --显示分数
    score_1_text = '玩家一得分: %s' % score_1
    score_2_text = '玩家二得分: %s' % score_2
    text_1 = font.render(score_1_text, True, (0, 0, 255))
    text_2 = font.render(score_2_text, True, (255, 0, 0))
    screen.blit(text_1, (2, 5))
    screen.blit(text_2, (2, 35))
    # --屏幕刷新
    pygame.display.update()
    clock.tick(60)

'''主函数'''
def main():

pygame.init()
pygame.font.init()
pygame.mixer.init()
scre

5打地鼠:

源代码分享:

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

'''游戏初始化'''
def initGame():

pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('打地鼠 —— 九歌')
return screen

'''主函数'''
def main():

# 初始化
screen = initGame()
# 加载背景音乐和其他音效
pygame.mixer.music.load(cfg.BGM_PATH)
pygame.mixer.music.play(-1)
audios = {
    'count_down': pygame.mixer.Sound(cfg.COUNT_DOWN_SOUND_PATH),
    'hammering': pygame.mixer.Sound(cfg.HAMMERING_SOUND_PATH)
}
# 加载字体
font = pygame.font.Font(cfg.FONT_PATH, 40)
# 加载背景图片
bg_img = pygame.image.load(cfg.GAME_BG_IMAGEPATH)
# 开始界面
startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)
# 地鼠改变位置的计时
hole_pos = random.choice(cfg.HOLE_POSITIONS)
change_hole_event = pygame.USEREVENT
pygame.time.set_timer(change_hole_event, 800)
# 地鼠
mole = Mole(cfg.MOLE_IMAGEPATHS, hole_pos)
# 锤子
hammer = Hammer(cfg.HAMMER_IMAGEPATHS, (500, 250))
# 时钟
clock = pygame.time.Clock()
# 分数
your_score = 0
flag = False
# 初始时间
init_time = pygame.time.get_ticks()
# 游戏主循环
while True:
    # --游戏时间为60s
    time_remain = round((61000 - (pygame.time.get_ticks() - init_time)) / 1000.)
    # --游戏时间减少, 地鼠变位置速度变快
    if time_remain == 40 and not flag:
        hole_pos = random.choice(cfg.HOLE_POSITIONS)
        mole.reset()
        mole.setPosition(hole_pos)
        pygame.time.set_timer(change_hole_event, 650)
        flag = True
    elif time_remain == 20 and flag:
        hole_pos = random.choice(cfg.HOLE_POSITIONS)
        mole.reset()
        mole.setPosition(hole_pos)
        pygame.time.set_timer(change_hole_event, 500)
        flag = False
    # --倒计时音效
    if time_remain == 10:
        audios['count_down'].play()
    # --游戏结束
    if time_remain < 0: break
    count_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE)
    # --按键检测
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEMOTION:
            hammer.setPosition(pygame.mouse.get_pos())
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                hammer.setHammering()
        elif event.type == change_hole_event:
            hole_pos = random.choice(cfg.HOLE_POSITIONS)
            mole.reset()
            mole.setPosition(hole_pos)
    # --碰撞检测
    if hammer.is_hammering and not mole.is_hammer:
        is_hammer = pygame.sprite.collide_mask(hammer, mole)
        if is_hammer:
            audios['hammering'].play()
            mole.setBeHammered()
            your_score += 10
    # --分数
    your_score_text = font.render('Score: '+str(your_score), True, cfg.BROWN)
    # --绑定必要的游戏元素到屏幕(注意顺序)
    screen.blit(bg_img, (0, 0))
    screen.blit(count_down_text, (875, 8))
    screen.blit(your_score_text, (800, 430))
    mole.draw(screen)
    hammer.draw(screen)
    # --更新
    pygame.display.flip()
    clock.tick(60)
# 读取最佳分数(try块避免第一次游戏无.rec文件)
try:
    best_score = int(open(cfg.RECORD_PATH).read())
except:
    best_score = 0
# 若当前分数大于最佳分数则更新最佳分数
if your_score > best_score:
    f = open(cfg.RECORD_PATH, 'w')
    f.write(str(your_score))
    f.close()
# 结束界面
score_info = {'your_score': your_score, 'best_score': best_score}
is_restart = endInterface(screen, cfg.GAME_END_IMAGEPATH, cfg.GAME_AGAIN_IMAGEPATHS, score_info, cfg.FONT_PATH, [cfg.WHITE, cfg.RED], cfg.SCREENSIZE)
return is_restart

'''run'''
if name == '__main__':

while True:
    is_restart = main()
    if not is_restart:
        break
目录
相关文章
|
6月前
拯救C盘大作战
拯救C盘大作战
|
安全 自动驾驶 物联网
AutoBot蔡亮:行车记录仪会成为汽车的眼睛 | 访谈
不清楚的状况。近日,雷科技(微信ID:leitech)就联系到了AutoBot(车车智能)的联合创始人,聊聊他们最新推出的车载智能硬件 AutoBot Eye 行车记录仪。
278 0
AutoBot蔡亮:行车记录仪会成为汽车的眼睛 | 访谈
|
安全
耗时3年,柬埔寨学生自制飞行汽车!10分钟最多飞行1公里,还是用的学校座椅
说到飞行汽车,不少人第一印象可能都会想到日本创业公司SkyDrive,此前根据朝日新闻报道,这款车最早可能会在2023年进行限购,2026年将实现量产。
137 0
耗时3年,柬埔寨学生自制飞行汽车!10分钟最多飞行1公里,还是用的学校座椅
飞机改装服务
本文研究全球及中国市场飞机改装服务现状及未来发展趋势,侧重分析全球及中国市场的主要企业,同时对比北美、欧洲、中国、日本、东南亚和印度等地区的现状及未来发展趋势
下一篇
无影云桌面