【问题标题】:Python game and trying to utilize pygame.mixer.Sound.play() to add sound effectsPython 游戏并尝试利用 pygame.mixer.Sound.play() 添加音效
【发布时间】:2022-10-15 04:49:45
【问题描述】:

首先,我是这个网站的新手,所以如果我做错了什么或不正确的事情,请随时说出来。我正在为一堂课用 PyCharm 编写游戏。游戏结束了,它可以工作了。当玩家进入房间(12 个房间)时,我还想为每个房间添加不同的音效。我可以利用 pygame 并且它可以工作。我的问题是我正在使用多维字典,无法弄清楚如何利用 pygame 播放字典中的声音片段(或者甚至可能)。我只会在下面放置部分代码。如果需要更多,请随时告诉我。

代码(部分):

"""  Scenario: Recall that the game requires players to type in a command line prompt to move through the different rooms and get items from each room. The game's goal is for the player to get all the items before encountering the room containing the villain. Each step of the game will require a text output to let the player know where they are in the game and an option of whether to obtain the item in each room. """

# -----------------------------

import time
import textwrap
from playsound import playsound
import pygame
pygame.mixer.pre_init()
pygame.mixer.init()


# load sound clips
creepy = pygame.mixer.Sound("creepy.wav")    # creepy music box
bees = pygame.mixer.Sound("bees.wav")    # bees flying
door = pygame.mixer.Sound("door.wav")    # door opening





  #    <skipped code>


def main():
    # format for the rooms ->  {effect (either a sound or a poem), description, available directional movements,
    # and item (if available).}

    rooms = {
    # starting point of the game
    'The U.S.S. Sulaco Central Console Realm': {
        'effect': 'You are hearing sounds of evil man laughing coming from all directions.',
        'effect2': 'seveneight.wav',
        'descr': 'You have just entered the \033[36mThe U.S.S. Sulaco Central Console Realm\033[00m. The Queen '
                 'has been laying her eggs early, hoping her facehugger alien children will hatch in time. So, '
                 'escape down one of the corridors! You can move \033[93mNorth\033[00m, \033[93mSouth\033[00m, '
                 '\033[93mEast\033[00m, or \033[93mWest\033[00m.',
        'North': 'Underground Florida Military Bunker Realm',
        'South': 'New York Realm',
        'East': 'Cabrini Green Warehouse Realm',
        'West': 'Blackhole 3'},

    'Underground Florida Military Bunker Realm': {
        'effect': 'Seven, eight, gonna stay up late...',
        'effect2': 'seveneight.wav',
        'descr': 'You have just entered the \033[36mUnderground Florida Military Bunker Realm\033[00m. The horde '
                 'of zombies has suddenly disappeared from the grounds around the underground bunker. However, '
                 'the scientists and soldiers are still reluctant to leave. Still, they are closing in on a cure '
                 'with these newly developed vaccines. You can move \033[93mSouth\033[00m, \033[93mEast\033[00m, '
                 'or \033[93mWest\033[00m.',
        'South': 'The U.S.S. Sulaco Central Console Realm',
        'East': 'Blackhole 1',
        'West': 'Morningside Cemetery Mausoleum Realm',
        'item': 'Hypnocil Shots'},
}




    #    <skipped code>




    # Check if the player enters a command to move to a new room
    if len(move) >= 2 and move[1] in rooms[current_room].keys():
        current_room = move_between_rooms(current_room, move[1], rooms)
        open_realm_door()
        time.sleep(4)
        print('\n{}'.format(rooms[current_room]['effect']))
        time.sleep(4)
        # open_realm_door()
        star_divider(25)
        print(textwrap.fill((rooms[current_room]['descr']), 100))
        **effect3 = (rooms[current_room]['effect2'])
        print(effect3)    # make sure the right sound clip is being passed
        pygame.init()
        pygame.mixer.Sound.play("effect3")**
        time.sleep(6)

        continue

   


    #    <skipped code>

我得到的错误是:

文件“D:\Documents\sounds\73ProjectTwoTextBasedGame.py”,第 423 行,在 main pygame.mixer.Sound.play("effect3") TypeError:“声音”对象的描述符“播放”不适用于“str”对象

【问题讨论】:

  • 您是否希望您的声音出现在字典中?如果是这样,您能否包括创建字典的代码。

标签: python-3.x pygame


【解决方案1】:

目前还不清楚你的意图是什么。但是根据错误消息和现有代码,问题看起来就像您希望有一个声音字典。

这样做的方法是将声音效果名称作为键加载您的字典:

sound_effects = {}
for effect_name in [ "creepy.wav", "bees.wav", "door.wav" ]:  # and the rest
    basename = effect_name.split( '.' )[0]
    sound_effects[basename] = pygame.mixer.Sound( effect_name )

然后在代码的后面,您的播放应该可以工作:

pygame.mixer.Sound.play( sound_effects["creepy"] )

这样,您的游戏位置只需要存储他们想要播放的声音的名称。

或许将所有的声音播放封装到一个函数中会更好,这样处理&报告错误更方便:

def playSoundEffect( name ):
    global sound_effects

    if ( name not in sound_effects ):
        sys.stderr.write( "Request to play unknown sound effect [" + name + "]
" )
    else:
        pygame.mixer.Sound.play( sound_effects[name] )

将此应用于您现有的代码(注意:真的在这里猜)~

    effect3 = (rooms[current_room]['effect2'])
    print(effect3)    # make sure the right sound clip is being passed
    
    playSoundEffect( effect3 )
    time.sleep(6)

顺便说一句:您只需要在任何循环之外调用pygame.init() 一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多