|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pygame
import sys
import os
import math as m
os.chdir("C:\\Users\\david\\Desktop\\碰撞小球")
from random import *
from pygame.locals 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]
def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.left > self.width :
self.rect.left = 0
elif self.rect.top > self.height:
self.rect.bottom = 0
elif self.rect.bottom <0:
self.rect.top = self.height
elif self.rect.right <0:
self.rect.left = self.width
def main():
pygame.init()
ball_image = "gray_ball.png"
bg_image = "background.png"
running = True
bg_size = width, height = 1024,511
screen = pygame.display.set_mode(bg_size)
background = pygame.image.load(bg_image).convert_alpha()
pygame.display.set_caption("nihao")
balls_copy = []
balls = []
for i in range(5):
position = randint(0, width - 100), randint(0, height - 100)
speed = [randint(-10,10),randint(-10,10)]
ball = Ball(ball_image, position, speed, bg_size)
balls.append(ball)
clock = pygame.time.Clock()
balls_copy = balls.copy()
while running:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
screen.blit(background,(0,0))
for eachball in balls:
ball_index = 0
item = balls.pop(ball_index)
for each in balls:
distance = m.sqrt(m.pow((item.rect.center[0] - each.rect.center[0]), 2) + m.pow(
(item.rect.center[1] - each.rect.center[1]), 2))
if distance <= (item.rect.width + each.rect.width) / 2:
each.speed[0], each.speed[1] = - \
each.speed[0], -each.speed[1]
item.speed[0], item.speed[1] = - \
item.speed[0], -item.speed[1]
balls = balls_copy #-----------------------------------------------对于这一行代码,为什么balls = balls_copy 与balls = balls_copy.copy(),两段代码执行的效果相差这么大??
for each in balls:
screen.blit(each.image,each.rect)
each.move()
pygame.display.flip()
clock.tick(30)
if __name__ == "__main__":
main() |
|