import pygame
import my_color
from random import randint
from time import sleep
game_width=600
game_height=400
all_balls=[]
# main_ball={}
key_ball_center = 'ball_center'
key_ball_color = 'ball_color'
key_ball_radius = 'ball_radius'
key_ball_xspeed = 'ball_xspeed'
key_ball_yspeed = 'ball_yspeed'
key_ball_class = 'ball_class'
def ball_crash(main_ball):
x1,y1=main_ball[key_ball_center]
r1=main_ball[key_ball_radius]
for ball in all_balls:
if main_ball!=ball:
x2,y2=ball[key_ball_center]
r2=ball[key_ball_radius]
if (x2-x1)**2+(y2-y1)**2<=(r1+r2)**2:
if ball[key_ball_class]==2:
main_ball[key_ball_radius]=r1-1
elif ball[key_ball_class]==1:
main_ball[key_ball_radius]=r1+1
dead = 0
ball[key_ball_class]=dead
for ball2 in all_balls:
radius = ball2[key_ball_radius]
if main_ball!=ball2:
if ball2[key_ball_class]!=0:
if radius-1>0:
ball2[key_ball_radius]=radius - 1
def move_ball(main_ball):
# print(main_ball)
if main_ball:
x,y = main_ball[key_ball_center]
x +=main_ball[key_ball_xspeed]
y +=main_ball[key_ball_yspeed]
radius = main_ball[key_ball_radius]
if x+radius>game_width:
x = game_width-radius
elif x < radius:
x=radius
if y+radius>game_height:
y=game_height-radius
elif y<radius:
y=radius
main_ball[key_ball_center]=(x,y)
def draw_ball(window):
if all_balls:
for ball in all_balls:
if ball[key_ball_class]==0:
all_balls.remove(ball)
pygame.draw.circle(window,
ball[key_ball_color],
ball[key_ball_center],
ball[key_ball_radius])
pygame.display.update()
window.fill(my_color.white)
sleep(0.01)
def rand_pos():
'''
生成随机的位置和半径
'''
radius = randint(5,10)
x = randint(radius,game_width-radius)
y = randint(radius,game_height-radius)
return radius,x,y
def create_balls():
'''
生产ball
'''
radius,x,y = rand_pos()
color = my_color.rand_color()
xspeed = 0
yspeed = 0
flag = [1,2][randint(0,1)]
ball={
key_ball_color:color,
key_ball_center:(x,y),
key_ball_radius:radius,
key_ball_xspeed:xspeed,
key_ball_yspeed:yspeed,
key_ball_class:flag
}
all_balls.append(ball)
def main_page():
pygame.init()
window = pygame.display.set_mode((game_width,game_height))
window.fill(my_color.white)
create_balls()
main_ball = all_balls[0]
pygame.display.flip()
while True:
if len(all_balls)<=20:
create_balls()
draw_ball(window)
move_ball(main_ball)
ball_crash(main_ball)
# print(main_ball)
all_balls[0]=main_ball
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit(0)
if event.type == pygame.KEYDOWN:
if event.key == 273:
main_ball[key_ball_xspeed]=0
main_ball[key_ball_yspeed]=-2
if event.key == 274:
main_ball[key_ball_xspeed]=0
main_ball[key_ball_yspeed]=2
if event.key == 275:
main_ball[key_ball_xspeed]=2
main_ball[key_ball_yspeed]=0
if event.key == 276:
main_ball[key_ball_xspeed]=-2
main_ball[key_ball_yspeed]=0
if __name__ == '__main__':
main_page()
网友评论