Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Match-3游戏-与比赛相关的声音_Python_Pygame - Fatal编程技术网

Python Match-3游戏-与比赛相关的声音

Python Match-3游戏-与比赛相关的声音,python,pygame,Python,Pygame,我想在pygame的第三场比赛中得到一些帮助。我加载了如下图像和声音,“宝石”将是经典元素空气、地球、火和水。例如,当3个或更多水精灵匹配时,如何播放适当的水声文件?不需要任何游戏代码的帮助,只需在图像和音频文件之间创建关联,以及如何“在匹配元素时”播放即可[]'. 多谢各位 # Directions UP = 'up' DOWN = 'down' LEFT = 'left' RIGHT = 'right' # Space to the sides of grid XMARGIN = int(

我想在pygame的第三场比赛中得到一些帮助。我加载了如下图像和声音,“宝石”将是经典元素空气、地球、火和水。例如,当3个或更多水精灵匹配时,如何播放适当的水声文件?不需要任何游戏代码的帮助,只需在图像和音频文件之间创建关联,以及如何“在匹配元素时”播放即可[]'. 多谢各位

# Directions
UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'

# Space to the sides of grid
XMARGIN = int((WIDTH - ELEMENTSIZE * GRIDWIDTH) / 2)
YMARGIN = int((HEIGHT - ELEMENTSIZE * GRIDHEIGHT) / 2)

EMPTY_SPACE = -1
ROWABOVEBOARD = 'row above board'

# Colours
AIR = pygame.Color(145, 129, 129)
FIRE = pygame.Color(255, 123, 0)
WATER = pygame.Color(93, 118, 245)
EARTH = pygame.Color(22, 136, 0)
ELECTRIC = pygame.Color(22, 204, 0)
SMOKE = pygame.Color(222, 222, 222)
ICE = pygame.Color(234, 231, 255)
METAL = pygame.Color(105, 105, 105)
BLOOD = pygame.Color(222, 7, 7)

# FPS controller
fpsController = pygame.time.Clock()

def main():
    global FPSCLOCK, BOARDRECTS, ELEMENTIMAGES, SOUNDS, PLAYSURF, BASICFONT

    # Basic set up
    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    PLAYSURF = pygame.display.set_mode((WIDTH, HEIGHT))
    BASICFONT = pygame.font.Font('freesansbold.ttf', 36)

    # Load images
    ELEMENTIMAGES = []
    for i in range(1, NUMELEMENTS+1):
        elementImage = pygame.image.load('element%s.jpg' % i)
        if elementImage.get_size() != (ELEMENTSIZE, ELEMENTSIZE):
            elementImage = pygame.transform.smoothscale(elementImage, (ELEMENTSIZE, ELEMENTSIZE))
        ELEMENTIMAGES.append(elementImage)

    # Load sounds
    SOUNDS = {}
    SOUNDS['bad swap'] = pygame.mixer.Sound('badswap.wav')
    SOUNDS['match'] = []
    for i in range(NUMMATCHSOUNDS):
        SOUNDS['match'].append(pygame.mixer.Sound('elementsound%s.wav' % i))

    # Rect objects for board space conversions
    BOARDRECTS = []
    for x in range(GRIDWIDTH):
        BOARDRECTS.append([])
        for y in range(GRIDHEIGHT):
            r = pygame.Rect((XMARGIN + (x * ELEMENTSIZE),
                             YMARGIN + (y * ELEMENTSIZE),
                             ELEMENTSIZE, ELEMENTSIZE))
            BOARDRECTS[x].append(r)

    while True:
        runGame()

