import pygame
import sys
import math
from random import *
# 动画精灵就是一个带有图像和位置数据的对象
# 我们这里继承他,主要调用一个初始化函数
class Ball(pygame.sprite.Sprite): # 继承动画精灵基类
# 调用动画精灵的初始化函数
def __init__(self,image,position,speed,bg_size):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image).convert_alpha()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = position
self.speed = speed
self.width, self.height = bg_size[0], bg_size[1]
self.radius = self.rect.width / 2
def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.right < 0:
self.rect.left = self.width
elif self.rect.left > self.width:
self.rect.right = 0
elif self.rect.bottom < 0:
self.rect.top = self.height
elif self.rect.top > self.height:
self.rect.bottom = 0
def main():
pygame.init()
ball_image = "gray_ball.png"
bg_image = "background.png"
# 如果点击暂停 可以结束循环
running = True
# 添加背景音乐
pygame.mixer.music.load("bg_music.ogg")
pygame.mixer.music.play()
# 添加音效
winner_sound = pygame.mixer.Sound("winner.wav")
loser_sound = pygame.mixer.Sound("loser.wav")
hole_sound = pygame.mixer.Sound("hole.wav")
# 音乐结束游戏结束
GAMEOVER = pygame.USEREVENT # 自定义事件,自定义事件 GAMEOVER 不用加 pygame
pygame.mixer.music.set_endevent(GAMEOVER) # 音乐结束时将自定义事件GAMEPVER加入事件列表
bg_size = width, height = 1024, 681
screen = pygame.display.set_mode(bg_size)
pygame.display.set_caption("玩个球")
background = pygame.image.load(bg_image).convert_alpha()
# 添加精灵组
group = pygame.sprite.Group()
# 创建5个球
BALL_NUM = 5
for i in range(BALL_NUM):
position = randint(0, width-100), randint(0, height-100)
speed = [randint(-10, 10), randint(-10, 10)]
ball = Ball(ball_image,position,speed,bg_size)
# 防止出生就重叠,每新建一个就和之前的检测,如果有的话,就重新赋值坐标
while pygame.sprite.spritecollide(ball, group, False, pygame.sprite.collide_circle):
ball.rect.left, ball.rect.top = randint(0, width-100), randint(0, height-100)
group.add(ball)
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == GAMEOVER: # 自定义事件 GAMEOVER 不用加 pygame
loser_sound.play()
running = False
screen.blit(background,(0, 0))
for each in group:
each.move()
screen.blit(each.image,each.rect)
for each in group:
group.remove(each)
if pygame.sprite.spritecollide(each, group, False, pygame.sprite.collide_circle):
each.speed[0] = -each.speed[0]
each.speed[1] = -each.speed[1]
group.add(each)
pygame.display.flip()
clock.tick(30)
if __name__ == "__main__":
main()
使用pygame.mixer.music
一次只能播放一个音乐
但是pygame.mixer.Sound
可以同时播放好几个
声音文件只接受ogg
或者wav
格式文件