Python的pygame 打飞机之Dodger飞机大战

参考AI Sweigart的Dodger的基础游戏界面
增加了飞机的射击功能,和检测炮弹和敌人相撞.并将计分方式改为根据敌人的大小进行计分,如果大号敌人一个为10分,小号敌人一个为5分
素材在我其他上传的名为"飞机大战素材"里.

在这里插入图片描述

import pygame, random, sys
from pygame.locals import *

WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (0, 0, 0)
BACKGROUNDCOLOR = (255, 255, 255)
FPS = 60
BADDIEMINSIZE = 30
BADDIEMAXSIZE = 60
BADDIEMINSPEED = 1
BADDIEMAXSPEED = 7
ADDNEWBADDIERATE = 20
PLAYERMOVERATE = 5
PAODANSIZE=10


#中止程序
def terminate():
    pygame.quit()
    sys.exit()
#暂停程序
def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE: # Pressing ESC quits.
                    terminate()
                return
#检测玩家和敌人的碰撞
def playerHasHitBaddie(playerRect, baddies):
    for b in baddies:
        if playerRect.colliderect(b['rect']):
            return True
    return False

#检测炮弹和敌人的碰撞
def paodanHasHitBaddie(paodans, baddies,score):
    for paodan in paodans[:]:
        for b in baddies[:]:
            if paodan['rect'].colliderect(b['rect']):
                if b['rect'].width < (BADDIEMAXSIZE+BADDIEMINSIZE)/2 :
                    score += 5
                else:
                    score += 10
                paodans.remove(paodan)
                baddies.remove(b)

    return score

#将等分和其他文本绘制到屏幕上
def drawText(text, font, surface, x, y):
    textobj = font.render(text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (int(x), int(y))
    surface.blit(textobj, textrect)



# Set up pygame, the window, and the mouse cursor.
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Dodger')
pygame.mouse.set_visible(False)

# Set up the fonts.
font = pygame.font.SysFont(None, 48)

# Set up sounds.
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')

# Set up images.
playerImage = pygame.image.load('player.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('baddie.png')
paodanImage =pygame.image.load('paodan.jpg')

def send_paodan(x,y,paodans):
    newPaodan = {
        'rect': pygame.Rect(x,y,PAODANSIZE, PAODANSIZE),
        'speed': 10,
        'surface': pygame.transform.scale(paodanImage, (PAODANSIZE, PAODANSIZE)),
        }
    paodans.append(newPaodan)

# Show the "Start" screen.
windowSurface.fill(BACKGROUNDCOLOR)
drawText('Dodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()

topScore = 0
while True:
    # Set up the start of the game.
    baddies = []
    paodans = []
    score = 0
    playerRect.topleft = (WINDOWWIDTH // 2, WINDOWHEIGHT - 50)
    moveLeft = moveRight = moveUp = moveDown = False
    reverseCheat = slowCheat = False
    baddieAddCounter = 0
    pygame.mixer.music.play(-1, 0.0)

    while True: # The game loop runs while the game part is playing.


        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()

            if event.type == KEYDOWN:
                if event.key == K_z:
                    reverseCheat = True
                if event.key == K_x:
                    slowCheat = True
                if event.key == K_LEFT or event.key == K_a:
                    moveRight = False
                    moveLeft = True
                if event.key == K_RIGHT or event.key == K_d:
                    moveLeft = False
                    moveRight = True
                if event.key == K_UP or event.key == K_w:
                    moveDown = False
                    moveUp = True
                if event.key == K_DOWN or event.key == K_s:
                    moveUp = False
                    moveDown = True
                if event.key ==K_SPACE:
                    send_paodan(playerRect.centerx,playerRect.centery,paodans)

            if event.type == KEYUP:
                if event.key == K_z:
                    reverseCheat = False
                    #score = 0
                if event.key == K_x:
                    slowCheat = False
                    #score = 0
                if event.key == K_ESCAPE:
                        terminate()

                if event.key == K_LEFT or event.key == K_a:
                    moveLeft = False
                if event.key == K_RIGHT or event.key == K_d:
                    moveRight = False
                if event.key == K_UP or event.key == K_w:
                    moveUp = False
                if event.key == K_DOWN or event.key == K_s:
                    moveDown = False

            if event.type == MOUSEMOTION:
                # If the mouse moves, move the player where to the cursor.
                playerRect.centerx = event.pos[0]
                playerRect.centery = event.pos[1]
        # Add new baddies at the top of the screen, if needed.
        if not reverseCheat and not slowCheat:
            baddieAddCounter += 1
        if baddieAddCounter == ADDNEWBADDIERATE:
            baddieAddCounter = 0
            baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
            newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH - baddieSize), 0 - baddieSize, baddieSize, baddieSize),
                        'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
                        'surface':pygame.transform.scale(baddieImage, (baddieSize, baddieSize)),
                        }

            baddies.append(newBaddie)

        # Move the player around.
        if moveLeft and playerRect.left > 0:
            playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
        if moveRight and playerRect.right < WINDOWWIDTH:
            playerRect.move_ip(PLAYERMOVERATE, 0)
        if moveUp and playerRect.top > 0:
            playerRect.move_ip(0, -1 * PLAYERMOVERATE)
        if moveDown and playerRect.bottom < WINDOWHEIGHT:
            playerRect.move_ip(0, PLAYERMOVERATE)



        # Move the baddies down.
        for b in baddies:
            if not reverseCheat and not slowCheat:
                b['rect'].move_ip(0, b['speed'])
            elif reverseCheat:
                b['rect'].move_ip(0, -5)
            elif slowCheat:
                b['rect'].move_ip(0, 1)

        # Delete baddies that have fallen past the bottom.
        for b in baddies[:]:
            if b['rect'].top > WINDOWHEIGHT:
                baddies.remove(b)

        for paodan in paodans:
            if not reverseCheat and not slowCheat:
                paodan['rect'].move_ip(0, -paodan['speed'])
        for paodan in paodans[:]:
            if paodan['rect'].bottom <=4:
                paodans.remove(paodan)

        score = paodanHasHitBaddie(paodans, baddies, score)


        # Draw the game world on the window.
        windowSurface.fill(BACKGROUNDCOLOR)

        # Draw the score and top score.
        drawText('Score: %s' % (score), font, windowSurface, 10, 0)
        drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)

        # Draw the player's rectangle.
        windowSurface.blit(playerImage, playerRect)

        # Draw each baddie.
        for b in baddies:
            windowSurface.blit(b['surface'], b['rect'])

        for paodan in paodans:
            windowSurface.blit(paodan['surface'], paodan['rect'])

        pygame.display.update()

        # Check if any of the baddies have hit the player.
        if playerHasHitBaddie(playerRect, baddies):
            if score > topScore:
                topScore = score # set new top score
            break

        mainClock.tick(FPS)

    # Stop the game and show the "Game Over" screen.
    pygame.mixer.music.stop()
    gameOverSound.play()

    drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
    drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
    pygame.display.update()
    waitForPlayerToPressKey()

    gameOverSound.stop()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