def runGame():
    # Board initialisation
    gameBoard = getBlankBoard()
    score = 0
    fillBoardAndAnimate(gameBoard, [], score) # Drop initial elements

    # Initialise new game variables
    firstSelectedElement = None
    lastMouseDownX = None
    lastMouseDownY = None
    gameIsOver = False
    lastScoreDeduction = time.time()
    clickContinueTextSurf = None

    # Main game loop
    while True:
        clickedSpace = None
        for event in pygame.event.get(): # Event handling
            if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
            elif event.type == KEYUP and event.key == K_BACKSPACE:
                return # new game

            elif event.type == MOUSEBUTTONUP:
                if gameIsOver:
                    return # click to start new game

                if event.pos == (lastMouseDownX, lastMouseDownY):
                    clickedSpace = checkForElementClick(event.pos)
                else:
                    firstSelectedElement = checkForElementClick((lastMouseDownX, lastMouseDownY))
                    clickedSpace = checkForElementClick(event.pos)
                    if not firstSelectedElement or not clickedSpace:
                        firstSelectedElement = None
                        clickedSpace = None
            elif event.type == MOUSEBUTTONDOWN:
                lastMouseDownX, lastMouseDownY = event.pos

        if clickedSpace and not firstSelectedElement:
            firstSelectedElement = clickedSpace
        elif clickedSpace and firstSelectedElement:
            firstSwappingElement, secondSwappingElement = getSwappingElements(gameBoard, firstSelectedElement, clickedSpace)
            if firstSwappingElement == None and secondSwappingElement == None:
                # If both are None, elements are not adjacent
                firstSelectedElement = None
                continue

            # Swap animation
            boardCopy = getBoardCopyMinusElements(gameBoard, (firstSwappingElement, secondSwappingElement))
            animateMovingElements(boardCopy, [firstSwappingElement, secondSwappingElement], [], score)

            # Swap elements in the board
            gameBoard[firstSwappingElement['x']][firstSwappingElement['y']] = secondSwappingElement['imageNum']
            gameBoard[secondSwappingElement['x']][secondSwappingElement['y']] = firstSwappingElement['imageNum']

            # See if this is a match
            matchedElements = findMatchingElements(gameBoard)
            if matchedElements == []:
                # No match - swap back
                SOUNDS['bad swap'].play()
                animateMovingElements(boardCopy, [firstSwappingElement, secondSwappingElement], [], score)
                gameBoard[firstSwappingElement['x']][firstSwappingElement['y']] = firstSwappingElement['imageNum']
                gameBoard[secondSwappingElement['x']][secondSwappingElement['y']] = secondSwappingElement['imageNum']
            else:
                # A match
                scoreAdd = 0
                while matchedElements != []:
                    points = []
                    for elementSet in matchedElements:
                        scoreAdd += (10 + (len(elementSet) - 3) * 10)
                        for element in elementSet:
                            gameBoard[element[0]][element[1]] = EMPTY_SPACE
                        points.append({'points': scoreAdd,
                                       'x': element[0] * ELEMENTSIZE + XMARGIN,
                                       'y': element[1] * ELEMENTSIZE + YMARGIN})
                    score += scoreAdd

                    # Drop new elements
                    fillBoardAndAnimate(gameBoard, points, score)

                    # Check for new matches
                    matchedElements = findMatchingElements(gameBoard)
            firstSelectedElement = None

            if not canMakeMove(gameBoard):
                gameIsOver = True

        # Draw the board
        PLAYSURF.fill(BGCOLOUR)
        drawBoard(gameBoard)
        if firstSelectedElement != None:
            highlightSpace(firstSelectedElement['x'], firstSelectedElement['y'])
        if gameIsOver:
            if clickContinueTextSurf == None:
                clickContinueTextSurf = BASICFONT.render('Final Score: %s (Click to continue)' % (score), 1, GAMEOVERCOLOUR, GAMEOVERBGCOLOUR)
                clickContinueTextRect = clickContinueTextSurf.get_rect()
                clickContinueTextRect.center = int(WIDTH / 2), int(HEIGHT / 2)
            PLAYSURF.blit(clickContinueTextSurf, clickContinueTextRect)
        elif score > 0 and time.time() - lastScoreDeduction > DEDUCTSPEED:
            # score drops over time
            score -= 1
            lastScoreDeduction = time.time()
        drawScore(score)
        pygame.display.update()
        FPSCLOCK.tick(FPS)                

