?? ball.py
字號:
import sys, pygame
import winsound
class Ball:
def __init__(self, width, height, image, speed):
self.speed = speed
self.image = pygame.image.load(image)
self.width = width
self.height = height
self.size = self.get_size()
self.c = 0
def get_size(self):
return self.image.get_rect()
def move(self):
self.size = self.size.move(self.speed)
def boundary_collision(self):
if self.size.left < 0 or self.size.right > self.width:
self.speed[0] = -self.speed[0]
self.c = self.c+1
if self.size.top < 0 or self.size.bottom > self.height:
self.speed[1] = -self.speed[1]
self.c = self.c+1
def blit(self):
screen.blit(self.image, self.get_size())
def ball_collision(self, other, sound):
if self.check(self.size.left, self.size.top, self.size.right, self.size.bottom, other.size.left, other.size.top, other.size.right, other.size.bottom) == True:
winsound.Beep(sound,2)
temp = self.speed
self.speed = other.speed
other.speed = temp
def check(self, xl, xt, xr, xb, yl, yt, yr, yb):
if (self.inside(xl, xb, yl, yt, yr, yb) or self.inside(xl, xt, yl, yt, yr, yb) or self.inside(xr, xt, yl, yt, yr, yb) or self.inside(xr, xb, yl, yt, yr, yb)) == True:
return True
else:
return False
def inside(self, x, y, p1, p2, p3, p4):
if x>p1 and x<p3 and y>p2 and y<p4:
return True
else:
return False
pygame.init()
size = width,height = 700,700
speed = ([4,17], [15,19], [13,16], [12,5], [14,1], [2,9], [8,7], [3,18], [10,20], [11,6])
ball = []
sound = (40, 80, 100, 150, 50, 8000, 5000, 4000, 7000, 10000)
img = ("ballf.bmp", "ballf.bmp", "ballf.bmp", "ballf.bmp", "ballf.bmp", "ballf.bmp","ballf.bmp","ballf.bmp","ballf.bmp","ballf.bmp",)
for i in range(10):
ball.append(Ball(width, height, img[i], speed[i]))
black = 0,0,0
screen = pygame.display.set_mode(size)
d = 0
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
for i in range(10):
ball[i].move()
for i in range(10):
ball[i].boundary_collision()
if ball[i].c > 0:
d = d+1
if d>9:
for i in range(10):
for j in range(10-i-1):
ball[i].ball_collision(ball[i+j+1], sound[i])
screen.fill(black)
for i in range(10):
screen.blit(ball[i].image, ball[i].size)
pygame.display.flip()
pygame.time.delay(15)
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -