首頁 > 軟體

基於Python實現射擊小遊戲的製作

2022-04-06 13:01:12

1.遊戲畫面

1.1開始

1.2射擊怪物

2.涉及知識點

1.sprites

2.pygame混音器

3.圖章   

4.python基礎語法

3.程式碼

3.1發射聲

from sprites import *
try:
    import pygame    
    pygame.mixer.init()
    fire_sound = pygame.mixer.Sound("audio/發射聲.wav")
    cricket_sound = pygame.mixer.Sound('audio/cricket.wav')
except:
    import sys
    input("本程式需要pygame混音器支援以便配音,請先在cmd下用pip install pygame安裝此模組。")

3.2背景

width,height = 480,360
screen = Screen()
screen.bgpic('res/ghosthouse.jpg')
screen.setup(width,height)

batimages = ['res/bat1.png','res/bat2.png']
batindex = 0
bat = Sprite(visible=False,pos=(-50-width//2,100))
bat.dx = 3
bat.dy = 0
bat.alive = True
bat.show()

3.3射擊效果

def bat_alt_costume():
    global batindex
    batindex = 1 - batindex
    bat.shape(batimages[batindex])
    screen.ontimer(bat_alt_costume,90)
bat_alt_costume()    

hole = Sprite(shape='res/Bullet_Hole.png',visible=False)

m1 = Mouse(1)           # 滑鼠左鍵
m3 = Mouse(3)           # 滑鼠右鍵
clock = Clock()         # 時鐘物件 
start_stamp = False
while True:
    bat.move(bat.dx,bat.dy)

    # 掉到地面就蓋圖章,留下屍體
    if bat.ycor() < random.randint(-200,-100):
        bat.dx = 0
        bat.dy = 0
        bat.setheading(random.randint(1,360))
        bat.stamp()
        bat.reborn(-500-width//2,100,3,0,delay=2)
        bat.alive = True
        bat.setheading(0)
        
    # 蝙蝠碰到滑鼠指標並且按下了滑鼠左鍵       
    if bat.collide_mouse() and m1.down() and bat.alive:         
        bat.dy = -10                # 開始往下掉
        bat.alive = False
        try: cricket_sound.play()
        except:pass
        
    # 到了最右邊就到最左邊去重新開始
    if bat.xcor() > width//2 :
        bat.reborn(-500-width//2,100,3,0,delay=2)
        bat.alive = True
        bat.setheading(0)
    hole.goto(mouse_position())

    # 發射子彈,用蓋圖章留下彈洞,為防連續發射用了start_stamp變數
    if m1.down() and not start_stamp:
        hole.stamp()
        start_stamp = True
        try: fire_sound.play()
        except: pass
        
    # 鬆開按鍵後
    if not m1.down():start_stamp = False

    clock.tick(60)

4.經驗總結

利用python各種遊戲庫可以做任何小遊戲

到此這篇關於基於Python實現射擊小遊戲的製作的文章就介紹到這了,更多相關Python射擊遊戲內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com