roberto schrieb:
hello
(i am rather new in python ...)

i am about to start a course of physics and math for students aged
14-17 (high school)
and i am deeply interested in the possibilty of teaching fundamental
concepts of these subjects via teaching programming;
i chose python (i won't change my mind ...)

so i am looking for resources on how to deal with these topics via
this great programming language;

Hi Roberto,

I've done a few short scripts which might be interesting to you. Take
them as examples, which you may use, modify or simply take for
inspiration to do something similar.

The first one, together with an example - tdemo_planet_and_moon.py -
which you might find here:

http://svn.python.org/view/python/trunk/Demo/turtle/

are simulations of gravitational three-body-systems.

tdemo_sierpinsky.py is a script which draws a colorful sierpinsky-triangle
and uses a simple 3D-Vector class. (BTW the gravitation-scripts above use
a 2DVector class which is included in the turtle module.)

tdemo_spaceship.py is sort of a game which I've used in my physics classes
to let my students experience how to drive a spaceship in agravic space. (Try to drive it along a circlular orbit!) Before this, my students in a computer science class had programmed it, so it's code might be worth to be polished a bit ;-)

Another mathematically interesting example is the script tdemo_chaos.py which you can also find at the link mentioned above. It shows that the result of some
80 iterations of an algebraic expression depends extremely on the way it is
realized in python (that means of the order of arithmetic operations).

All those examples use the turtle module which is part of the Python standard
library since Python 2.6. This module is devised to provide very easy
access to graphics which might be of importance if you do mathematics and
physics, because it allows to avoid some 'bureaucratic' overhead which is
necessary to use Toolkits like Tkinter and others. Thus you can concentrate
more easily on the mathematical and physical contents of you curriculum.

Maybe it might be useful to create some sort of repository in the web
for small classroom dedicated math- and physics related Python scripts?

Regards,
Gregor






i need some help from you and moreover if you are aware of books
already covering these need

thank you in advance
#!/usr/bin/python
"""       turtle-example-suite:

            tdemo_planets.py

Gravitational system simulation using the
approximation method from Feynman-lectures,
p.9-8, using turtlegraphics.

Example: heavy central body, light planet,
very light second planet! This one will be
deflected several times by the gravitational
force exerted by the first planet.

You can hold the movement temporarily by
pressing the left mouse button with mouse
on the scrollbar of the canvas.

"""
from turtle import Vec2D, Shape, Turtle, mainloop
from time import sleep

G = 8   # gravitational constant

class GravSys(object):
    def __init__(self):
        self.planets = []
        self.dt = 0.01
    def init(self):
        for planet in self.planets:
            planet.init()
    def start(self):
        for i in range(20000):
            for planet in self.planets:
                planet.step()
            
class Star(Turtle):
    def __init__(self, m, x, v, gravSys, shape):
        Turtle.__init__(self, shape)
        self.resizemode("user")
        gravSys.planets.append(self)
        self.gravSys = gravSys
        self.dt = self.gravSys.dt
        self.penup()
        self.m = m
        self.setpos(x)
        self.vel = v
        self.pendown()
    def init(self):
        self.vel = self.vel + 0.5*self.dt*self.acc()
    def acc(self):
        a = Vec2D(0,0)
        for planet in self.gravSys.planets:
            if planet != self:
                r = planet.pos()-self.pos()
                a += (G*planet.m/abs(r)**3)*r
        return a
    def step(self):
        self.setpos(self.pos() + self.dt*self.vel)
        if self != sun:
            self.setheading(self.towards(sun))
        self.vel = self.vel + self.dt*self.acc()

## create compound yellow/blue turtleshape for planets
## yellow semicircle will always point towards the sun
def createPlanetShape():
    s = Turtle()
    s.tracer(0,0)
    s.ht()
    s.pu()
    s.fd(6)
    s.lt(90)
    s.begin_poly()
    s.circle(6, 180)
    s.end_poly()
    m1 = s.get_poly()
    s.begin_poly()
    s.circle(6,180)
    s.end_poly()
    m2 = s.get_poly()

    planetshape = Shape("compound")
    planetshape.addcomponent(m1,"orange")
    planetshape.addcomponent(m2,"blue")
    s.getscreen().addshape("planet", planetshape)
    s.tracer(1,0)
    s.ht()

def main():
    global sun
    createPlanetShape()
    ## setup gravitational system
    gs = GravSys()
    sun = Star(1000000, Vec2D(0,0), Vec2D(0,-3.5), gs, "circle")
    sun.color("yellow")
    sun.turtlesize(1.8)
    sun.pu()
    earth = Star(10000, Vec2D(100,0), Vec2D(0,350), gs, "planet")
    earth.pencolor("green")
    venus = Star(4, Vec2D(-80,0), Vec2D(0,-350), gs, "planet")
    venus.pencolor("blue")
    venus.turtlesize(0.7)
    gs.init()
    gs.start()
    return "Done!"

if __name__ == '__main__':
    msg = main()
    print msg
    mainloop()
#!/usr/bin/python
"""       xturtle-example-suite:

           xtx_sierpinski.py

This program draws a coloured sierpinski
triangle.

Each vertex of the triangle is associated
with a color - in the case of this example
red, green and blue. The colors of the
triangular cells of the Sierpinski triangle
are computed by interpolation.

This interpolation uses a 3-vector class
similar to the 2-vector class, which is part
of the xturtle graphics module.
"""

from turtle import *
from time import clock

class Vec3(tuple):

    def __new__(cls, x, y, z):
        return tuple.__new__(cls, (x, y, z))
    def __add__(self, other):
        return Vec3(self[0]+other[0], self[1]+other[1], self[2]+other[2])
    def __mul__(self, other):
        return Vec3(self[0]*other, self[1]*other, self[2]*other)
    def __rmul__(self, other):
        return Vec3(self[0]*other, self[1]*other, self[2]*other)
    def __sub__(self, other):
        return Vec3(self[0]-other[0], self[1]-other[1], self[2]-other[2])
    def __div__(self, other):
        other = float(other)
        return Vec3(self[0]/other, self[1]/other, self[2]/other)
    def __neg__(self):
        return Vec3(-self[0], -self[1], -self[2])
    def __repr__(self):
        return "(%.2f,%.2f,%.2f)" % self 


  
def triangle(laenge, stufe, f1, f2, f3):  # f1, f2, f3 colors of the vertices
    if stufe == 0:
        color((f1+f2+f3)/3)
        fill(1)
        for i in range(3):
            fd(laenge)
            lt(120)
        fill(0)
    else:
        c12 = (f1+f2)/2
        c13 = (f1+f3)/2
        c23 = (f2+f3)/2
        triangle(laenge / 2, stufe - 1, f1, c12, c13)
        fd(laenge)
        lt(120)
        triangle(laenge / 2, stufe - 1, f2, c23, c12)
        fd(laenge)
        lt(120)
        triangle(laenge / 2, stufe - 1, f3, c13, c23)
        fd(laenge)
        lt(120)

def main():
    reset()
    getpen().undobuffer.reset(1)
    sierp_size = 600
    colormode(255)
    speed(0)
    ht()
    pu()
    ##rt(90)                   ## die obligate Rechtsdrehung
    bk(sierp_size*0.5)
    lt(90)
    bk(sierp_size*0.4)
    rt(90)
    tracer(1,0)
    ## Hier nun anderen (Logo) Farbmodus nutzen:
    ta = clock()
    triangle(sierp_size, 6,
            Vec3(255.0,0,0), Vec3(0,255.0,0), Vec3(0,0,255.0))
    tb = clock()
    return "%.2f sec." % (tb-ta)

if __name__ == '__main__':
    main()
    mainloop()


## on my desktop-machine: approx. 1.5 sec.
#!/usr/bin/python
"""       xturtle-example-suite:

            xtx_spaceship.py

How does rocket propulsion work?
Play this game to learn about it.

The keys:

<space> starts a new game

Arrow-Keys:
<up> exerts a force (for a moment) and so
     accelerates spaceship in direction of
     its heading
<left>,<right> turns spaceship by 10 degrees

If the canvas has lost the focus, click into
it!

   Press STOP to exit the program!
   ===============================

Remark: this is a rather old script;
a rewrite possibly  on OOP basis
would make it clearer and/or cleaner.
"""
from turtle import *
from time import clock

FORCE_UNIT = 0.1  # change this to fine-tune
                  # control of the spaceship
                  # on your machine

smallfont  = ("Courier", 12, "bold")
normalfont = ("Courier", 18, "normal")
boldfont   = ("Courier", 18, "bold")

def scenery():
    global target
    designer.ht()
    designer.speed(0)
    designer.pu()
    designer.lt(180)
    designer.fd(240)
    designer.lt(90)
    designer.pensize(10)
    designer.pencolor("blue")
    designer.circle(120, 15)
    designer.pd()
    designer.circle(120, 330)
    designer.pu()
    designer.circle(120, 15)
    designer.lt(90)
    designer.fd(120)
    designer.dot(20, "yellow")
    target = designer.pos()

# spaceship is the "anonymous" turtle
def start():
    global vx, vy
    vx, vy = 0.0, 0.0
    reset()
    ht()
    speed(0)
    pensize(7)
    color("red", "orange")
    pu()
    fd(120)
    pd()
    lt(90)
    st()
    # hint for the player
    writer.reset()
    writer.ht()
    writer.speed(0)
    writer.up()
    writer.goto(-307,-220)
    writer.write('Move "spaceship" to yellow dot using 
up/left/right-arrow-keys!',
                 font = ("Courier", 12, "bold") )

def turnleft():
    lt(10)

def turnright():
    rt(10)

def rueckstoss():
    global vx, vy
    from math import sin, cos, pi
    alpha = heading() * pi / 180.0
    vx += FORCE_UNIT * cos(alpha)
    vy += FORCE_UNIT * sin(alpha)

def steps():
    global result
    x,y=pos()
    setpos(x+vx, y+vy)
    if (110 < distance(target) < 135 and
          8 < towards(0,0) < 352):
        result = "CRASH!" 
    elif distance(target) > 450:
        result = "ESCAPED!"
    elif distance(target) < 15:
        result = "SUCCESS!"
    if not result:
        ontimer(steps)
    
def go():
    global result
    result = None
    # Ein Spiel!
    startzeit = clock()
    steps()
    # ouptut result!
    writer.goto(-305,-200)
    writer.pencolor("red")
    writer.write(result, font=boldfont, move=1)
    if result == "SUCCESS!":
        zeit = clock() - startzeit
        writer.write(" (%2.2f s)" % zeit, font=boldfont, move=1)
    writer.pencolor("black")
    writer.write(" New game: spacebar", font=normalfont)

def spiel():
    if result:  # i.e. if game over
        start()
        go()

def main():
    global designer, writer
    designer = Turtle()
    writer = Turtle()
    tracer(1,0)
    shape("arrow")

    global result
    onkey(turnleft,"Left")
    onkey(turnright,"Right")
    onkey(rueckstoss, "Up")
    onkey(spiel, "space")
    #onscreenclick(listen)
    listen()
    result = "start"
    scenery()
    ontimer(spiel,500)
    delay(5)
    # a moment please to ...
    return "EVENTLOOP"

if __name__ == '__main__':
    msg = main()
    print msg
    mainloop()
_______________________________________________
Edu-sig mailing list
[email protected]
http://mail.python.org/mailman/listinfo/edu-sig

Reply via email to