In [3]:
from Graphics import *

In [4]:
win = Window(200, 500)

In [5]:
ball = Circle((100, 10), 10)

In [6]:
ball.draw(win)

Out[6]:
In [39]:
gravity = .01
speed_y = 0
speed_x = .1
ball.x = 100
ball.y = 10

ball.penDown()

while True:
speed_y = speed_y + gravity
ball.y = ball.y + speed_y
ball.x = ball.x + speed_x
if ball.y > 500:
speed_y = -speed_y * .8
ball.y = 500 - 5
if ball.x > 200:
speed_x = -speed_x
ball.x = 200
elif ball.x < 0:
speed_x = -speed_x
ball.x = 0
wait(.005)

Running script aborted!

In [8]:
ball.x, ball.y

Out[8]:
(100.0, 3819180523171.0)
In [65]:
import random

class World:
def __init__(self):
self.gravity = .01
self.window = Window(200, 500)
self.balls = [Ball(self) for i in range(7)]

def run(self):
while True:
for ball in self.balls:
ball.move()
wait(.005)

class Ball:
def __init__(self, world):
self.world = world
self.speed_y = 0
self.speed_x = random.random() * 2 - 1
self.ball = Circle((random.randint(0, 200),
random.randint(0, 100)), 10)
self.ball.penDown()
self.ball.draw(self.world.window)

def move(self):
self.speed_y = self.speed_y + self.world.gravity
self.ball.y = self.ball.y + self.speed_y
self.ball.x = self.ball.x + self.speed_x
if self.ball.y > 500:
self.speed_y = -self.speed_y * .8
self.ball.y = 500 - 5
if self.ball.x > 200:
self.speed_x = -self.speed_x
self.ball.x = 200
elif self.ball.x < 0:
self.speed_x = -self.speed_x
self.ball.x = 0

In [66]:
world = World()

In [67]:
world.run()

Running script aborted!

In [122]:
import random
import math

class World:
def __init__(self):
self.gravity = .01
self.window = Window(200, 500)
self.balls = [Ball(self) for i in range(7)]

def step(self):
for ball in self.balls:
ball.move()

def check_collides(self):
for ball1 in self.balls:
for ball2 in self.balls:
if ball1 is ball2:
continue  # can't collide with yourself!
if ball1.collide(ball2):
# if collide, swap speeds!
ball1.speed_x, ball2.speed_x = ball2.speed_x, ball1.speed_x
ball1.speed_y, ball2.speed_y = ball2.speed_y, ball1.speed_y

def run(self):
while True:
self.step()
self.check_collides()
wait(.005)

class Ball:
def __init__(self, world):
self.world = world
self.speed_y = 0
self.speed_x = random.random() * 2 - 1
self.ball = Circle((random.randint(0, 200),
self.ball.color = colors[random.choice(list(colors.Keys))]
self.ball.penDown()
self.ball.draw(self.world.window)

def move(self):
self.speed_y = self.speed_y + self.world.gravity
self.ball.y = self.ball.y + self.speed_y
self.ball.x = self.ball.x + self.speed_x
#### keep in bounds:
if self.ball.y > 500:
self.speed_y = -self.speed_y * .8
self.ball.y = 500 - 5
if self.ball.x > 200:
self.speed_x = -self.speed_x
self.ball.x = 200
elif self.ball.x < 0:
self.speed_x = -self.speed_x
self.ball.x = 0

def collide(self, other):

def distance(self, other):
return math.sqrt((self.ball.x - other.ball.x) ** 2 +
(self.ball.y - other.ball.y) ** 2)

In [130]:
w2 = World()

In [124]:
w2.step()

In [131]:
w2.run()

Running script aborted!

In [132]:
w2.window

Out[132]:
In [ ]: