我正在使用pygame制作游戏。当玩家死亡时,它会播放“游戏结束”音乐,但会播放多次。我将循环设为0,但它又播放了多次。
import pygame
pygame.init()
# creating our window
win = pygame.display.set_mode((800, 480))
pygame.display.set_caption("My First Game")
# creating our icon
game_icon = pygame.image.load('logo.png')
pygame.display.set_icon(game_icon)
# player variables
player_x = 0
player_y = 240
# jumping variables
is_jump = False
jump_count = 10
# enemy variables
enemy_x = 100
enemy_y = 240
enemy_left = False
enemy_right = True
# dead variable
is_dead = False
# score and score timer variables
score = 0
score_timer = 0
# main loop
run = True
while run:
pygame.time.delay(50)
# checking if user pressed the exit button(he probly rage quit) then quiting our game
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# controls
keys = pygame.key.get_pressed()
# left control
if keys[pygame.K_LEFT] and player_x != 0:
player_x -= 5
# right control
if keys[pygame.K_RIGHT] and player_x != 735:
player_x += 5
# jump control
if not(is_jump) and not(is_dead):
if keys[pygame.K_UP]:
is_jump = True
pygame.mixer.music.load("jump.wav")
pygame.mixer.music.play(loops=0)
elif not(is_dead):
if jump_count >= -10:
neg = 1
if jump_count < 0:
neg = -1
player_y -= (jump_count ** 2) * 0.5 * neg
jump_count -= 1
else:
is_jump = False
jump_count = 10
# drawing player and enemy
if not(is_dead):
player = pygame.draw.rect(
win, (255, 0, 0), (player_x, player_y, 64, 64))
enemy = pygame.draw.rect(win, (0, 0, 255), (enemy_x, enemy_y, 64, 64))
# enemy movement
if enemy_right:
enemy_x = enemy_x + 5
if enemy_x == 735:
enemy_right = False
enemy_left = True
if enemy_left:
enemy_x = enemy_x - 5
if enemy_x == 0:
enemy_left = False
enemy_right = True
# checking collision between enemy and player
if player.colliderect(enemy):
is_dead = True
# checking if collision has happend and player died
if is_dead:
# displaying game over if player is dead
font_over = pygame.font.Font("freesansbold.ttf", 64)
game_over = font_over.render("Game Over", True, (255, 255, 255))
win.blit(game_over, (230, 200))
# dead sound
pygame.mixer.music.load("over.wav")
pygame.mixer.music.play(loops=0)
# displaying score
font_score = pygame.font.Font("freesansbold.ttf", 32)
score_text = font_score.render(
"Score: " + str(score), True, (255, 255, 255))
win.blit(score_text, (0, 0))
# score and score timer
if not(is_dead):
score_timer += 1
if score_timer == 60:
score += 1
score_timer = 0
# updating our window and filling it black
pygame.display.update()
win.fill((0, 0, 0))
# quiting the game if user no longer whants to play
pygame.quit()
答案 0 :(得分:3)
只有在玩家退出时,您才退出主游戏循环(运行时)。 并且您正在运行该代码以在循环的每个迭代中通过音乐玩游戏,因此,一旦将is_dead变量设置为true,则每次运行主循环时(在用户退出应用程序之前)将重复通过音乐进行游戏的代码。 )。
要解决此问题,您可以声明变量hasPlayedGameOverSound = False
。也许在声明is_dead变量之后最好。
然后将#死音注释后的两行更改为
if not hasPlayedGameOverSound:
pygame.mixer.music.load("over.wav")
pygame.mixer.music.play(loops=0)
hasPlayedGameOverSound = True
这应该确保声音游戏只能播放一次