def getSwappingElements(board, firstXY, secondXY):
    # If the elements at the (X, Y) coordinates of the two elements are adjacent,
    # then their 'direction' keys are set to the appropriate direction
    # value to be swapped with each other.
    # Otherwise, (None, None) is returned.
    firstElement = {'imageNum': board[firstXY['x']][firstXY['y']],
                'x': firstXY['x'],
                'y': firstXY['y']}
    secondElement = {'imageNum': board[secondXY['x']][secondXY['y']],
                 'x': secondXY['x'],
                 'y': secondXY['y']}
    highlightedElement = None
    if firstElement['x'] == secondElement['x'] + 1 and firstElement['y'] == secondElement['y']:
        firstElement['direction'] = LEFT
        secondElement['direction'] = RIGHT
    elif firstElement['x'] == secondElement['x'] - 1 and firstElement['y'] == secondElement['y']:
        firstElement['direction'] = RIGHT
        secondElement['direction'] = LEFT
    elif firstElement['y'] == secondElement['y'] + 1 and firstElement['x'] == secondElement['x']:
        firstElement['direction'] = UP
        secondElement['direction'] = DOWN
    elif firstElement['y'] == secondElement['y'] - 1 and firstElement['x'] == secondElement['x']:
        firstElement['direction'] = DOWN
        secondElement['direction'] = UP
    else:
        # These elements are not adjacent and can't be swapped.
        return None, None
    return firstElement, secondElement

def getBlankBoard():
    # Create and return a blank board data structure.
    board = []
    for x in range(GRIDWIDTH):
        board.append([EMPTY_SPACE] * GRIDHEIGHT)
    return board

def canMakeMove(board):
    # Return True if the board is in a state where a matching
    # move can be made on it. Otherwise return False.

    # The patterns in oneOffPatterns represent elements that are configured
    # in a way where it only takes one move to make a triplet.
    oneOffPatterns = (((0,1), (1,0), (2,0)),
                      ((0,1), (1,1), (2,0)),
                      ((0,0), (1,1), (2,0)),
                      ((0,1), (1,0), (2,1)),
                      ((0,0), (1,0), (2,1)),
                      ((0,0), (1,1), (2,1)),
                      ((0,0), (0,2), (0,3)),
                      ((0,0), (0,1), (0,3)))

    # The x and y variables iterate over each space on the board.
    # If we use + to represent the currently iterated space on the
    # board, then this pattern: ((0,1), (1,0), (2,0))refers to identical
    # elements being set up like this:
    #
    #     +A
    #     B
    #     C
    #
    # That is, element A is offset from the + by (0,1), element B is offset
    # by (1,0), and element C is offset by (2,0). In this case, element A can
    # be swapped to the left to form a vertical three-in-a-row triplet.
    #
    # There are eight possible ways for the elements to be one move
    # away from forming a triple, hence oneOffPattern has 8 patterns.

    for x in range(GRIDWIDTH):
        for y in range(GRIDHEIGHT):
            for pat in oneOffPatterns:
                # check each possible pattern of "match in next move" to
                # see if a possible move can be made.
                if (getElementAt(board, x+pat[0][0], y+pat[0][1]) == \
                    getElementAt(board, x+pat[1][0], y+pat[1][1]) == \
                    getElementAt(board, x+pat[2][0], y+pat[2][1]) != None) or \
                   (getElementAt(board, x+pat[0][1], y+pat[0][0]) == \
                    getElementAt(board, x+pat[1][1], y+pat[1][0]) == \
                    getElementAt(board, x+pat[2][1], y+pat[2][0]) != None):
                    return True # return True the first time you find a pattern
    return False

