马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pygame
import sys
import traceback
from pygame.locals import *
from random import *
# 球类继承自Spirte类
class Ball(pygame.sprite.Sprite):
def __init__(self, grayball_image, position, speed, bg_size):
# 初始化动画精灵
pygame.sprite.Sprite.__init__(self)
self.grayball_image = pygame.image.load(grayball_image).convert_alpha()
self.rect = self.grayball_image.get_rect()
# 将小球放在指定位置
self.rect.left, self.rect.top = position
self.side = [choice([-1, 1]), choice([-1, 1])]
self.speed = speed
self.collide = False
self.control = False
self.width, self.height = bg_size[0], bg_size[1]
self.radius = self.rect.width / 2
def move(self):
if self.control:
self.rect = self.rect.move(self.speed)
else:
self.rect = self.rect.move((self.side[0] * self.speed[0], \
self.side[1] * self.speed[1]))
# 如果小球的左侧出了边界,那么将小球左侧的位置改为右侧的边界
# 这样便实现了从左边进入,右边出来的效果
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()
grayball_image = "UFO.jpg"
bg_image = "background.jpg"
running = True
# 添加背景音乐
pygame.mixer.music.load("music.ogg")
pygame.mixer.music.play()
# 添加音效
loser_sound = pygame.mixer.Sound("fail.ogg")
laugh_sound = pygame.mixer.Sound("laugh.ogg")
winner_sound = pygame.mixer.Sound("win.ogg")
# 根据背景图片指定游戏界面尺寸
bg_size = width, height = 1200,800
screen = pygame.display.set_mode(bg_size)
pygame.display.set_caption("Play the ball - FishC Demo")
background = pygame.image.load(bg_image).convert_alpha()
# 用来存放小球对象的列表
balls = []
group = pygame.sprite.Group()
# 创建 5 个小球
for i in range(5):
# 位置随机,速度随机
position = randint(0, width-100), randint(0, height-100)
speed = [randint(1, 10), randint(1, 10)]
ball = Ball(grayball_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)
balls.append(ball)
group.add(ball)
if __name__ == "__main__":
try:
main()
except SystemExit:
pass
except:
traceback.print_exc()
pygame.quit()
input()
|