思路:
先改变方向,再移动
? ? ? ? 1)位于端点会改变方向:
? ? ? ? ? ? ? ? 位于左端点----->方向变为右
????????????????位于右端点----->方向变为左
? ? ? ? 2)两球位置相同会改变方向:
? ? ? ? ? ? ? ? 给定一个球ball和列表balls,判断balls中是否有与ball位置相同的same_ball,
? ? ? ? ? ? ? ? 是,改变方向:
? ? ? ? ? ? ? ? ????????ball.dire = -ball.dire
? ? ? ? ? ? ? ? ????????same_ball.dire = -ball.dire
'''
自定义类Ball,每个小球都有位置loc和方向dire;
向右dire是1,向左dire是—1,
'''
class Ball:
def __init__(self, loc, dire):
self.loc = loc
self.dire = dire
def ballBumpWall(ball):
if ball.loc == 0: # 球撞墙,在左端点,方向变为右
ball.dire = 1
if ball.loc == l: # 球撞墙,在右端点,方向变为左
ball.dire = -1
def ballBumpBall(ball, balls):
for i in range(len(balls)):
if balls[i].loc == ball.loc and balls.index(ball) != i:
ball.dire = -ball.dire
balls[i].dire = -ball.dire
finput = input().split()
n = int(finput[0]) # n个小球
l = int(finput[1]) # 长度为L(L为偶数)的线段
t = int(finput[2]) # t秒之后
finput = input().split()
balls = []
for i in range(n):
balls.append(Ball(int(finput[i]), 1)) # 初始方向都是右——1
start = 1
while start<=t:
for i in range(n):
ballBumpWall(balls[i])
ballBumpBall(balls[i], balls)
if balls[i].dire == 1:
balls[i].loc += 1
if balls[i].dire == -1:
balls[i].loc -= 1
start += 1
for ball in balls:
print(ball.loc,end=' ')
|