Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.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 Pygame:声音只播放8次,然后关闭4次,然后打开,然后关闭,然后重新打开_Python_Audio_Pygame - Fatal编程技术网

Python Pygame:声音只播放8次,然后关闭4次,然后打开,然后关闭,然后重新打开

Python Pygame:声音只播放8次,然后关闭4次,然后打开,然后关闭,然后重新打开,python,audio,pygame,Python,Audio,Pygame,我有一个奇怪的现象,我的声音文件播放8次,然后关闭,然后播放,然后关闭,然后再次播放 import sys, pygame, os, time # Force static position of screen os.environ['SDL_VIDEO_CENTERED'] = '1' # to get rid of sound lag pygame.mixer.pre_init(44100, -16, 8, 2048) # Runs imported module pygame.ini

我有一个奇怪的现象,我的声音文件播放8次,然后关闭,然后播放,然后关闭,然后再次播放

import sys, pygame, os, time

# Force static position of screen
os.environ['SDL_VIDEO_CENTERED'] = '1'

# to get rid of sound lag
pygame.mixer.pre_init(44100, -16, 8, 2048)

# Runs imported module
pygame.init()

# Constants
UP = 'up'
DOWN = 'down'
BOOSTSP = 12
NORMSP = 8

WIN_W = 920
WIN_H = 570
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

PADDLE_HEIGHT = 440
BALL_WIDTH = BALL_HEIGHT = 20

