Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.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 鼠标悬停在对象上时的声音效果?_Python_Python 3.x_Pygame - Fatal编程技术网

Python 鼠标悬停在对象上时的声音效果?

Python 鼠标悬停在对象上时的声音效果?,python,python-3.x,pygame,Python,Python 3.x,Pygame,所以我尝试设置这个东西,每当玩家将鼠标“悬停”在标签上方时,就会产生声音效果。 这是图像: 我尝试过寻找解决方案,我以前已经找到了一个,但在添加声音时它不起作用 import math, random, sys import enum import pygame, time from pygame.locals import* from sys import exit from pygame import mixer #initialising python pygame.init() #py

所以我尝试设置这个东西,每当玩家将鼠标“悬停”在标签上方时,就会产生声音效果。 这是图像:

我尝试过寻找解决方案,我以前已经找到了一个,但在添加声音时它不起作用

import math, random, sys
import enum
import pygame, time
from pygame.locals import*
from sys import exit
from pygame import mixer

#initialising python
pygame.init()
#pygame.mixer.init()
pygame.mixer.pre_init(44100,16,2,4096)
mixer.init()

#define display
W, H = 1600,900
HW, HH = (W/2), (H/2)
AREA = W * H


#bsound effects
buttonsound1 = pygame.mixer.Sound("ButtonSound1.wav") 


#initialising display
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
FPS = 54
progress = 0
background = pygame.Surface(DS.get_size())
smallfont = pygame.font.SysFont("century gothic",25)


#background image
bg = pygame.image.load("Daytime.jpg").convert()
loadingimg = pygame.image.load("LoadingScreen.png").convert()
pause = pygame.image.load("Pause screen.png").convert()
gameover = pygame.image.load("Game Over.png").convert()
mainmenu = pygame.image.load("Main_Menu4.png").convert()
#mainmenu = pygame.transform.smoothscale(mainmenu, (W,H))
loadingimg = pygame.transform.smoothscale(loadingimg, (W,H))

#define some colours
BLACK = (0,0,0,255)
WHITE = (255,255,255,255)
green = (0,140,0)
grey = (180,180,180)

walkLeft = [pygame.image.load('Moving1.png'), pygame.image.load('Moving2.png'), pygame.image.load('Moving3.png'), pygame.image.load('Moving4.png'), pygame.image.load('Moving5.png'), pygame.image.load('Moving6.png'), pygame.image.load('Moving7.png'), pygame.image.load('Moving8.png'), pygame.image.load('Moving9.png')]
walkRight = []
for i in walkLeft:
    walkRight.append(pygame.transform.flip(i, True, False))


char = pygame.image.load('Moving1.png').convert_alpha()
char2 = pygame.image.load('Moving1.png').convert_alpha()
char2 = pygame.transform.flip(char2, True, False)

x = 0
y = 500
height = 40
width = 87
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
walkCount = 0
run = True


# FUNCTIONS
def event_handler():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            pygame.quit()
            exit()

# === CLASSES === (CamelCase names)

class Button():

    def __init__(self, text, x=0, y=0, width=100, height=50, command=None):

        self.text = text
        self.command = command

        self.image_normal = pygame.Surface((width, height))
        self.image_normal.fill(green)

        self.image_hovered = pygame.Surface((width, height))
        #buttonsound1.play()

        self.image = self.image_normal
        self.rect = self.image.get_rect()

        font = pygame.font.Font('freesansbold.ttf', 15)


        text_image = font.render(text, True, WHITE)
        text_rect = text_image.get_rect(center = self.rect.center)

        self.image_normal.blit(text_image, text_rect)
        self.image_hovered.blit(text_image, text_rect)

        # you can't use it before `blit` 
        self.rect.topleft = (x, y)

        self.hovered = False
        #self.clicked = False

    def update(self):

        if self.hovered:
            buttonsound1.play()
        else:
            self.image = self.image_normal

    def draw(self, surface):

        surface.blit(self.image, self.rect)

    def handle_event(self, event):

        if event.type == pygame.MOUSEMOTION:
            self.hovered = self.rect.collidepoint(event.pos)
            buttonsound1.play()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if self.hovered:
                buttonsound1.play()
                print('Clicked:', self.text)
                if self.command:
                    self.command()


class GameState( enum.Enum ):
    Loading = 0
    Menu = 1
    Settings = 2
    Playing = 3
    GameOver = 4

#set the game state initially.
game_state = GameState.Loading


#LOADING
def text_objects(text, color, size):
    if size == "small":
        textSurface = smallfont.render(text, True, color)

    return textSurface, textSurface.get_rect()

def loading(progress):
    if progress < 100:
        text = smallfont.render("Loading: " + str(int(progress)) + "%", True, WHITE)
    else:
        text = smallfont.render("Loading: " + str(100) + "%", True, WHITE)

    DS.blit(text, [50, 660])

def message_to_screen(msh, color, y_displace = 0, size = "small"):
    textSurf, textRect = text_objects(msg, color, size)
    textRect.center = HW, HH + y_displace
    DS.blit(textSurf, textRect)