def drawMovingElement(element, progress):
    # Draw an element sliding in the direction that its 'direction' key
    # indicates. The progress parameter is a number from 0 (just
    # starting) to 100 (slide complete).
    movex = 0
    movey = 0
    progress *= 0.01

    if element['direction'] == UP:
        movey = -int(progress * ELEMENTSIZE)
    elif element['direction'] == DOWN:
        movey = int(progress * ELEMENTSIZE)
    elif element['direction'] == RIGHT:
        movex = int(progress * ELEMENTSIZE)
    elif element['direction'] == LEFT:
        movex = -int(progress * ELEMENTSIZE)

    basex = element['x']
    basey = element['y']
    if basey == ROWABOVEBOARD:
        basey = -1

    pixelx = XMARGIN + (basex * ELEMENTSIZE)
    pixely = YMARGIN + (basey * ELEMENTSIZE)
    r = pygame.Rect( (pixelx + movex, pixely + movey, ELEMENTSIZE, ELEMENTSIZE) )
    PLAYSURF.blit(ELEMENTIMAGES[element['imageNum']], r)

def pullDownAllElements(board):
    # pulls down elements on the board to the bottom to fill in any gaps
    for x in range(GRIDWIDTH):
        elementsInColumn = []
        for y in range(GRIDHEIGHT):
            if board[x][y] != EMPTY_SPACE:
                elementsInColumn.append(board[x][y])
        board[x] = ([EMPTY_SPACE] * (GRIDHEIGHT - len(elementsInColumn))) + elementsInColumn

def getElementAt(board, x, y):
    if x < 0 or y < 0 or x >= GRIDWIDTH or y >= GRIDHEIGHT:
        return None
    else:
        return board[x][y]

def getDropSlots(board):
    # Creates a "drop slot" for each column and fills the slot with a
    # number of elements that that column is lacking. This function assumes
    # that the elements have been gravity dropped already.
    boardCopy = copy.deepcopy(board)
    pullDownAllElements(boardCopy)

    dropSlots = []
    for i in range(GRIDWIDTH):
        dropSlots.append([])

    # count the number of empty spaces in each column on the board
    for x in range(GRIDWIDTH):
        for y in range(GRIDHEIGHT-1, -1, -1): # start from bottom, going up
            if boardCopy[x][y] == EMPTY_SPACE:
                possibleElements = list(range(len(ELEMENTIMAGES)))
                for offsetX, offsetY in ((0, -1), (1, 0), (0, 1), (-1, 0)):
                    # Narrow down the possible elements we should put in the
                    # blank space so we don't end up putting an two of
                    # the same elements next to each other when they drop.
                    neighborElement = getElementAt(boardCopy, x + offsetX, y + offsetY)
                    if neighborElement != None and neighborElement in possibleElements:
                        possibleElements.remove(neighborElement)

                newElement = random.choice(possibleElements)
                boardCopy[x][y] = newElement
                dropSlots[x].append(newElement)
    return dropSlots
