モンキーハンティング

ボールの軌道を描けるようになったので、モンキーハンティングのシミュレータのようなものを作った。実行画面は次の通り。

赤いボールが鉄砲の弾で緑のボールがサルを表す。弾丸発射とともにサルが自由落下を始める。サルが地面に到達する前に両者の距離が十分縮まれば(弾丸の速度が十分速ければ)、必ずサルに弾が当たる。

ソースは以下の通り。

from visual import *

# constant
pi = 3.14159  # 円周率
gconst = 9.8  # 重力定数
dt = 0.001   # 時間刻み
eps = 1.0e-2  # 距離の判定値

# initial condition
dist = 10.0    # サルまでの水平距離
angl = 45.0/180.0*pi # サルへの角度
ballv = 10.0    # 弾丸の初速度
hght = dist * tan(angl) # サルの初期高さ

# objects
floor = box (pos=(0,0,0), length=20, height=0.0011,
             width=20, color=color.blue)

ball1 = sphere (pos=(0,0,0), radius=0.3, color=color.red)
ball1.velocity = vector(ballv*cos(angl),ballv*sin(angl),0)
ball1.trail = curve(color=ball1.color)

ball2 = sphere (pos=(dist,hght,0), radius=0.3, color=color.green)
ball2.velocity = vector(0,0,0)
ball2.trail = curve(color=ball2.color)

while True:
    rate (100)
    ball1.pos = ball1.pos + ball1.velocity*dt
    ball2.pos = ball2.pos + ball2.velocity*dt
    ball1.trail.append(pos=ball1.pos)     # 軌道を表示する
    ball2.trail.append(pos=ball2.pos)
    if ball2.pos.y < floor.pos.y:     # サルが地面に到達したとき
        ball2.velocity.y = -ball2.velocity.y
    else:
        ball2.velocity.y = ball2.velocity.y - gconst*dt
    ball1.velocity.y = ball1.velocity.y - gconst*dt

    if fabs(ball1.pos.y - floor.pos.y) < eps:  #はずれ
        print 'You miss it!'
        break

    if fabs(ball1.pos.x - ball2.pos.x) < eps and\
       fabs(ball1.pos.y - ball2.pos.y) < eps:
        print 'You got it!'           #当たり
        break