while (progress/4) < 100:
    event_handler()
    DS.blit(loadingimg, (0,0))
    time_count = (random.randint(1,1))
    increase = random.randint(1,20)
    progress += increase
    pygame.draw.rect(DS, green, [50, 700, 402, 29])
    pygame.draw.rect(DS, grey, [50, 701, 401, 27])
    if (progress/4) > 100:
        pygame.draw.rect(DS, green, [50, 700, 401, 28])
    else:
        pygame.draw.rect(DS, green, [50, 700, progress, 28])
    loading(progress/4)
    pygame.display.flip()

    time.sleep(time_count)

#changing to menu
game_state = GameState.Menu


Menumusic = pygame.mixer.music.load("MainMenu.mp3")
Menumusic = pygame.mixer.music.play(-1, 0.0)

def main_menu():
    DS.blit(mainmenu, (0, 0))
    pygame.display.update()

    btn1 = Button('Hello', 812.5, 250, 100, 50)
    btn2 = Button('World', 825, 325, 100, 50)
    btn3 = Button('Hello', 825, 450, 100, 50)
    btn4 = Button('World', 825, 575, 100, 50)
    btn5 = Button('World', 825, 675, 100, 50)
    btn6 = Button('Hello', 825, 790, 100, 50)

    while run:
        event_handler()
        btn1.update()
        btn2.update()

        # --- draws ---

        btn1.draw(DS)
        btn2.draw(DS)
        btn3.draw(DS)
        btn4.draw(DS)
        btn5.draw(DS)
        btn6.draw(DS)



    pygame.display.update()

main_menu()
导入数学、随机、系统
导入枚举
游戏、时间
从pygame.locals导入*
从系统导入退出
从pygame导入混合器
#初始化python
pygame.init()
#pygame.mixer.init()
pygame.mixer.pre_init(44100,16,24096)
mixer.init()
#定义显示
W、 H=1600900
HW,HH=(W/2),(H/2)
面积=W*H
#声效应
buttonsound1=pygame.mixer.Sound(“buttonsound1.wav”)
#初始化显示
CLOCK=pygame.time.CLOCK()
DS=pygame.display.set_模式((W,H))
pygame.display.set_模式((0,0),pygame.FULLSCREEN)
FPS=54
进度=0
background=pygame.Surface(DS.get\u size())
smallfont=pygame.font.SysFont(“世纪哥特式”,25)
#背景图像
bg=pygame.image.load(“day.jpg”).convert()
loadingimg=pygame.image.load(“LoadingScreen.png”).convert()
pause=pygame.image.load(“pause screen.png”).convert()
gameover=pygame.image.load(“Game Over.png”).convert()
Main menu=pygame.image.load(“Main_Menu4.png”).convert()
#主菜单=pygame.transform.smoothscale(主菜单,(W,H))
loadingimg=pygame.transform.smoothscale(loadingimg,(W,H))
#定义一些颜色
黑色=(0,0,0255)
白色=(255255)
绿色=(0140,0)
灰色=(180180)
walkLeft=[pygame.image.load('Moving1.png')、pygame.image.load('Moving2.png')、pygame.image.load('Moving3.png')、pygame.image.load('Moving5.png')、pygame.image.load('Moving6.png')、pygame.image.load('Moving7.png')、pygame.image.load('Moving8.png')、pygame.image.load('Moving9.png')]
walkRight=[]
对于walkLeft中的i:
append(pygame.transform.flip(i,True,False))
char=pygame.image.load('Moving1.png')。convert_alpha()
char2=pygame.image.load('Moving1.png')。convert_alpha()
char2=pygame.transform.flip(char2,True,False)
x=0
y=500
高度=40
宽度=87
水平=5
isJump=False
跳数=10
左=假
右=假
步行次数=0
运行=真
#功能
def事件处理程序():
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
运行=错误
pygame.quit()
退出()
#===类===(CamelCase名称)
类按钮():
定义初始化(self,text,x=0,y=0,width=100,height=50,command=None):
self.text=文本
self.command=命令
self.image_normal=pygame.Surface((宽度、高度))
自映像\u正常填充(绿色)
self.image_hovered=pygame.Surface((宽度、高度))
#按钮声音1.播放()
self.image=self.image\u正常
self.rect=self.image.get_rect()
font=pygame.font.font('freesansbold.ttf',15)
text\u image=font.render(文本,真,白色)
text\u rect=text\u image.get\u rect(center=self.rect.center)
self.image\u normal.blit(text\u image,text\u rect)
self.image\u hovered.blit(text\u image,text\u rect)
#在“blit”之前不能使用它
self.rect.topleft=(x,y)
self.hovered=False
#self.clicked=False
def更新(自我):
如果self.hover:
按钮声音1.播放()
其他:
self.image=self.image\u正常
def绘图(自、表面):
blit(self.image,self.rect)
def句柄_事件(自身、事件):
如果event.type==pygame.MOUSEMOTION:
self.hovered=self.rect.collidepoint(event.pos)
按钮声音1.播放()
elif event.type==pygame.MOUSEBUTTONDOWN:
如果self.hover:
按钮声音1.播放()
打印('单击:',self.text)
如果自我命令:
self.command()
类游戏状态(enum.enum):
加载=0
菜单=1
设置=2
播放=3
GameOver=4
#最初设置游戏状态。
游戏状态=游戏状态。正在加载
#装载
def text_对象(文本、颜色、大小):
如果大小=“小”:
textSurface=smallfont.render(文本、真、彩色)
返回textSurface,textSurface.get_rect()
def加载(进度):
如果进度<100:
text=smallfont.render(“加载:”+str(int(进度))+“%”,真,白色)
其他:
text=smallfont.render(“加载:”+str(100)+“%”,真,白色)
blit(文本[50660])
def消息到屏幕(msh,颜色,y_置换=0,大小=“小”):
textSurf,textRect=text\u对象(消息、颜色、大小)
textRect.center=HW,HH+y_置换
DS.blit(textSurf,textRect)
而(进度/4)<100:
事件处理程序()
DS.blit(加载img,(0,0))
时间计数=(random.randint(1,1))
增加=随机。随机数(1,20)
进步+=增加
pygame.draw.rect(DS,绿色,[5070040229])
pygame.draw.rect(DS,grey,[5070140127])
如果(进度/4)>100:
pygame.draw.rect(DS,绿色,[5070040128])
其他:
pygame.draw.rect(DS,绿色,[50700,进度,28])
装载(进度/4)
pygame.display.flip()
时间。睡眠(时间计数)
#切换到菜单
游戏状态=游戏状态。菜单
Menumusic=pygame.mixer.music.load(“main menu.mp3”)
Menumusic=pygame.mixer.music.play(-1,0.0)
def主菜单():
DS.blit(主菜单,(0,0))
pygame.display.update()
btn1=按钮('Hello',812.525010050)
btn2=按钮(“世界”,825325100,50)
btn3=按钮('Hello',82545010050)
btn4=按钮(“世界”,82557500)
btn5=按钮(“世界”,825675100,50)
btn6=按钮(“你好”,825790100,50)
运行时:
事件处理程序()
btn1.update()
btn2.update()
#---抽签---
btn1.图纸(DS)
btn2.图纸(DS)
btn3.图纸(DS)
btn4.图纸(DS)
btn5.图纸(DS)
btn6.图纸(DS)
pygame.display.update()
主菜单()
我所期望的是,每当鼠标滑过标签h时,就会产生一种声音效果
import pygame