嗨!对于Python飞机大战游戏,你可以使用Pygame库来进行开发。Pygame是一个用于开发2D游戏的Python库,提供了丰富的功能和工具来创建游戏。 下面是一个简单的示例代码,展示了如何使用Pygame创建一个飞机大战游戏: ```python import pygame import random # 初始化游戏 pygame.init() # 设置游戏窗口大小 screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("飞机大战") # 加载背景图像 background = pygame.image.load("background.jpg") # 加载玩家飞机图像 player_img = pygame.image.load("player.png") player_width = 50 player_height = 50 player_x = screen_width // 2 - player_width // 2 player_y = screen_height - player_height - 10 # 加载敌机图像 enemy_img = pygame.image.load("enemy.png") enemy_width = 50 enemy_height = 50 enemy_x = random.randint(0, screen_width - enemy_width) enemy_y = 0 enemy_speed = 5 # 游戏主循环 running = True while running: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 绘制背景 screen.blit(background, (0, 0)) # 绘制玩家飞机 screen.blit(player_img, (player_x, player_y)) # 绘制敌机 screen.blit(enemy_img, (enemy_x, enemy_y)) enemy_y += enemy_speed # 更新屏幕 pygame.display.flip() # 退出游戏 pygame.quit() ``` 这只是一个基本的示例,你可以根据自己的需求进行扩展和修改。你需要准备好背景图像、玩家飞机图像和敌机图像,并将其放在与代码相同的文件夹下。 当然,你可以根据自己的需求添加更多功能,例如玩家飞机的移动、子弹射击、敌机的生成与碰撞检测等等。祝你编写出一个有趣的飞机大战游戏!如果你还有其他问题,欢迎继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值