#说明
向上=‘向上’
向下=‘向下’
左=‘左’
右=‘右’
#网格两侧的空间
XMARGIN=int((宽度-元素大小*网格宽度)/2)
YMARGIN=int((高度-元素大小*网格高度)/2)
空_空间=-1
RowUpposboard=‘RowUpposboard’
#颜色
AIR=pygame.Color(145129129)
FIRE=pygame.Color(255、123、0)
水=pygame.颜色(93118245)
地球=pygame.Color(22136,0)
电气=pygame.颜色(22,204,0)
烟雾=pygame.Color(222222222222)
ICE=pygame.Color(23423155)
金属=pygame.颜色(105,105,105)
血=pygame.Color(222,7,7)
#FPS控制器
fpsController=pygame.time.Clock()
def main():
全球FPSCLOCK、BOARDRECTS、Element图像、声音、PLAYSURF、BASICFONT
#基本设置
pygame.init()
fpscall=pygame.time.Clock()
PLAYSURF=pygame.display.set_模式((宽度、高度))
BASICFONT=pygame.font.font('freesansbold.ttf',36)
#加载图像
ELEMENTIMAGES=[]
对于范围内的i(1,数值+1):
elementImage=pygame.image.load('元素%s.jpg'%1!')
if元素image.get_size()!=(ELEMENTSIZE,ELEMENTSIZE):
elementImage=pygame.transform.smoothscale(elementImage,(ELEMENTSIZE,ELEMENTSIZE))
ELEMENTIMAGES.append(elementImage)
#加载声音
声音={}
SOUNDS['bad swap']=pygame.mixer.Sound('badswap.wav'))
声音['match']=[]
对于范围内的i(NUMMATCHSOUNDS):
声音['match'].append(pygame.mixer.Sound('elementsound%s.wav'%i'))
#用于电路板空间转换的Rect对象
BOARDRECTS=[]
对于范围内的x(网格宽度):
BOARDRECTS.append([])
对于范围内的y(网格高度):
r=pygame.Rect((XMARGIN+(x*ELEMENTSIZE),
YMARGIN+(y*元素大小),
元素大小,元素大小)
BOARDRECTS[x]。追加(r)
尽管如此:
runGame()
def runGame():
#董事会初始化
gameBoard=getBlankBoard()
分数=0
填充板和动画(游戏板,[],分数)#删除初始元素
#初始化新的游戏变量
firstSelectedElement=None
lastMouseDownX=无
lastMouseDownY=无
gameIsOver=False
LastScoreDecretion=time.time()
单击ContinueTextSurf=None
#主游戏循环
尽管如此:
clickedSpace=无
对于pygame.event.get()中的事件:#事件处理
如果event.type==QUIT或(event.type==KEYUP和event.key==K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type==KEYUP和event.key==K_退格:
返回#新游戏
elif event.type==MOUSEBUTTONUP:
如果发生以下情况:
return#点击开始新游戏
如果event.pos==(lastMouseDownX,lastMouseDownY):
clickedSpace=checkForElementClick(event.pos)
其他:
firstSelectedElement=checkForElementClick((lastMouseDownX,lastMouseDownY))
clickedSpace=checkForElementClick(event.pos)
如果未首先选择元素或未单击空间:
firstSelectedElement=None
clickedSpace=无
elif event.type==MOUSEBUTTONDOWN:
lastMouseDownX,lastMouseDownY=event.pos
如果单击了空格而未首先选择元素:
firstSelectedElement=单击空间
elif单击空格并首先选择元素:
firstSwappingElement,secondSwappingElement=getSwappingElements(游戏板,firstSelectedElement,clickedSpace)
如果firstSwappingElement==无,而secondSwappingElement==无:
#如果两者均为“无”,则图元不相邻
firstSelectedElement=None
持续
#交换动画
boardCopy=getBoardCopyMinusElements(游戏板,(第一个交换元素,第二个交换元素))
animateMovingElements(boardCopy,[firstSwappingElement,secondSwappingElement],],score)
#交换板中的元素
游戏板[firstSwappingElement['x']][firstSwappingElement['y']]=secondSwappingElement['imageNum']
游戏板[secondSwappingElement['x']][secondSwappingElement['y']]=firstSwappingElement['imageNum']
#看看这是否匹配
matchedElements=findMatchingElements(游戏板)
如果匹配元素==[]:
#没有比赛-换回
声音[‘坏交换’].play()
animateMovingElements(boardCopy,[firstSwappingElement,secondSwappingElement],],score)
游戏板[firstSwappingElement['x']][firstSwappingElement['y']]=firstSwappingElement['imageNum']
游戏板[secondSwappingElement['x']][secondSwappingElement['y']]=secondSwappingElement['imageNum']
其他:
#火柴
scoreAdd=0
而匹配元素!=[]:
点数=[]
对于匹配元素中的元素集:
scoreAdd+=(10+(len(elementSet)-3)*10)
对于elementSet中的元素:
游戏板[元素[0]][元素[1]]=空白
points.append({'points':scoreAdd,
“x”:元素[0]*ELEMENTSIZE+XMARGIN,
“y”:
ELEMENT_SOUNDS = {
    'water': WATER_SOUND,
    'fire': FIRE_SOUND,
    }

board = [
    ['water', 'fire', 'water'],
    ['fire', 'water', 'fire'],
    ['water', 'water', 'water'],
    ]

if match:
    # Figure out the kind of the matching element 'water' in this case.
    element_kind = 'water'
    ELEMENT_SOUNDS[element_kind].play()