#initialising python
pygame.init()
#pygame.mixer.init()
pygame.mixer.pre_init(44100,16,2,4096)
pygame.mixer.init()

#define display
W, H = 200, 200
HW, HH = (W/2), (H/2)
AREA = W * H

#initialising display
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
#pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
pygame.display.set_mode((0, 0) )
FPS = 54

#define some colours
BLACK = (0,0,0,255)
WHITE = (255,255,255,255)
green = (0,140,0)
grey = (180,180,180)


class Button():

    def __init__(self, text, x=0, y=0, width=100, height=50, command=None):

        self.text = text
        self.command = command
        self.image_normal = pygame.Surface((width, height))
        self.image_normal.fill(green)
        self.image_hovered = pygame.Surface((width, height))
        self.image_hovered.fill(grey)
        self.image  = self.image_normal
        self.rect   = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

        self.hovered= False  # is the mouse over this button?

    def update(self):
        pass

    def handleMouseOver( self, mouse_position ):
        """ If the given co-ordinate inside our rect,
            Do all the mouse-hovering work             """
        # Check button position against mouse
        # Change the state *once* on entry/exit
        if ( self.mouseIsOver( mouse_position ) ):
            if ( self.hovered == False ):
                self.image = self.image_hovered
                self.hovered = True   # edge-triggered, not level triggered
                # Do we want to check pygame.mixer.get_busy() ?
                if ( pygame.mixer.get_busy() == False ):
                    print( self.text + " DO buttonsound1.play() ")
        else:
            if ( self.hovered == True ):
                self.image = self.image_normal
                self.hovered = False

    def mouseIsOver( self, mouse_position ):
        """ Is the given co-ordinate inside our rect """
        return self.rect.collidepoint( mouse_position )

    def draw(self, surface):

        surface.blit(self.image, self.rect)


def main_menu():

    run = True
    btn1 = Button('Hello1',  50,  50, 40, 40)
    btn2 = Button('World2', 100,  50, 40, 40)
    btn3 = Button('Hello3',  50, 100, 40, 40)
    btn4 = Button('World4', 100, 100, 40, 40)

    # Put the buttons into a list so we can loop over them, simply
    buttons = [ btn1, btn2, btn3, btn4 ]

    while run:

        # draw the buttons
        for b in buttons:
            b.draw( DS ) # --- draws ---

        # Handle events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEMOTION:
                mouse_position = event.pos
                for b in buttons:
                    b.handleMouseOver( mouse_position )
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_position = event.pos
                for b in buttons:
                    if ( b.mouseIsOver( mouse_position ) ):
                        print('Clicked:', b.text)
                        #if b.command:
                        #    b.command()


        pygame.display.update()



main_menu()
pygame.quit()