class Entity(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

class Paddle(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.x = x
        self.y = y
        self.speed = 8
        self.pWidth = 20
        self.score = 0
        self.pHeight = PADDLE_HEIGHT
        self.paddle = pygame.Surface((self.pWidth, self.pHeight))
        self.paddle = self.paddle.convert()
        self.lp_moveUP = self.lp_moveDOWN = self.rp_moveUP = self.rp_moveDOWN = False

    def update(self, down, up):
        # Adjust speed
        if up or down or up or down:
            if up:
                self.y -= self.speed
            if down:
                self.y += self.speed

        # paddle movement
        if self.y < 0:
            self.y = 0
        if self.y > WIN_H - self.pHeight:
            self.y = WIN_H - self.pHeight

class Ball(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.speed = [-5, -5]
        self.ball = pygame.Surface((BALL_WIDTH, BALL_HEIGHT))
        self.ball = self.ball.convert()
        self.rect = pygame.Rect(WIN_W/2, WIN_H/2-(BALL_HEIGHT/2), BALL_WIDTH, BALL_HEIGHT)

    def restart(self, lPaddle, rPaddle, screen):
        time.sleep(2)
        self.rect.y = WIN_H/2-(BALL_HEIGHT/2)
        self.rect.x = WIN_W/2
        lPaddle.y = (WIN_H/2) - (PADDLE_HEIGHT/2)
        rPaddle.y = (WIN_H/2) - (PADDLE_HEIGHT/2)

        return True
导入系统、pygame、os、时间
#屏幕的静态位置
os.environ['SDL\u VIDEO\u CENTERED']=“1”
#消除声音滞后
pygame.mixer.pre_init(44100,-16,82048)
#运行导入的模块
pygame.init()
#常数
向上=‘向上’
向下=‘向下’
BOOSTSP=12
NORMSP=8
温W=920
WIN_H=570
黑色=(0,0,0)
白色=(255,255,255)
桨叶高度=440
球头宽度=球头高度=20
类实体(pygame.sprite.sprite):
定义初始化(自):
pygame.sprite.sprite.\uuuuu init\uuuuuuu(自我)
类桨(实体):
定义初始化(self,x,y):
实体。u u初始化(自)
self.x=x
self.y=y
自身速度=8
self.pWidth=20
self.score=0
self.pHeight=桨叶高度
self.patle=pygame.Surface((self.pWidth,self.pHeight))
self.paile=self.paile.convert()
self.lp\u moveUP=self.lp\u moveDOWN=self.rp\u moveUP=self.rp\u moveDOWN=False
def更新(自我、向下、向上):
#调速
如果向上或向下或向上或向下:
如果出现以下情况:
self.y-=自速度
如果关闭:
self.y+=自速度
#桨叶运动
如果self.y<0:
self.y=0
如果self.y>WIN_H-self.pHeight:
self.y=WIN_H-self.pHeight
类球(实体):
定义初始化(self,x,y):
实体。u u初始化(自)
self.speed=[-5,-5]
self.ball=pygame.Surface((球的宽度、高度))
self.ball=self.ball.convert()
self.rect=pygame.rect(赢W/2,赢H/2-(球高/2),球宽,球高)
def重启(self、lPaddle、rPaddle、screen):
时间。睡眠(2)
自校正y=WIN_H/2-(球高度/2)
self.rect.x=WIN_W/2
lpadle.y=(WIN_H/2)-(桨高/2)
rPaddle.y=(WIN_H/2)-(桨高/2)
返回真值
请注意,在“更新”方法中,如果球碰到球拍,我会播放声音。您可以看到,我打印了“playSound”函数的返回值,它是play()方法的返回值

def更新(self、lPaddle、rPaddle、sound、playSound):
#如果球击中顶部或底部
如果self.rect.top<0或self.rect.top>WIN\u H-球的高度:
自速度[1]=-自速度[1]
打印播放声音(声音[“bop”],1)
#如果球碰到球拍
如果(自身速度[0]<0):
如果(self.rect.left>lPaddle.x+lPaddle.pWidth-15和self.rect.leftlPaddle.y和self.rect.top<(lPaddle.y+lPaddle.pHeight)):
自速度[0]=-自速度[0]
打印播放声音(声音[“嘟嘟”],1)
其他:
如果(self.rect.left>rPaddle.x-15和self.rect.leftrPaddle.y和self.rect.top<(rPaddle.y+rPaddle.pHeight)):
自速度[0]=-自速度[0]
打印播放声音(声音[“嘟嘟”],1)
self.rect=self.rect.move(self.speed)
#返回True持续.5秒,然后返回False持续.5秒。
def检查时间(当前、beg):
返回值(当前值)%1000<500
#接受字符串,(x,y)和大小。返回文本和矩形。
def txtRect(sen、XPO、YPO、大小):
phrase=pygame.font.font(无,大小)
短语=短语.渲染(森,1,黑色)
phraseRect=phrase.get_rect()
phraseRect.x=xpos
phraseRect.y=ypos
返回短语
#加载声音文件
def播放声音(声音、音量):
声音。设置音量(音量)
返回声音。播放()
#加载声音文件
def loadSound():
声音={}
sound[“beep”]=pygame.mixer.sound(“sound/beep.ogg”)
sound[“boom”]=pygame.mixer.sound(“sound/boom.ogg”)
sound[“bop”]=pygame.mixer.sound(“sound/bop.ogg”)
sound[“choose”]=pygame.mixer.sound(“sound/choose.ogg”)
sound[“count”]=pygame.mixer.sound(“sound/count.ogg”)
sound[“end”]=pygame.mixer.sound(“sound/end.ogg”)
sound[“music”]=pygame.mixer.sound(“sound/music.ogg”)
sound[“select”]=pygame.mixer.sound(“sound/select.ogg”)
回音
def main():
大小=赢W,赢H
fps=60
#用于倒计时
倒计时=3
减量=真
pygame.display.set_标题('Pong')
screen=pygame.display.set_模式(大小,pygame.SRCALPHA)
#创建我们的对象
球=球((球宽/2)-(球宽/2),球高/2-(球高/2))
lPaddle=桨叶(桨叶W/15,(桨叶H/2)-(桨叶高度/2))
rPaddle=桨(桨宽1.1,(桨高2)-(桨高2))
#创建声音对象
声音=加载声音()
clock=pygame.time.clock()
beg\u time=pygame.time.get\u ticks()
输入=计数=播放=输出=真
lp\u moveUP=lp\u moveDOWN=rp\u moveDOWN=rp\u moveUP=False
而简介:
#打印背景
屏幕填充(白色)
#标题文本:Pong
text=txtRect(“Pong”,0,0,200)
text=txtRect(“Pong”,WIN_W/2-(text[1].width/2),WIN_H/4200)
screen.blit(文本[0],文本[1])
#闪烁文本:单击此处开始
text=txtRect(“-单击此处开始-”,0,0,50)
text=txtRect(“-单击此处开始-”,WIN_W/2-(text[1].width/2),WIN_H/1.7,50)
if checkTime(beg_time,pygame.time.get_ticks()):
screen.blit(文本[0],文本[1])
#检查是否按下了车窗退出按钮
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:sys.exit()
elif event.type==pygame.MOUSEBUTTONDOWN或pygame.key.get_pressed()[pygame.K_RETURN]!=0:
screen.blit(文本[0],文本[1])
pygame.display.flip()
播放声音(声音[“选择”],.3)
pygame.time.wait(1500)
简介=错误
#限制while循环每次迭代的帧数
时钟滴答声(fps)
    def update(self, lPaddle, rPaddle, sound, playSound):
        # If ball hits the top or bottom
        if self.rect.top < 0 or self.rect.top > WIN_H - BALL_HEIGHT:
            self.speed[1] = -self.speed[1]
            print playSound(sound["bop"], 1)

        # If ball hits paddle
        if(self.speed[0] < 0):
            if (self.rect.left > lPaddle.x + lPaddle.pWidth - 15 and self.rect.left < lPaddle.x + lPaddle.pWidth-10) and (self.rect.top > lPaddle.y and self.rect.top < (lPaddle.y + lPaddle.pHeight)):
                self.speed[0] = -self.speed[0]
                print playSound(sound["beep"], 1)
        else:
            if (self.rect.left > rPaddle.x - 15 and self.rect.left < rPaddle.x - 5) and (self.rect.top > rPaddle.y and self.rect.top < (rPaddle.y + rPaddle.pHeight)):
                self.speed[0] = -self.speed[0]
                print playSound(sound["beep"], 1)

        self.rect = self.rect.move(self.speed)


# Returns True for .5 seconds, then False for .5 seconds.
def checkTime(cur, beg):
    return (cur - beg) % 1000 < 500


# Takes in string, (x, y) and size. Returns text and rect.
def txtRect(sen, xpos, ypos, size):
    phrase = pygame.font.Font(None, size)
    phrase = phrase.render(sen, 1, BLACK)
    phraseRect = phrase.get_rect()
    phraseRect.x = xpos
    phraseRect.y = ypos

    return phrase, phraseRect


# Loads sound files
def playSound(sound, volume):
    sound.set_volume(volume)
    return sound.play()


# Loads sound files
def loadSound():
    sound = {}
    sound["beep"] = pygame.mixer.Sound("sound/beep.ogg")
    sound["boom"] = pygame.mixer.Sound("sound/boom.ogg")
    sound["bop"] = pygame.mixer.Sound("sound/bop.ogg")
    sound["choose"] = pygame.mixer.Sound("sound/choose.ogg")
    sound["count"] = pygame.mixer.Sound("sound/count.ogg")
    sound["end"] = pygame.mixer.Sound("sound/end.ogg")
    sound["music"] = pygame.mixer.Sound("sound/music.ogg")
    sound["select"] = pygame.mixer.Sound("sound/select.ogg")

    return sound


def main():
    size = WIN_W, WIN_H
    fps = 60

    # Used for count down
    countDown = 3
    decrement = True

    pygame.display.set_caption('Pong')
    screen = pygame.display.set_mode(size, pygame.SRCALPHA)

    # Create our objects
    ball = Ball((WIN_W/2)-(BALL_WIDTH/2), WIN_H/2-(BALL_HEIGHT/2))
    lPaddle = Paddle(WIN_W/15, (WIN_H/2)-(PADDLE_HEIGHT/2))
    rPaddle = Paddle(WIN_W/1.1, (WIN_H/2)-(PADDLE_HEIGHT/2))

    # Create sound objects
    sound = loadSound()

    clock = pygame.time.Clock()

    beg_time = pygame.time.get_ticks()
    intro = count = play = outro = True
    lp_moveUP = lp_moveDOWN = rp_moveDOWN = rp_moveUP = False

    while intro:
        # Print background
        screen.fill(WHITE)

        # Title Text: Pong
        text = txtRect("Pong", 0, 0, 200)
        text = txtRect("Pong", WIN_W/2-(text[1].width/2), WIN_H/4, 200)
        screen.blit(text[0], text[1])

        # Blinking Text: Click here to start
        text = txtRect("- Click here to start -", 0, 0, 50)
        text = txtRect("- Click here to start -", WIN_W/2-(text[1].width/2), WIN_H/1.7, 50)
        if checkTime(beg_time, pygame.time.get_ticks()):
            screen.blit(text[0], text[1])

        # Checks if window exit button pressed
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN or pygame.key.get_pressed()[pygame.K_RETURN] != 0:
                screen.blit(text[0], text[1])
                pygame.display.flip()
                playSound(sound["select"], .3)
                pygame.time.wait(1500)
                intro = False

        # Limits frames per iteration of while loop
        clock.tick(fps)
        # Writes to main surface
        pygame.display.flip()

    # Gameplay
    while play:
        # Print background
        screen.fill(WHITE)
        screen.blit(lPaddle.paddle, (lPaddle.x, lPaddle.y))
        screen.blit(rPaddle.paddle, (rPaddle.x, rPaddle.y))
        screen.blit(ball.ball, ball.rect)

        # Print Score
        sen = "Player 1 score: " + str(lPaddle.score)
        text = txtRect(sen, WIN_W/6.5, WIN_H/57, 40)
        screen.blit(text[0], text[1])
        sen = "Player 2 score: " + str(rPaddle.score)
        text = txtRect(sen, WIN_W - WIN_W/6.5 - text[1].width, WIN_H/57, 40)
        screen.blit(text[0], text[1])

        # Countdown
        if count:
            text = txtRect(str(countDown), 0, 0, 75)
            text = txtRect(str(countDown), WIN_W/3.5 - (text[1].width/2), WIN_H/4, 75)
            screen.blit(text[0], text[1])
            text = txtRect(str(countDown), WIN_W/1.4 - (text[1].width/2), WIN_H/4, 75)
            screen.blit(text[0], text[1])

            # Writes to main surface
            pygame.display.flip()

            playSound(sound["count"], 1)
            time.sleep(1)
            countDown -= 1

            # bug fix: prevent display of 0.
            if countDown == 0:
                count = False

        # Gameplay
        else:
            # Checks if window exit button pressed
            for event in pygame.event.get():
                if event.type == pygame.QUIT: sys.exit()

                # Keyboard mechanics
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        pygame.quit()
                        sys.exit()
                    if event.key == pygame.K_UP:
                        rp_moveUP = True
                        rp_moveDOWN = False

                    elif event.key == pygame.K_DOWN:
                        rp_moveUP = False
                        rp_moveDOWN = True
                    if event.key == pygame.K_w:
                        lp_moveUP = True
                        lp_moveDOWN = False

                    elif event.key == pygame.K_s:
                        lp_moveUP = False
                        lp_moveDOWN = True

                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_UP:
                        rp_moveUP = False
                    elif event.key == pygame.K_DOWN:
                        rp_moveDOWN = False
                    if event.key == pygame.K_w:
                        lp_moveUP = False
                    elif event.key == pygame.K_s:
                        lp_moveDOWN = False

            lPaddle.update(lp_moveDOWN, lp_moveUP)
            rPaddle.update(rp_moveDOWN, rp_moveUP)
            ball.update(lPaddle, rPaddle, sound, playSound)

            # If ball moves off the screen
            if ball.rect.left < 0 - ball.rect.width or ball.rect.left > WIN_W + ball.rect.width:
                if ball.rect.left < 0:
                    rPaddle.score += 1
                elif ball.rect.left > WIN_H + ball.rect.width:
                    lPaddle.score += 1
                playSound(sound["end"], 1)
                count = ball.restart(lPaddle, rPaddle, screen)
                countDown = 3

        # Game ends
        if lPaddle.score == 3 or rPaddle.score == 3:
            playSound(sound["boom"], 1)
            break

        # Limits frames per iteration of while loop
        clock.tick(fps)
        # Writes to main surface
        pygame.display.flip()

    # Gameplay
    while outro:
        # Print background
        screen.fill(WHITE)

        # End Text: Player wins
        if lPaddle.score == 3 or rPaddle.score == 3:
            if lPaddle.score == 3:
                sen = "Player 1 Wins!"
            else:
                sen = "Player 2 Wins!"

            text = txtRect(sen, 0, 0, 40)
            text = txtRect(sen, WIN_W/2-(text[1].width/2)-130, WIN_H/4, 100)

        screen.blit(text[0], text[1])

        text = txtRect("- Click here to continue -", 0, 0, 50)
        text = txtRect("- Click here to continue -", WIN_W/2-(text[1].width/2), WIN_H/1.7, 50)
        # Blinking Text: Click here to start
        if checkTime(beg_time, pygame.time.get_ticks()):
            screen.blit(text[0], text[1])

        # Checks if window exit button pressed
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN or pygame.key.get_pressed()[pygame.K_RETURN] != 0:
                screen.blit(text[0], (WIN_W/2-(text[1].width/2), WIN_H/1.7))
                pygame.display.flip()
                loadSound("choose", 1)
                pygame.time.wait(1500)
                outro = False
                main()

        # Limits frames per iteration of while loop
        clock.tick(fps)
        # Writes to main surface
        pygame.display.flip()

if __name__ == "__main__":
    main()