|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码是仿造小甲鱼的play the ball 游戏 但是我的运行起来只有一个球会动,其他四个球疯狂抖动
import pygame
import sys
import random
#创建一个球类
class Ball(pygame.sprite.Sprite):
def __init__(self, image, position, speed, bg_size):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
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.left < 0 or self.rect.right > self.width:
self.speed[0] = -self.speed[0]
if self.rect.top < 0 or self.rect.bottom > self.height:
self.speed[1] = -self.speed[1]
def main():
pygame.init()
ball_image = "ball.png"
backgroung_image = "background.png"
running = True
clock = pygame.time.Clock()
bg_size = width,height = 1200, 600
screen = pygame.display.set_mode(bg_size)
pygame.display.set_caption("Play the ball - gjw demo")
background = pygame.image.load(backgroung_image)
balls = []
group = pygame.sprite.Group()
#创建5个小球
for i in range(5):
position = random.randint(0,width - 80),random.randint(0,height - 80)
speed = [random.randint(-10,10), random.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 = random.randint(0, width-80), random.randint(0, height-80)
balls.append(ball)
group.add(ball)
#小球跑起来
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.blit(background,(0,0))
for each in balls:
each.move()
screen.blit(each.image, each.rect)
#碰撞检测
for each in group:
group.remove(each)
if pygame.sprite.spritecollide(ball, 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()
|
|