1
目前只是嘗試pygame,我創建了一個白色背景,只是一個圖像的窗口。我希望能夠使用箭頭鍵(正常工作)以及按下箭頭鍵時移動圖像,我想要播放引擎聲音mp3。這是我目前得到的代碼:pygame按鍵上的聲音
image_to_move = "dodge.jpg"
import pygame
from pygame.locals import *
pygame.init()
pygame.display.set_caption("Drive the car")
screen = pygame.display.set_mode((800, 800), 0, 32)
background = pygame.image.load(image_to_move).convert()
pygame.init()
sound = pygame.mixer.music.load("dodgeSound.mp3")
x, y = 0, 0
move_x, move_y = 0, 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
break
#Changes the moving variables only when the key is being pressed
if event.type == KEYDOWN:
pygame.mixer.music.play()
if event.key == K_LEFT:
move_x = -2
if event.key == K_RIGHT:
move_x = 2
if event.key == K_DOWN:
move_y = 2
if event.key == K_UP:
move_y = -2
#Stops moving the image once the key isn't being pressed
elif event.type == KEYUP:
pygame.mixer.music.stop()
if event.key == K_LEFT:
move_x = 0
if event.key == K_RIGHT:
move_x = 0
if event.key == K_DOWN:
move_y = 0
if event.key == K_UP:
move_y = 0
x+= move_x
y+= move_y
screen.fill((255, 255, 255))
screen.blit(background, (x, y))
pygame.display.update()
圖像將加載很好,我可以在任何
你的if語句*任何*鍵(不只是那些4),被釋放停止聲音。 – ninMonkey 2013-03-20 05:43:32
所以我需要使用4個鍵的每個子if語句下的pygame.mixer.music.stop()? – 2013-03-20 12:44:26